@pyreon/hooks 0.0.2

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 ADDED
@@ -0,0 +1,617 @@
1
+ import { onMount, onUnmount } from "@pyreon/core";
2
+ import { computed, effect, signal, watch } from "@pyreon/reactivity";
3
+ import { useTheme } from "@pyreon/styler";
4
+ import { get, throttle } from "@pyreon/ui-core";
5
+
6
+ //#region src/useBreakpoint.ts
7
+ const defaultBreakpoints = {
8
+ xs: 0,
9
+ sm: 576,
10
+ md: 768,
11
+ lg: 992,
12
+ xl: 1200
13
+ };
14
+ /**
15
+ * Return the currently active breakpoint name as a reactive signal.
16
+ */
17
+ function useBreakpoint(breakpoints = defaultBreakpoints) {
18
+ const sorted = Object.entries(breakpoints).sort(([, a], [, b]) => a - b);
19
+ const active = signal(getActive(sorted));
20
+ let rafId;
21
+ function getActive(bps) {
22
+ if (typeof window === "undefined") return bps[0]?.[0] ?? "";
23
+ const w = window.innerWidth;
24
+ let result = bps[0]?.[0] ?? "";
25
+ for (const [name, min] of bps) if (w >= min) result = name;
26
+ else break;
27
+ return result;
28
+ }
29
+ function onResize() {
30
+ if (rafId !== void 0) cancelAnimationFrame(rafId);
31
+ rafId = requestAnimationFrame(() => {
32
+ const next = getActive(sorted);
33
+ if (next !== active.peek()) active.set(next);
34
+ });
35
+ }
36
+ onMount(() => {
37
+ window.addEventListener("resize", onResize);
38
+ });
39
+ onUnmount(() => {
40
+ window.removeEventListener("resize", onResize);
41
+ if (rafId !== void 0) cancelAnimationFrame(rafId);
42
+ });
43
+ return active;
44
+ }
45
+
46
+ //#endregion
47
+ //#region src/useClickOutside.ts
48
+ /**
49
+ * Call handler when a click occurs outside the target element.
50
+ */
51
+ function useClickOutside(getEl, handler) {
52
+ const listener = (e) => {
53
+ const el = getEl();
54
+ if (!el || el.contains(e.target)) return;
55
+ handler();
56
+ };
57
+ onMount(() => {
58
+ document.addEventListener("mousedown", listener, true);
59
+ document.addEventListener("touchstart", listener, true);
60
+ });
61
+ onUnmount(() => {
62
+ document.removeEventListener("mousedown", listener, true);
63
+ document.removeEventListener("touchstart", listener, true);
64
+ });
65
+ }
66
+
67
+ //#endregion
68
+ //#region src/useMediaQuery.ts
69
+ /**
70
+ * Subscribe to a CSS media query, returns a reactive boolean.
71
+ */
72
+ function useMediaQuery(query) {
73
+ const matches = signal(false);
74
+ let mql;
75
+ const onChange = (e) => {
76
+ matches.set(e.matches);
77
+ };
78
+ onMount(() => {
79
+ mql = window.matchMedia(query);
80
+ matches.set(mql.matches);
81
+ mql.addEventListener("change", onChange);
82
+ });
83
+ onUnmount(() => {
84
+ mql?.removeEventListener("change", onChange);
85
+ });
86
+ return matches;
87
+ }
88
+
89
+ //#endregion
90
+ //#region src/useColorScheme.ts
91
+ /**
92
+ * Returns the OS color scheme preference as 'light' or 'dark'.
93
+ */
94
+ function useColorScheme() {
95
+ const prefersDark = useMediaQuery("(prefers-color-scheme: dark)");
96
+ return computed(() => prefersDark() ? "dark" : "light");
97
+ }
98
+
99
+ //#endregion
100
+ //#region src/useControllableState.ts
101
+ /**
102
+ * Unified controlled/uncontrolled state pattern.
103
+ * When `value` is provided the component is controlled; otherwise
104
+ * internal state is used with `defaultValue` as the initial value.
105
+ * The `onChange` callback fires in both modes.
106
+ *
107
+ * Returns [getter, setter] where getter is a reactive function.
108
+ */
109
+ const useControllableState = ({ value, defaultValue, onChange }) => {
110
+ const internal = signal(defaultValue);
111
+ const onChangeFn = onChange;
112
+ const isControlled = value !== void 0;
113
+ const getter = () => isControlled ? value : internal();
114
+ const setValue = (next) => {
115
+ const current = isControlled ? value : internal();
116
+ const nextValue = typeof next === "function" ? next(current) : next;
117
+ if (!isControlled) internal.set(nextValue);
118
+ onChangeFn?.(nextValue);
119
+ };
120
+ return [getter, setValue];
121
+ };
122
+
123
+ //#endregion
124
+ //#region src/useDebouncedCallback.ts
125
+ /**
126
+ * Returns a debounced version of the callback.
127
+ * The returned function has `.cancel()` and `.flush()` methods.
128
+ * Always calls the latest callback (no stale closures).
129
+ * Cleans up on unmount.
130
+ */
131
+ const useDebouncedCallback = (callback, delay) => {
132
+ const currentCallback = callback;
133
+ let timer = null;
134
+ let lastArgs = null;
135
+ const cancel = () => {
136
+ if (timer != null) {
137
+ clearTimeout(timer);
138
+ timer = null;
139
+ }
140
+ lastArgs = null;
141
+ };
142
+ const flush = () => {
143
+ if (timer != null && lastArgs != null) {
144
+ clearTimeout(timer);
145
+ timer = null;
146
+ currentCallback(...lastArgs);
147
+ lastArgs = null;
148
+ }
149
+ };
150
+ const debounced = (...args) => {
151
+ lastArgs = args;
152
+ if (timer != null) clearTimeout(timer);
153
+ timer = setTimeout(() => {
154
+ timer = null;
155
+ currentCallback(...args);
156
+ lastArgs = null;
157
+ }, delay);
158
+ };
159
+ onUnmount(() => cancel());
160
+ return Object.assign(debounced, {
161
+ cancel,
162
+ flush
163
+ });
164
+ };
165
+
166
+ //#endregion
167
+ //#region src/useDebouncedValue.ts
168
+ /**
169
+ * Return a debounced version of a reactive value.
170
+ */
171
+ function useDebouncedValue(getter, delayMs) {
172
+ const debounced = signal(getter());
173
+ let timer;
174
+ effect(() => {
175
+ const val = getter();
176
+ if (timer !== void 0) clearTimeout(timer);
177
+ timer = setTimeout(() => {
178
+ debounced.set(val);
179
+ }, delayMs);
180
+ });
181
+ onUnmount(() => {
182
+ if (timer !== void 0) clearTimeout(timer);
183
+ });
184
+ return debounced;
185
+ }
186
+
187
+ //#endregion
188
+ //#region src/useElementSize.ts
189
+ /**
190
+ * Observe element dimensions reactively via ResizeObserver.
191
+ */
192
+ function useElementSize(getEl) {
193
+ const size = signal({
194
+ width: 0,
195
+ height: 0
196
+ });
197
+ let observer;
198
+ onMount(() => {
199
+ const el = getEl();
200
+ if (!el) return void 0;
201
+ observer = new ResizeObserver(([entry]) => {
202
+ if (!entry) return;
203
+ const { width, height } = entry.contentRect;
204
+ size.set({
205
+ width,
206
+ height
207
+ });
208
+ });
209
+ observer.observe(el);
210
+ const rect = el.getBoundingClientRect();
211
+ size.set({
212
+ width: rect.width,
213
+ height: rect.height
214
+ });
215
+ });
216
+ onUnmount(() => {
217
+ observer?.disconnect();
218
+ });
219
+ return size;
220
+ }
221
+
222
+ //#endregion
223
+ //#region src/useFocus.ts
224
+ /**
225
+ * Track focus state reactively.
226
+ */
227
+ function useFocus() {
228
+ const focused = signal(false);
229
+ return {
230
+ focused,
231
+ props: {
232
+ onFocus: () => focused.set(true),
233
+ onBlur: () => focused.set(false)
234
+ }
235
+ };
236
+ }
237
+
238
+ //#endregion
239
+ //#region src/useFocusTrap.ts
240
+ const FOCUSABLE = "a[href], button:not([disabled]), textarea:not([disabled]), input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex=\"-1\"])";
241
+ /**
242
+ * Trap Tab/Shift+Tab focus within a container element.
243
+ */
244
+ function useFocusTrap(getEl) {
245
+ const listener = (e) => {
246
+ if (e.key !== "Tab") return;
247
+ const el = getEl();
248
+ if (!el) return;
249
+ const focusable = Array.from(el.querySelectorAll(FOCUSABLE));
250
+ if (focusable.length === 0) return;
251
+ const first = focusable[0];
252
+ const last = focusable[focusable.length - 1];
253
+ if (e.shiftKey) {
254
+ if (document.activeElement === first) {
255
+ e.preventDefault();
256
+ last.focus();
257
+ }
258
+ } else if (document.activeElement === last) {
259
+ e.preventDefault();
260
+ first.focus();
261
+ }
262
+ };
263
+ onMount(() => {
264
+ document.addEventListener("keydown", listener);
265
+ });
266
+ onUnmount(() => {
267
+ document.removeEventListener("keydown", listener);
268
+ });
269
+ }
270
+
271
+ //#endregion
272
+ //#region src/useHover.ts
273
+ /**
274
+ * Track hover state reactively.
275
+ *
276
+ * @example
277
+ * const { hovered, props } = useHover()
278
+ * h('div', { ...props, class: () => hovered() ? 'active' : '' })
279
+ */
280
+ function useHover() {
281
+ const hovered = signal(false);
282
+ return {
283
+ hovered,
284
+ props: {
285
+ onMouseEnter: () => hovered.set(true),
286
+ onMouseLeave: () => hovered.set(false)
287
+ }
288
+ };
289
+ }
290
+
291
+ //#endregion
292
+ //#region src/useIntersection.ts
293
+ /**
294
+ * Observe element intersection reactively.
295
+ */
296
+ function useIntersection(getEl, options) {
297
+ const entry = signal(null);
298
+ let observer;
299
+ onMount(() => {
300
+ const el = getEl();
301
+ if (!el) return void 0;
302
+ observer = new IntersectionObserver(([e]) => {
303
+ if (e) entry.set(e);
304
+ }, options);
305
+ observer.observe(el);
306
+ });
307
+ onUnmount(() => {
308
+ observer?.disconnect();
309
+ });
310
+ return entry;
311
+ }
312
+
313
+ //#endregion
314
+ //#region src/useInterval.ts
315
+ /**
316
+ * Declarative `setInterval` with auto-cleanup.
317
+ * Pass `null` as `delay` to pause the interval.
318
+ * Always calls the latest callback (no stale closures).
319
+ */
320
+ const useInterval = (callback, delay) => {
321
+ const currentCallback = callback;
322
+ let intervalId = null;
323
+ const start = () => {
324
+ if (delay === null) return;
325
+ intervalId = setInterval(() => currentCallback(), delay);
326
+ };
327
+ const stop = () => {
328
+ if (intervalId != null) {
329
+ clearInterval(intervalId);
330
+ intervalId = null;
331
+ }
332
+ };
333
+ start();
334
+ onUnmount(() => stop());
335
+ };
336
+
337
+ //#endregion
338
+ //#region src/useIsomorphicLayoutEffect.ts
339
+ const useIsomorphicLayoutEffect = typeof window !== "undefined" ? onMount : onMount;
340
+
341
+ //#endregion
342
+ //#region src/useKeyboard.ts
343
+ /**
344
+ * Listen for a specific key press.
345
+ */
346
+ function useKeyboard(key, handler, options) {
347
+ const eventName = options?.event ?? "keydown";
348
+ const listener = (e) => {
349
+ const ke = e;
350
+ if (ke.key === key) handler(ke);
351
+ };
352
+ onMount(() => {
353
+ (options?.target ?? document).addEventListener(eventName, listener);
354
+ });
355
+ onUnmount(() => {
356
+ (options?.target ?? document).removeEventListener(eventName, listener);
357
+ });
358
+ }
359
+
360
+ //#endregion
361
+ //#region src/useLatest.ts
362
+ /**
363
+ * Returns a ref-like object that always holds the latest value.
364
+ * Useful to avoid stale closures in callbacks and effects.
365
+ *
366
+ * In Pyreon, since the component body runs once, this simply wraps
367
+ * the value in a mutable object. The caller is expected to call this
368
+ * once and update `.current` manually if needed, or pass a reactive
369
+ * getter to read the latest value.
370
+ */
371
+ const useLatest = (value) => {
372
+ return { current: value };
373
+ };
374
+
375
+ //#endregion
376
+ //#region src/useMergedRef.ts
377
+ /**
378
+ * Merges multiple refs (callback or object) into a single callback ref.
379
+ * Handles undefined, callback refs, and object refs with `.current`.
380
+ */
381
+ const useMergedRef = (...refs) => {
382
+ return (node) => {
383
+ for (const ref of refs) {
384
+ if (!ref) continue;
385
+ if (typeof ref === "function") ref(node);
386
+ else ref.current = node;
387
+ }
388
+ };
389
+ };
390
+
391
+ //#endregion
392
+ //#region src/usePrevious.ts
393
+ /**
394
+ * Track the previous value of a reactive getter.
395
+ * Returns undefined on first access.
396
+ */
397
+ function usePrevious(getter) {
398
+ const prev = signal(void 0);
399
+ let current;
400
+ effect(() => {
401
+ const next = getter();
402
+ prev.set(current);
403
+ current = next;
404
+ });
405
+ return prev;
406
+ }
407
+
408
+ //#endregion
409
+ //#region src/useReducedMotion.ts
410
+ /**
411
+ * Returns true when the user prefers reduced motion.
412
+ */
413
+ function useReducedMotion() {
414
+ return useMediaQuery("(prefers-reduced-motion: reduce)");
415
+ }
416
+
417
+ //#endregion
418
+ //#region src/useRootSize.ts
419
+ /**
420
+ * Returns `rootSize` from the theme context along with
421
+ * `pxToRem` and `remToPx` conversion utilities.
422
+ *
423
+ * Defaults to `16` when no rootSize is set in the theme.
424
+ */
425
+ const useRootSize = () => {
426
+ const rootSize = useTheme()?.rootSize ?? 16;
427
+ return {
428
+ rootSize,
429
+ pxToRem: (px) => `${px / rootSize}rem`,
430
+ remToPx: (rem) => rem * rootSize
431
+ };
432
+ };
433
+
434
+ //#endregion
435
+ //#region src/useScrollLock.ts
436
+ let lockCount = 0;
437
+ let savedOverflow = "";
438
+ /**
439
+ * Lock page scroll. Uses reference counting for concurrent locks.
440
+ * Returns an unlock function.
441
+ */
442
+ function useScrollLock() {
443
+ let isLocked = false;
444
+ const lock = () => {
445
+ if (isLocked) return;
446
+ isLocked = true;
447
+ if (lockCount === 0) {
448
+ savedOverflow = document.body.style.overflow;
449
+ document.body.style.overflow = "hidden";
450
+ }
451
+ lockCount++;
452
+ };
453
+ const unlock = () => {
454
+ if (!isLocked) return;
455
+ isLocked = false;
456
+ lockCount--;
457
+ if (lockCount === 0) document.body.style.overflow = savedOverflow;
458
+ };
459
+ onUnmount(() => {
460
+ if (isLocked) unlock();
461
+ });
462
+ return {
463
+ lock,
464
+ unlock
465
+ };
466
+ }
467
+
468
+ //#endregion
469
+ //#region src/useSpacing.ts
470
+ /**
471
+ * Returns a `spacing(n)` function that computes spacing values
472
+ * based on `rootSize` from the theme.
473
+ *
474
+ * @param base - Base spacing unit in px (defaults to `rootSize / 2`, i.e. 8px)
475
+ *
476
+ * @example
477
+ * ```ts
478
+ * const spacing = useSpacing()
479
+ * spacing(1) // "8px"
480
+ * spacing(2) // "16px"
481
+ * spacing(0.5) // "4px"
482
+ * ```
483
+ */
484
+ const useSpacing = (base) => {
485
+ const { rootSize } = useRootSize();
486
+ const unit = base ?? rootSize / 2;
487
+ return (multiplier) => `${unit * multiplier}px`;
488
+ };
489
+
490
+ //#endregion
491
+ //#region src/useThemeValue.ts
492
+ /**
493
+ * Deep-reads a value from the current theme by dot-separated path.
494
+ *
495
+ * @example
496
+ * ```ts
497
+ * const primary = useThemeValue<string>('colors.primary')
498
+ * const columns = useThemeValue<number>('grid.columns')
499
+ * ```
500
+ */
501
+ const useThemeValue = (path) => {
502
+ const theme = useTheme();
503
+ if (!theme) return void 0;
504
+ return get(theme, path);
505
+ };
506
+
507
+ //#endregion
508
+ //#region src/useThrottledCallback.ts
509
+ /**
510
+ * Returns a throttled version of the callback.
511
+ * Uses `throttle` from `@pyreon/ui-core`.
512
+ * Always calls the latest callback (no stale closures).
513
+ * Cleans up on unmount.
514
+ */
515
+ const useThrottledCallback = (callback, delay) => {
516
+ const currentCallback = callback;
517
+ const throttled = throttle((...args) => currentCallback(...args), delay);
518
+ onUnmount(() => throttled.cancel());
519
+ return throttled;
520
+ };
521
+
522
+ //#endregion
523
+ //#region src/useTimeout.ts
524
+ /**
525
+ * Declarative `setTimeout` with auto-cleanup.
526
+ * Pass `null` as `delay` to disable. Returns `reset` and `clear` controls.
527
+ * Always calls the latest callback (no stale closures).
528
+ */
529
+ const useTimeout = (callback, delay) => {
530
+ const currentCallback = callback;
531
+ let timer = null;
532
+ const clear = () => {
533
+ if (timer != null) {
534
+ clearTimeout(timer);
535
+ timer = null;
536
+ }
537
+ };
538
+ const reset = () => {
539
+ clear();
540
+ if (delay !== null) timer = setTimeout(() => {
541
+ timer = null;
542
+ currentCallback();
543
+ }, delay);
544
+ };
545
+ reset();
546
+ onUnmount(() => clear());
547
+ return {
548
+ reset,
549
+ clear
550
+ };
551
+ };
552
+
553
+ //#endregion
554
+ //#region src/useToggle.ts
555
+ /**
556
+ * Simple boolean toggle.
557
+ */
558
+ function useToggle(initial = false) {
559
+ const value = signal(initial);
560
+ return {
561
+ value,
562
+ toggle: () => value.update((v) => !v),
563
+ setTrue: () => value.set(true),
564
+ setFalse: () => value.set(false)
565
+ };
566
+ }
567
+
568
+ //#endregion
569
+ //#region src/useUpdateEffect.ts
570
+ /**
571
+ * Like `effect` but skips the initial value — only fires on updates.
572
+ *
573
+ * In Pyreon, this is implemented using `watch()` which already skips
574
+ * the initial value by default (immediate defaults to false).
575
+ *
576
+ * @param source - A reactive getter to watch
577
+ * @param callback - Called when source changes, receives (newVal, oldVal)
578
+ */
579
+ const useUpdateEffect = (source, callback) => {
580
+ const stop = watch(source, callback);
581
+ onUnmount(() => stop());
582
+ };
583
+
584
+ //#endregion
585
+ //#region src/useWindowResize.ts
586
+ /**
587
+ * Track window dimensions reactively with throttling.
588
+ */
589
+ function useWindowResize(throttleMs = 200) {
590
+ const size = signal({
591
+ width: typeof window !== "undefined" ? window.innerWidth : 0,
592
+ height: typeof window !== "undefined" ? window.innerHeight : 0
593
+ });
594
+ let timer;
595
+ function onResize() {
596
+ if (timer !== void 0) return;
597
+ timer = setTimeout(() => {
598
+ timer = void 0;
599
+ size.set({
600
+ width: window.innerWidth,
601
+ height: window.innerHeight
602
+ });
603
+ }, throttleMs);
604
+ }
605
+ onMount(() => {
606
+ window.addEventListener("resize", onResize);
607
+ });
608
+ onUnmount(() => {
609
+ window.removeEventListener("resize", onResize);
610
+ if (timer !== void 0) clearTimeout(timer);
611
+ });
612
+ return size;
613
+ }
614
+
615
+ //#endregion
616
+ 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 };
617
+ //# sourceMappingURL=index.js.map