@vitus-labs/hooks 2.0.0-alpha.9 → 2.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -1,6 +1,292 @@
1
- import { useCallback, useEffect, useRef, useState } from "react";
2
- import { throttle } from "@vitus-labs/core";
1
+ import { context, get, throttle } from "@vitus-labs/core";
2
+ import { useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
3
3
 
4
+ //#region src/useBreakpoint.ts
5
+ /**
6
+ * Returns the name of the currently active breakpoint from the
7
+ * unistyle/core theme context (e.g. `"xs"`, `"md"`, `"lg"`).
8
+ *
9
+ * Reads `theme.breakpoints` from the nearest `Provider` and
10
+ * subscribes to viewport changes via `matchMedia`.
11
+ *
12
+ * Returns `undefined` when no Provider or breakpoints are available.
13
+ */
14
+ const useBreakpoint = () => {
15
+ const breakpoints = useContext(context)?.theme?.breakpoints;
16
+ const sorted = useMemo(() => {
17
+ if (!breakpoints) return [];
18
+ return Object.entries(breakpoints).sort(([, a], [, b]) => a - b);
19
+ }, [breakpoints]);
20
+ const [current, setCurrent] = useState(() => {
21
+ if (sorted.length === 0) return void 0;
22
+ if (typeof window === "undefined") return sorted[0]?.[0];
23
+ const width = window.innerWidth;
24
+ let match = sorted[0]?.[0];
25
+ for (const [name, min] of sorted) if (width >= min) match = name;
26
+ return match;
27
+ });
28
+ useEffect(() => {
29
+ if (sorted.length === 0) return void 0;
30
+ let raf = 0;
31
+ const update = () => {
32
+ raf = 0;
33
+ const width = window.innerWidth;
34
+ let match = sorted[0]?.[0];
35
+ for (const [name, min] of sorted) if (width >= min) match = name;
36
+ setCurrent(match);
37
+ };
38
+ const onResize = () => {
39
+ if (raf === 0) raf = requestAnimationFrame(update);
40
+ };
41
+ window.addEventListener("resize", onResize, { passive: true });
42
+ return () => {
43
+ if (raf !== 0) cancelAnimationFrame(raf);
44
+ window.removeEventListener("resize", onResize);
45
+ };
46
+ }, [sorted]);
47
+ return current;
48
+ };
49
+
50
+ //#endregion
51
+ //#region src/useClickOutside.ts
52
+ /**
53
+ * Calls `handler` when a click (mousedown or touchstart) occurs
54
+ * outside the element referenced by `ref`.
55
+ */
56
+ const useClickOutside = (ref, handler) => {
57
+ const handlerRef = useRef(handler);
58
+ handlerRef.current = handler;
59
+ useEffect(() => {
60
+ const listener = (event) => {
61
+ const el = ref.current;
62
+ const target = event.target;
63
+ if (!el || !target || el.contains(target)) return;
64
+ handlerRef.current(event);
65
+ };
66
+ document.addEventListener("mousedown", listener);
67
+ document.addEventListener("touchstart", listener);
68
+ return () => {
69
+ document.removeEventListener("mousedown", listener);
70
+ document.removeEventListener("touchstart", listener);
71
+ };
72
+ }, [ref]);
73
+ };
74
+
75
+ //#endregion
76
+ //#region src/useMediaQuery.ts
77
+ /**
78
+ * Subscribes to a CSS media query and returns whether it currently matches.
79
+ * Uses `window.matchMedia` with an event listener for live updates.
80
+ */
81
+ const useMediaQuery = (query) => {
82
+ const [matches, setMatches] = useState(useCallback(() => typeof window !== "undefined" ? window.matchMedia(query).matches : false, [query]));
83
+ useEffect(() => {
84
+ const mql = window.matchMedia(query);
85
+ setMatches(mql.matches);
86
+ const handler = (e) => setMatches(e.matches);
87
+ mql.addEventListener("change", handler);
88
+ return () => mql.removeEventListener("change", handler);
89
+ }, [query]);
90
+ return matches;
91
+ };
92
+
93
+ //#endregion
94
+ //#region src/useColorScheme.ts
95
+ /**
96
+ * Returns the user's preferred color scheme (`"light"` or `"dark"`).
97
+ * Reacts to OS-level preference changes in real time.
98
+ * Pairs with rocketstyle's `mode` system.
99
+ */
100
+ const useColorScheme = () => {
101
+ return useMediaQuery("(prefers-color-scheme: dark)") ? "dark" : "light";
102
+ };
103
+
104
+ //#endregion
105
+ //#region src/useControllableState.ts
106
+ /**
107
+ * Unified controlled/uncontrolled state pattern.
108
+ * When `value` is provided the component is controlled; otherwise
109
+ * internal state is used with `defaultValue` as the initial value.
110
+ * The `onChange` callback fires in both modes.
111
+ */
112
+ const useControllableState = ({ value, defaultValue, onChange }) => {
113
+ const [internal, setInternal] = useState(defaultValue);
114
+ const onChangeRef = useRef(onChange);
115
+ onChangeRef.current = onChange;
116
+ const isControlled = value !== void 0;
117
+ const current = isControlled ? value : internal;
118
+ return [current, useCallback((next) => {
119
+ const nextValue = typeof next === "function" ? next(current) : next;
120
+ if (!isControlled) setInternal(nextValue);
121
+ onChangeRef.current?.(nextValue);
122
+ }, [current, isControlled])];
123
+ };
124
+
125
+ //#endregion
126
+ //#region src/useDebouncedCallback.ts
127
+ /**
128
+ * Returns a stable debounced version of the callback.
129
+ * The returned function has `.cancel()` and `.flush()` methods.
130
+ * Always calls the latest callback (no stale closures).
131
+ * Cleans up on unmount.
132
+ */
133
+ const useDebouncedCallback = (callback, delay) => {
134
+ const callbackRef = useRef(callback);
135
+ callbackRef.current = callback;
136
+ const timerRef = useRef(null);
137
+ const lastArgsRef = useRef(null);
138
+ const cancel = useCallback(() => {
139
+ if (timerRef.current != null) {
140
+ clearTimeout(timerRef.current);
141
+ timerRef.current = null;
142
+ }
143
+ lastArgsRef.current = null;
144
+ }, []);
145
+ const flush = useCallback(() => {
146
+ if (timerRef.current != null && lastArgsRef.current != null) {
147
+ clearTimeout(timerRef.current);
148
+ timerRef.current = null;
149
+ callbackRef.current(...lastArgsRef.current);
150
+ lastArgsRef.current = null;
151
+ }
152
+ }, []);
153
+ useEffect(() => cancel, [cancel]);
154
+ const debounced = useCallback((...args) => {
155
+ lastArgsRef.current = args;
156
+ if (timerRef.current != null) clearTimeout(timerRef.current);
157
+ timerRef.current = setTimeout(() => {
158
+ timerRef.current = null;
159
+ callbackRef.current(...args);
160
+ lastArgsRef.current = null;
161
+ }, delay);
162
+ }, [delay]);
163
+ return Object.assign(debounced, {
164
+ cancel,
165
+ flush
166
+ });
167
+ };
168
+
169
+ //#endregion
170
+ //#region src/useDebouncedValue.ts
171
+ /**
172
+ * Returns a debounced version of the value that only updates
173
+ * after `delay` ms of inactivity.
174
+ *
175
+ * @example
176
+ * ```ts
177
+ * const [search, setSearch] = useState('')
178
+ * const debouncedSearch = useDebouncedValue(search, 300)
179
+ * ```
180
+ */
181
+ const useDebouncedValue = (value, delay) => {
182
+ const [debounced, setDebounced] = useState(value);
183
+ useEffect(() => {
184
+ const id = setTimeout(() => setDebounced(value), delay);
185
+ return () => clearTimeout(id);
186
+ }, [value, delay]);
187
+ return debounced;
188
+ };
189
+
190
+ //#endregion
191
+ //#region src/useElementSize.ts
192
+ /**
193
+ * Tracks an element's `width` and `height` via `ResizeObserver`.
194
+ * Returns `[ref, { width, height }]` — pass `ref` as a callback ref.
195
+ */
196
+ const useElementSize = () => {
197
+ const [size, setSize] = useState({
198
+ width: 0,
199
+ height: 0
200
+ });
201
+ const observerRef = useRef(null);
202
+ return [useCallback((node) => {
203
+ if (observerRef.current) {
204
+ observerRef.current.disconnect();
205
+ observerRef.current = null;
206
+ }
207
+ if (!node || typeof ResizeObserver === "undefined") return;
208
+ const observer = new ResizeObserver((entries) => {
209
+ const entry = entries[0];
210
+ if (!entry) return;
211
+ const { width, height } = entry.contentRect;
212
+ setSize((prev) => prev.width === width && prev.height === height ? prev : {
213
+ width,
214
+ height
215
+ });
216
+ });
217
+ observer.observe(node);
218
+ observerRef.current = observer;
219
+ const rect = node.getBoundingClientRect();
220
+ setSize((prev) => prev.width === rect.width && prev.height === rect.height ? prev : {
221
+ width: rect.width,
222
+ height: rect.height
223
+ });
224
+ }, []), size];
225
+ };
226
+
227
+ //#endregion
228
+ //#region src/useFocus.ts
229
+ /**
230
+ * Simple focus-state hook that returns a boolean plus stable
231
+ * `onFocus`/`onBlur` handlers ready to spread onto an element.
232
+ */
233
+ const useFocus = (initial = false) => {
234
+ const [focused, setFocused] = useState(initial);
235
+ return {
236
+ focused,
237
+ onFocus: useCallback(() => setFocused(true), []),
238
+ onBlur: useCallback(() => setFocused(false), [])
239
+ };
240
+ };
241
+
242
+ //#endregion
243
+ //#region src/useFocusTrap.ts
244
+ const FOCUSABLE = "a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex=\"-1\"])";
245
+ const wrapFocus = (e, target) => {
246
+ if (!target) return;
247
+ e.preventDefault();
248
+ target.focus();
249
+ };
250
+ /**
251
+ * Traps keyboard focus within the referenced container.
252
+ * Tab and Shift+Tab cycle through focusable elements inside.
253
+ * Useful for modals, dialogs, and dropdown menus.
254
+ *
255
+ * Focusable elements are cached and only re-queried when DOM mutations
256
+ * inside the container add/remove nodes — not on every Tab keypress.
257
+ */
258
+ const useFocusTrap = (ref, enabled = true) => {
259
+ useEffect(() => {
260
+ if (!enabled) return void 0;
261
+ const container = ref.current;
262
+ if (!container) return void 0;
263
+ let focusable = null;
264
+ const refresh = () => {
265
+ focusable = container.querySelectorAll(FOCUSABLE);
266
+ };
267
+ refresh();
268
+ const observer = new MutationObserver(refresh);
269
+ observer.observe(container, {
270
+ childList: true,
271
+ subtree: true
272
+ });
273
+ const handler = (e) => {
274
+ if (e.key !== "Tab" || !focusable || focusable.length === 0) return;
275
+ const first = focusable[0];
276
+ const last = focusable[focusable.length - 1];
277
+ const active = document.activeElement;
278
+ if (e.shiftKey && active === first) wrapFocus(e, last);
279
+ else if (!e.shiftKey && active === last) wrapFocus(e, first);
280
+ };
281
+ document.addEventListener("keydown", handler);
282
+ return () => {
283
+ observer.disconnect();
284
+ document.removeEventListener("keydown", handler);
285
+ };
286
+ }, [ref, enabled]);
287
+ };
288
+
289
+ //#endregion
4
290
  //#region src/useHover.ts
5
291
  /**
6
292
  * Simple hover-state hook that returns a boolean plus stable
@@ -15,6 +301,299 @@ const useHover = (initial = false) => {
15
301
  };
16
302
  };
17
303
 
304
+ //#endregion
305
+ //#region src/useIntersection.ts
306
+ /**
307
+ * Observes an element's intersection with the viewport (or a root element).
308
+ * Returns `[ref, entry]` — pass `ref` as a callback ref.
309
+ */
310
+ const useIntersection = (options = {}) => {
311
+ const { threshold = 0, rootMargin = "0px", root = null } = options;
312
+ const [entry, setEntry] = useState(null);
313
+ const observerRef = useRef(null);
314
+ return [useCallback((node) => {
315
+ if (observerRef.current) {
316
+ observerRef.current.disconnect();
317
+ observerRef.current = null;
318
+ }
319
+ if (!node || typeof IntersectionObserver === "undefined") return;
320
+ const observer = new IntersectionObserver((entries) => {
321
+ setEntry(entries[0] ?? null);
322
+ }, {
323
+ threshold,
324
+ rootMargin,
325
+ root
326
+ });
327
+ observer.observe(node);
328
+ observerRef.current = observer;
329
+ }, [
330
+ threshold,
331
+ rootMargin,
332
+ root
333
+ ]), entry];
334
+ };
335
+
336
+ //#endregion
337
+ //#region src/useInterval.ts
338
+ /**
339
+ * Declarative `setInterval` with auto-cleanup.
340
+ * Pass `null` as `delay` to pause the interval.
341
+ * Always calls the latest callback (no stale closures).
342
+ */
343
+ const useInterval = (callback, delay) => {
344
+ const callbackRef = useRef(callback);
345
+ callbackRef.current = callback;
346
+ useEffect(() => {
347
+ if (delay === null) return void 0;
348
+ const id = setInterval(() => callbackRef.current(), delay);
349
+ return () => clearInterval(id);
350
+ }, [delay]);
351
+ };
352
+
353
+ //#endregion
354
+ //#region src/useIsomorphicLayoutEffect.ts
355
+ /**
356
+ * `useLayoutEffect` on the client, `useEffect` on the server.
357
+ * Avoids the React SSR warning about useLayoutEffect.
358
+ */
359
+ const useIsomorphicLayoutEffect = typeof window !== "undefined" ? useLayoutEffect : useEffect;
360
+
361
+ //#endregion
362
+ //#region src/useKeyboard.ts
363
+ /**
364
+ * Listens for a specific keyboard key and calls the handler.
365
+ * Matches `event.key` (e.g. `"Escape"`, `"Enter"`, `"a"`).
366
+ * Always calls the latest handler (no stale closures).
367
+ *
368
+ * @example
369
+ * ```ts
370
+ * useKeyboard('Escape', () => setOpen(false))
371
+ * ```
372
+ */
373
+ const useKeyboard = (key, handler) => {
374
+ const handlerRef = useRef(handler);
375
+ handlerRef.current = handler;
376
+ useEffect(() => {
377
+ const listener = (e) => {
378
+ if (e.key === key) handlerRef.current(e);
379
+ };
380
+ window.addEventListener("keydown", listener);
381
+ return () => window.removeEventListener("keydown", listener);
382
+ }, [key]);
383
+ };
384
+
385
+ //#endregion
386
+ //#region src/useLatest.ts
387
+ /**
388
+ * Returns a ref that always holds the latest value.
389
+ * Useful to avoid stale closures in callbacks and effects.
390
+ */
391
+ const useLatest = (value) => {
392
+ const ref = useRef(value);
393
+ ref.current = value;
394
+ return ref;
395
+ };
396
+
397
+ //#endregion
398
+ //#region src/useMergedRef.ts
399
+ /**
400
+ * Merges multiple refs (callback or object) into a single stable callback ref.
401
+ * Handles null, callback refs, and object refs with `.current`.
402
+ */
403
+ const useMergedRef = (...refs) => {
404
+ return useCallback((node) => {
405
+ for (const ref of refs) {
406
+ if (!ref) continue;
407
+ if (typeof ref === "function") ref(node);
408
+ else ref.current = node;
409
+ }
410
+ }, refs);
411
+ };
412
+
413
+ //#endregion
414
+ //#region src/usePrevious.ts
415
+ /**
416
+ * Returns the value from the previous render.
417
+ * Returns `undefined` on the first render.
418
+ */
419
+ const usePrevious = (value) => {
420
+ const ref = useRef(void 0);
421
+ useEffect(() => {
422
+ ref.current = value;
423
+ });
424
+ return ref.current;
425
+ };
426
+
427
+ //#endregion
428
+ //#region src/useReducedMotion.ts
429
+ /**
430
+ * Returns `true` when the user prefers reduced motion.
431
+ * Use to disable or simplify animations for accessibility.
432
+ */
433
+ const useReducedMotion = () => useMediaQuery("(prefers-reduced-motion: reduce)");
434
+
435
+ //#endregion
436
+ //#region src/useRootSize.ts
437
+ /**
438
+ * Returns `rootSize` from the theme context along with
439
+ * `pxToRem` and `remToPx` conversion utilities.
440
+ *
441
+ * Defaults to `16` when no Provider is mounted.
442
+ */
443
+ const useRootSize = () => {
444
+ const rootSize = useContext(context)?.theme?.rootSize ?? 16;
445
+ return useMemo(() => ({
446
+ rootSize,
447
+ pxToRem: (px) => `${px / rootSize}rem`,
448
+ remToPx: (rem) => rem * rootSize
449
+ }), [rootSize]);
450
+ };
451
+
452
+ //#endregion
453
+ //#region src/useScrollLock.ts
454
+ let lockCount = 0;
455
+ let originalOverflow;
456
+ /**
457
+ * Locks page scroll by setting `overflow: hidden` on `document.body`.
458
+ * Uses a reference counter so concurrent locks don't clobber each other.
459
+ */
460
+ const useScrollLock = (enabled) => {
461
+ useEffect(() => {
462
+ if (!enabled) return void 0;
463
+ if (lockCount === 0) originalOverflow = document.body.style.overflow;
464
+ lockCount++;
465
+ document.body.style.overflow = "hidden";
466
+ return () => {
467
+ lockCount--;
468
+ if (lockCount === 0) {
469
+ document.body.style.overflow = originalOverflow ?? "";
470
+ originalOverflow = void 0;
471
+ }
472
+ };
473
+ }, [enabled]);
474
+ };
475
+
476
+ //#endregion
477
+ //#region src/useSpacing.ts
478
+ /**
479
+ * Returns a `spacing(n)` function that computes spacing values
480
+ * based on `rootSize` from the theme.
481
+ *
482
+ * @param base - Base spacing unit in px (defaults to `rootSize / 2`, i.e. 8px)
483
+ *
484
+ * @example
485
+ * ```ts
486
+ * const spacing = useSpacing()
487
+ * spacing(1) // "8px"
488
+ * spacing(2) // "16px"
489
+ * spacing(0.5) // "4px"
490
+ * ```
491
+ */
492
+ const useSpacing = (base) => {
493
+ const { rootSize } = useRootSize();
494
+ const unit = base ?? rootSize / 2;
495
+ return useMemo(() => (multiplier) => `${unit * multiplier}px`, [unit]);
496
+ };
497
+
498
+ //#endregion
499
+ //#region src/useThemeValue.ts
500
+ /**
501
+ * Deep-reads a value from the current theme by dot-separated path.
502
+ *
503
+ * @example
504
+ * ```ts
505
+ * const primary = useThemeValue<string>('colors.primary')
506
+ * const columns = useThemeValue<number>('grid.columns')
507
+ * ```
508
+ */
509
+ const useThemeValue = (path) => {
510
+ const theme = useContext(context)?.theme;
511
+ if (!theme) return void 0;
512
+ return get(theme, path);
513
+ };
514
+
515
+ //#endregion
516
+ //#region src/useThrottledCallback.ts
517
+ /**
518
+ * Returns a stable throttled version of the callback.
519
+ * Uses `throttle` from `@vitus-labs/core`.
520
+ * Always calls the latest callback (no stale closures).
521
+ * Cleans up on unmount.
522
+ */
523
+ const useThrottledCallback = (callback, delay) => {
524
+ const callbackRef = useRef(callback);
525
+ callbackRef.current = callback;
526
+ const throttled = useMemo(() => throttle((...args) => callbackRef.current(...args), delay), [delay]);
527
+ useEffect(() => () => throttled.cancel(), [throttled]);
528
+ return throttled;
529
+ };
530
+
531
+ //#endregion
532
+ //#region src/useTimeout.ts
533
+ /**
534
+ * Declarative `setTimeout` with auto-cleanup.
535
+ * Pass `null` as `delay` to disable. Returns `reset` and `clear` controls.
536
+ * Always calls the latest callback (no stale closures).
537
+ */
538
+ const useTimeout = (callback, delay) => {
539
+ const callbackRef = useRef(callback);
540
+ callbackRef.current = callback;
541
+ const timerRef = useRef(null);
542
+ const clear = useCallback(() => {
543
+ if (timerRef.current != null) {
544
+ clearTimeout(timerRef.current);
545
+ timerRef.current = null;
546
+ }
547
+ }, []);
548
+ const reset = useCallback(() => {
549
+ clear();
550
+ if (delay !== null) timerRef.current = setTimeout(() => {
551
+ timerRef.current = null;
552
+ callbackRef.current();
553
+ }, delay);
554
+ }, [delay, clear]);
555
+ useEffect(() => {
556
+ reset();
557
+ return clear;
558
+ }, [reset, clear]);
559
+ return {
560
+ reset,
561
+ clear
562
+ };
563
+ };
564
+
565
+ //#endregion
566
+ //#region src/useToggle.ts
567
+ /**
568
+ * Boolean state with `toggle`, `setTrue`, and `setFalse` helpers.
569
+ * Returns `[value, toggle, setTrue, setFalse]`.
570
+ */
571
+ const useToggle = (initial = false) => {
572
+ const [value, setValue] = useState(initial);
573
+ return [
574
+ value,
575
+ useCallback(() => setValue((v) => !v), []),
576
+ useCallback(() => setValue(true), []),
577
+ useCallback(() => setValue(false), [])
578
+ ];
579
+ };
580
+
581
+ //#endregion
582
+ //#region src/useUpdateEffect.ts
583
+ /**
584
+ * Like `useEffect` but skips the initial mount — only fires on updates.
585
+ */
586
+ const useUpdateEffect = (effect, deps) => {
587
+ const mounted = useRef(false);
588
+ useEffect(() => {
589
+ if (!mounted.current) {
590
+ mounted.current = true;
591
+ return;
592
+ }
593
+ return effect();
594
+ }, deps);
595
+ };
596
+
18
597
  //#endregion
19
598
  //#region src/useWindowResize.ts
20
599
  /**
@@ -53,5 +632,5 @@ const useWindowResize = ({ throttleDelay = 200, onChange } = {}, { width = 0, he
53
632
  };
54
633
 
55
634
  //#endregion
56
- export { useHover, useWindowResize };
635
+ export { useBreakpoint, useClickOutside, useColorScheme, useControllableState, useDebouncedCallback, useDebouncedValue, useElementSize, useFocus, useFocusTrap, useHover, useIntersection, useInterval, useIsomorphicLayoutEffect, useKeyboard, useLatest, useMediaQuery, useMergedRef, usePrevious, useReducedMotion, useRootSize, useScrollLock, useSpacing, useThemeValue, useThrottledCallback, useTimeout, useToggle, useUpdateEffect, useWindowResize };
57
636
  //# sourceMappingURL=index.js.map