@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.
@@ -0,0 +1,435 @@
1
+ import { context, get, throttle } from "@vitus-labs/core";
2
+ import { useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
3
+ import { AccessibilityInfo, Appearance, Dimensions } from "react-native";
4
+
5
+ //#region src/useBreakpoint.native.ts
6
+ /**
7
+ * Returns the name of the currently active breakpoint from the
8
+ * unistyle/core theme context (e.g. `"xs"`, `"md"`, `"lg"`).
9
+ *
10
+ * Uses React Native's `Dimensions` API instead of `matchMedia`.
11
+ */
12
+ const useBreakpoint = () => {
13
+ const breakpoints = useContext(context)?.theme?.breakpoints;
14
+ const sorted = useMemo(() => {
15
+ if (!breakpoints) return [];
16
+ return Object.entries(breakpoints).sort(([, a], [, b]) => a - b);
17
+ }, [breakpoints]);
18
+ const getMatch = useCallback((width) => {
19
+ let match = sorted[0]?.[0];
20
+ for (const [name, min] of sorted) if (width >= min) match = name;
21
+ return match;
22
+ }, [sorted]);
23
+ const [current, setCurrent] = useState(() => {
24
+ if (sorted.length === 0) return void 0;
25
+ return getMatch(Dimensions.get("window").width);
26
+ });
27
+ useEffect(() => {
28
+ if (sorted.length === 0) return void 0;
29
+ const sub = Dimensions.addEventListener("change", ({ window }) => {
30
+ setCurrent(getMatch(window.width));
31
+ });
32
+ return () => sub.remove();
33
+ }, [sorted, getMatch]);
34
+ return current;
35
+ };
36
+
37
+ //#endregion
38
+ //#region src/useColorScheme.native.ts
39
+ const toScheme = (value) => value === "dark" ? "dark" : "light";
40
+ /**
41
+ * Returns the user's preferred color scheme (`"light"` or `"dark"`).
42
+ * Uses React Native's `Appearance` API and subscribes to changes.
43
+ */
44
+ const useColorScheme = () => {
45
+ const [scheme, setScheme] = useState(() => toScheme(Appearance.getColorScheme()));
46
+ useEffect(() => {
47
+ const sub = Appearance.addChangeListener(({ colorScheme }) => {
48
+ setScheme(toScheme(colorScheme));
49
+ });
50
+ return () => sub.remove();
51
+ }, []);
52
+ return scheme;
53
+ };
54
+
55
+ //#endregion
56
+ //#region src/useControllableState.ts
57
+ /**
58
+ * Unified controlled/uncontrolled state pattern.
59
+ * When `value` is provided the component is controlled; otherwise
60
+ * internal state is used with `defaultValue` as the initial value.
61
+ * The `onChange` callback fires in both modes.
62
+ */
63
+ const useControllableState = ({ value, defaultValue, onChange }) => {
64
+ const [internal, setInternal] = useState(defaultValue);
65
+ const onChangeRef = useRef(onChange);
66
+ onChangeRef.current = onChange;
67
+ const isControlled = value !== void 0;
68
+ const current = isControlled ? value : internal;
69
+ return [current, useCallback((next) => {
70
+ const nextValue = typeof next === "function" ? next(current) : next;
71
+ if (!isControlled) setInternal(nextValue);
72
+ onChangeRef.current?.(nextValue);
73
+ }, [current, isControlled])];
74
+ };
75
+
76
+ //#endregion
77
+ //#region src/useDebouncedCallback.ts
78
+ /**
79
+ * Returns a stable debounced version of the callback.
80
+ * The returned function has `.cancel()` and `.flush()` methods.
81
+ * Always calls the latest callback (no stale closures).
82
+ * Cleans up on unmount.
83
+ */
84
+ const useDebouncedCallback = (callback, delay) => {
85
+ const callbackRef = useRef(callback);
86
+ callbackRef.current = callback;
87
+ const timerRef = useRef(null);
88
+ const lastArgsRef = useRef(null);
89
+ const cancel = useCallback(() => {
90
+ if (timerRef.current != null) {
91
+ clearTimeout(timerRef.current);
92
+ timerRef.current = null;
93
+ }
94
+ lastArgsRef.current = null;
95
+ }, []);
96
+ const flush = useCallback(() => {
97
+ if (timerRef.current != null && lastArgsRef.current != null) {
98
+ clearTimeout(timerRef.current);
99
+ timerRef.current = null;
100
+ callbackRef.current(...lastArgsRef.current);
101
+ lastArgsRef.current = null;
102
+ }
103
+ }, []);
104
+ useEffect(() => cancel, [cancel]);
105
+ const debounced = useCallback((...args) => {
106
+ lastArgsRef.current = args;
107
+ if (timerRef.current != null) clearTimeout(timerRef.current);
108
+ timerRef.current = setTimeout(() => {
109
+ timerRef.current = null;
110
+ callbackRef.current(...args);
111
+ lastArgsRef.current = null;
112
+ }, delay);
113
+ }, [delay]);
114
+ return Object.assign(debounced, {
115
+ cancel,
116
+ flush
117
+ });
118
+ };
119
+
120
+ //#endregion
121
+ //#region src/useDebouncedValue.ts
122
+ /**
123
+ * Returns a debounced version of the value that only updates
124
+ * after `delay` ms of inactivity.
125
+ *
126
+ * @example
127
+ * ```ts
128
+ * const [search, setSearch] = useState('')
129
+ * const debouncedSearch = useDebouncedValue(search, 300)
130
+ * ```
131
+ */
132
+ const useDebouncedValue = (value, delay) => {
133
+ const [debounced, setDebounced] = useState(value);
134
+ useEffect(() => {
135
+ const id = setTimeout(() => setDebounced(value), delay);
136
+ return () => clearTimeout(id);
137
+ }, [value, delay]);
138
+ return debounced;
139
+ };
140
+
141
+ //#endregion
142
+ //#region src/useFocus.ts
143
+ /**
144
+ * Simple focus-state hook that returns a boolean plus stable
145
+ * `onFocus`/`onBlur` handlers ready to spread onto an element.
146
+ */
147
+ const useFocus = (initial = false) => {
148
+ const [focused, setFocused] = useState(initial);
149
+ return {
150
+ focused,
151
+ onFocus: useCallback(() => setFocused(true), []),
152
+ onBlur: useCallback(() => setFocused(false), [])
153
+ };
154
+ };
155
+
156
+ //#endregion
157
+ //#region src/useHover.ts
158
+ /**
159
+ * Simple hover-state hook that returns a boolean plus stable
160
+ * `onMouseEnter`/`onMouseLeave` handlers ready to spread onto an element.
161
+ */
162
+ const useHover = (initial = false) => {
163
+ const [hover, handleHover] = useState(initial);
164
+ return {
165
+ hover,
166
+ onMouseEnter: useCallback(() => handleHover(true), []),
167
+ onMouseLeave: useCallback(() => handleHover(false), [])
168
+ };
169
+ };
170
+
171
+ //#endregion
172
+ //#region src/useInterval.ts
173
+ /**
174
+ * Declarative `setInterval` with auto-cleanup.
175
+ * Pass `null` as `delay` to pause the interval.
176
+ * Always calls the latest callback (no stale closures).
177
+ */
178
+ const useInterval = (callback, delay) => {
179
+ const callbackRef = useRef(callback);
180
+ callbackRef.current = callback;
181
+ useEffect(() => {
182
+ if (delay === null) return void 0;
183
+ const id = setInterval(() => callbackRef.current(), delay);
184
+ return () => clearInterval(id);
185
+ }, [delay]);
186
+ };
187
+
188
+ //#endregion
189
+ //#region src/useIsomorphicLayoutEffect.ts
190
+ /**
191
+ * `useLayoutEffect` on the client, `useEffect` on the server.
192
+ * Avoids the React SSR warning about useLayoutEffect.
193
+ */
194
+ const useIsomorphicLayoutEffect = typeof window !== "undefined" ? useLayoutEffect : useEffect;
195
+
196
+ //#endregion
197
+ //#region src/useKeyboard.native.ts
198
+ /**
199
+ * No-op on React Native. Physical keyboard events are not reliably
200
+ * available across all RN platforms. Use `TextInput.onKeyPress` or
201
+ * a hardware keyboard library for specific use cases.
202
+ */
203
+ const useKeyboard = () => {};
204
+
205
+ //#endregion
206
+ //#region src/useLatest.ts
207
+ /**
208
+ * Returns a ref that always holds the latest value.
209
+ * Useful to avoid stale closures in callbacks and effects.
210
+ */
211
+ const useLatest = (value) => {
212
+ const ref = useRef(value);
213
+ ref.current = value;
214
+ return ref;
215
+ };
216
+
217
+ //#endregion
218
+ //#region src/useMergedRef.ts
219
+ /**
220
+ * Merges multiple refs (callback or object) into a single stable callback ref.
221
+ * Handles null, callback refs, and object refs with `.current`.
222
+ */
223
+ const useMergedRef = (...refs) => {
224
+ return useCallback((node) => {
225
+ for (const ref of refs) {
226
+ if (!ref) continue;
227
+ if (typeof ref === "function") ref(node);
228
+ else ref.current = node;
229
+ }
230
+ }, refs);
231
+ };
232
+
233
+ //#endregion
234
+ //#region src/usePrevious.ts
235
+ /**
236
+ * Returns the value from the previous render.
237
+ * Returns `undefined` on the first render.
238
+ */
239
+ const usePrevious = (value) => {
240
+ const ref = useRef(void 0);
241
+ useEffect(() => {
242
+ ref.current = value;
243
+ });
244
+ return ref.current;
245
+ };
246
+
247
+ //#endregion
248
+ //#region src/useReducedMotion.native.ts
249
+ /**
250
+ * Returns `true` when the user prefers reduced motion.
251
+ * Uses React Native's `AccessibilityInfo.isReduceMotionEnabled()`.
252
+ */
253
+ const useReducedMotion = () => {
254
+ const [reduced, setReduced] = useState(false);
255
+ useEffect(() => {
256
+ AccessibilityInfo.isReduceMotionEnabled().then(setReduced);
257
+ const sub = AccessibilityInfo.addEventListener("reduceMotionChanged", setReduced);
258
+ return () => sub.remove();
259
+ }, []);
260
+ return reduced;
261
+ };
262
+
263
+ //#endregion
264
+ //#region src/useRootSize.ts
265
+ /**
266
+ * Returns `rootSize` from the theme context along with
267
+ * `pxToRem` and `remToPx` conversion utilities.
268
+ *
269
+ * Defaults to `16` when no Provider is mounted.
270
+ */
271
+ const useRootSize = () => {
272
+ const rootSize = useContext(context)?.theme?.rootSize ?? 16;
273
+ return useMemo(() => ({
274
+ rootSize,
275
+ pxToRem: (px) => `${px / rootSize}rem`,
276
+ remToPx: (rem) => rem * rootSize
277
+ }), [rootSize]);
278
+ };
279
+
280
+ //#endregion
281
+ //#region src/useSpacing.ts
282
+ /**
283
+ * Returns a `spacing(n)` function that computes spacing values
284
+ * based on `rootSize` from the theme.
285
+ *
286
+ * @param base - Base spacing unit in px (defaults to `rootSize / 2`, i.e. 8px)
287
+ *
288
+ * @example
289
+ * ```ts
290
+ * const spacing = useSpacing()
291
+ * spacing(1) // "8px"
292
+ * spacing(2) // "16px"
293
+ * spacing(0.5) // "4px"
294
+ * ```
295
+ */
296
+ const useSpacing = (base) => {
297
+ const { rootSize } = useRootSize();
298
+ const unit = base ?? rootSize / 2;
299
+ return useMemo(() => (multiplier) => `${unit * multiplier}px`, [unit]);
300
+ };
301
+
302
+ //#endregion
303
+ //#region src/useThemeValue.ts
304
+ /**
305
+ * Deep-reads a value from the current theme by dot-separated path.
306
+ *
307
+ * @example
308
+ * ```ts
309
+ * const primary = useThemeValue<string>('colors.primary')
310
+ * const columns = useThemeValue<number>('grid.columns')
311
+ * ```
312
+ */
313
+ const useThemeValue = (path) => {
314
+ const theme = useContext(context)?.theme;
315
+ if (!theme) return void 0;
316
+ return get(theme, path);
317
+ };
318
+
319
+ //#endregion
320
+ //#region src/useThrottledCallback.ts
321
+ /**
322
+ * Returns a stable throttled version of the callback.
323
+ * Uses `throttle` from `@vitus-labs/core`.
324
+ * Always calls the latest callback (no stale closures).
325
+ * Cleans up on unmount.
326
+ */
327
+ const useThrottledCallback = (callback, delay) => {
328
+ const callbackRef = useRef(callback);
329
+ callbackRef.current = callback;
330
+ const throttled = useMemo(() => throttle((...args) => callbackRef.current(...args), delay), [delay]);
331
+ useEffect(() => () => throttled.cancel(), [throttled]);
332
+ return throttled;
333
+ };
334
+
335
+ //#endregion
336
+ //#region src/useTimeout.ts
337
+ /**
338
+ * Declarative `setTimeout` with auto-cleanup.
339
+ * Pass `null` as `delay` to disable. Returns `reset` and `clear` controls.
340
+ * Always calls the latest callback (no stale closures).
341
+ */
342
+ const useTimeout = (callback, delay) => {
343
+ const callbackRef = useRef(callback);
344
+ callbackRef.current = callback;
345
+ const timerRef = useRef(null);
346
+ const clear = useCallback(() => {
347
+ if (timerRef.current != null) {
348
+ clearTimeout(timerRef.current);
349
+ timerRef.current = null;
350
+ }
351
+ }, []);
352
+ const reset = useCallback(() => {
353
+ clear();
354
+ if (delay !== null) timerRef.current = setTimeout(() => {
355
+ timerRef.current = null;
356
+ callbackRef.current();
357
+ }, delay);
358
+ }, [delay, clear]);
359
+ useEffect(() => {
360
+ reset();
361
+ return clear;
362
+ }, [reset, clear]);
363
+ return {
364
+ reset,
365
+ clear
366
+ };
367
+ };
368
+
369
+ //#endregion
370
+ //#region src/useToggle.ts
371
+ /**
372
+ * Boolean state with `toggle`, `setTrue`, and `setFalse` helpers.
373
+ * Returns `[value, toggle, setTrue, setFalse]`.
374
+ */
375
+ const useToggle = (initial = false) => {
376
+ const [value, setValue] = useState(initial);
377
+ return [
378
+ value,
379
+ useCallback(() => setValue((v) => !v), []),
380
+ useCallback(() => setValue(true), []),
381
+ useCallback(() => setValue(false), [])
382
+ ];
383
+ };
384
+
385
+ //#endregion
386
+ //#region src/useUpdateEffect.ts
387
+ /**
388
+ * Like `useEffect` but skips the initial mount — only fires on updates.
389
+ */
390
+ const useUpdateEffect = (effect, deps) => {
391
+ const mounted = useRef(false);
392
+ useEffect(() => {
393
+ if (!mounted.current) {
394
+ mounted.current = true;
395
+ return;
396
+ }
397
+ return effect();
398
+ }, deps);
399
+ };
400
+
401
+ //#endregion
402
+ //#region src/useWindowResize.native.ts
403
+ /**
404
+ * Tracks the React Native window dimensions.
405
+ * Uses `Dimensions` API instead of `window.innerWidth/innerHeight`.
406
+ * The `throttleDelay` parameter is accepted for API compat but not used
407
+ * (RN dimension events fire infrequently).
408
+ */
409
+ const useWindowResize = ({ onChange } = {}, { width, height } = {}) => {
410
+ const [windowSize, setWindowSize] = useState(() => {
411
+ const dim = Dimensions.get("window");
412
+ return {
413
+ width: width ?? dim.width,
414
+ height: height ?? dim.height
415
+ };
416
+ });
417
+ const onChangeRef = useRef(onChange);
418
+ onChangeRef.current = onChange;
419
+ useEffect(() => {
420
+ const sub = Dimensions.addEventListener("change", ({ window }) => {
421
+ const sizes = {
422
+ width: window.width,
423
+ height: window.height
424
+ };
425
+ setWindowSize(sizes);
426
+ onChangeRef.current?.(sizes);
427
+ });
428
+ return () => sub.remove();
429
+ }, []);
430
+ return windowSize;
431
+ };
432
+
433
+ //#endregion
434
+ export { useBreakpoint, useColorScheme, useControllableState, useDebouncedCallback, useDebouncedValue, useFocus, useHover, useInterval, useIsomorphicLayoutEffect, useKeyboard, useLatest, useMergedRef, usePrevious, useReducedMotion, useRootSize, useSpacing, useThemeValue, useThrottledCallback, useTimeout, useToggle, useUpdateEffect, useWindowResize };
435
+ //# sourceMappingURL=vitus-labs-hooks.native.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vitus-labs/hooks",
3
- "version": "2.0.0-alpha.9+f2f47db",
3
+ "version": "2.0.0-beta.1",
4
4
  "license": "MIT",
5
5
  "author": "Vit Bokisch <vit@bokisch.cz>",
6
6
  "maintainers": [
@@ -10,10 +10,13 @@
10
10
  "sideEffects": false,
11
11
  "exports": {
12
12
  "source": "./src/index.ts",
13
+ "react-native": "./lib/vitus-labs-hooks.native.js",
13
14
  "import": "./lib/index.js",
14
15
  "types": "./lib/index.d.ts"
15
16
  },
16
17
  "types": "./lib/index.d.ts",
18
+ "react-native": "./lib/vitus-labs-hooks.native.js",
19
+ "main": "./lib/index.js",
17
20
  "files": [
18
21
  "lib",
19
22
  "!lib/**/*.map",
@@ -31,7 +34,8 @@
31
34
  "test:coverage": "vitest run --coverage",
32
35
  "test:watch": "vitest",
33
36
  "cover": "coveralls < .coverage/lcov.info",
34
- "typecheck": "tsc --noEmit"
37
+ "typecheck": "tsc --noEmit",
38
+ "version": "node ../../scripts/sync-peer-deps.mjs"
35
39
  },
36
40
  "publishConfig": {
37
41
  "access": "public"
@@ -48,14 +52,20 @@
48
52
  "node": ">= 18"
49
53
  },
50
54
  "peerDependencies": {
51
- "@vitus-labs/core": "^1.4.0",
52
- "react": ">= 19"
55
+ "@vitus-labs/core": "2.0.0-beta.1",
56
+ "react": ">= 19",
57
+ "react-native": ">= 0.76"
53
58
  },
54
- "devDependencies": {
55
- "@vitus-labs/core": "2.0.0-alpha.9+f2f47db",
56
- "@vitus-labs/tools-rolldown": "^1.6.0",
57
- "@vitus-labs/tools-storybook": "^1.6.0",
58
- "@vitus-labs/tools-typescript": "^1.6.0"
59
+ "peerDependenciesMeta": {
60
+ "react-native": {
61
+ "optional": true
62
+ }
59
63
  },
60
- "gitHead": "f2f47db887d6a846ee5f9e96f290c59cdde4772a"
64
+ "devDependencies": {
65
+ "@vitus-labs/core": "workspace:*",
66
+ "@vitus-labs/tools-rolldown": "2.2.0",
67
+ "@vitus-labs/tools-storybook": "2.2.0",
68
+ "@vitus-labs/tools-typescript": "2.1.0",
69
+ "react-native": ">=0.84.1"
70
+ }
61
71
  }
package/LICENSE DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2023-present Vit Bokisch
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.