@alessiofrittoli/react-hooks 3.7.0 → 3.8.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 CHANGED
@@ -1,23 +1,47 @@
1
- # React Hooks 🪝
1
+ <h1 align="center">React Hooks 🪝</h1>
2
+ <p align="center">
3
+ TypeScript React utility Hooks
4
+ </p>
5
+ <p align="center">
6
+ <a href="https://npmjs.org/package/@alessiofrittoli/react-hooks">
7
+ <img src="https://img.shields.io/npm/v/@alessiofrittoli/react-hooks" alt="Latest version"/>
8
+ </a>
9
+ <a href="https://coveralls.io/github/alessiofrittoli/react-hooks">
10
+ <img src="https://coveralls.io/repos/github/alessiofrittoli/react-hooks/badge.svg" alt="Test coverage"/>
11
+ </a>
12
+ <a href="https://socket.dev/npm/package/@alessiofrittoli/react-hooks/overview">
13
+ <img src="https://socket.dev/api/badge/npm/package/@alessiofrittoli/react-hooks" alt="Socket Security score"/>
14
+ </a>
15
+ <a href="https://npmjs.org/package/@alessiofrittoli/react-hooks">
16
+ <img src="https://img.shields.io/npm/dm/@alessiofrittoli/react-hooks.svg" alt="npm downloads"/>
17
+ </a>
18
+ <a href="https://bundlephobia.com/package/@alessiofrittoli/react-hooks">
19
+ <img src="https://badgen.net/bundlephobia/dependency-count/@alessiofrittoli/react-hooks" alt="Dependencies"/>
20
+ </a>
21
+ <a href="https://libraries.io/npm/%40alessiofrittoli%2Freact-hooks">
22
+ <img src="https://img.shields.io/librariesio/release/npm/@alessiofrittoli/react-hooks" alt="Dependencies status"/>
23
+ </a>
24
+ </p>
25
+ <p align="center">
26
+ <a href="https://bundlephobia.com/package/@alessiofrittoli/react-hooks">
27
+ <img src="https://badgen.net/bundlephobia/min/@alessiofrittoli/react-hooks" alt="minified"/>
28
+ </a>
29
+ <a href="https://bundlephobia.com/package/@alessiofrittoli/react-hooks">
30
+ <img src="https://badgen.net/bundlephobia/minzip/@alessiofrittoli/react-hooks" alt="minizipped"/>
31
+ </a>
32
+ <a href="https://bundlephobia.com/package/@alessiofrittoli/react-hooks">
33
+ <img src="https://badgen.net/bundlephobia/tree-shaking/@alessiofrittoli/react-hooks" alt="Tree shakable"/>
34
+ </a>
35
+ </p>
36
+ <p align="center">
37
+ <a href="https://github.com/sponsors/alessiofrittoli">
38
+ <img src="https://img.shields.io/static/v1?label=Fund%20this%20package&message=%E2%9D%A4&logo=GitHub&color=%23DB61A2" alt="Fund this package"/>
39
+ </a>
40
+ </p>
2
41
 
3
- [![NPM Latest Version][version-badge]][npm-url] [![Coverage Status][coverage-badge]][coverage-url] [![Socket Status][socket-badge]][socket-url] [![NPM Monthly Downloads][downloads-badge]][npm-url] [![Dependencies][deps-badge]][deps-url]
4
-
5
- [![GitHub Sponsor][sponsor-badge]][sponsor-url]
6
-
7
- [version-badge]: https://img.shields.io/npm/v/%40alessiofrittoli%2Freact-hooks
8
- [npm-url]: https://npmjs.org/package/%40alessiofrittoli%2Freact-hooks
9
- [coverage-badge]: https://coveralls.io/repos/github/alessiofrittoli/react-hooks/badge.svg
10
- [coverage-url]: https://coveralls.io/github/alessiofrittoli/react-hooks
11
- [socket-badge]: https://socket.dev/api/badge/npm/package/@alessiofrittoli/react-hooks
12
- [socket-url]: https://socket.dev/npm/package/@alessiofrittoli/react-hooks/overview
13
- [downloads-badge]: https://img.shields.io/npm/dm/%40alessiofrittoli%2Freact-hooks.svg
14
- [deps-badge]: https://img.shields.io/librariesio/release/npm/%40alessiofrittoli%2Freact-hooks
15
- [deps-url]: https://libraries.io/npm/%40alessiofrittoli%2Freact-hooks
16
42
  [sponsor-badge]: https://img.shields.io/static/v1?label=Fund%20this%20package&message=%E2%9D%A4&logo=GitHub&color=%23DB61A2
17
43
  [sponsor-url]: https://github.com/sponsors/alessiofrittoli
18
44
 
19
- ## TypeScript React utility Hooks
20
-
21
45
  ### Table of Contents
22
46
 
23
47
  - [Getting started](#getting-started)
@@ -1284,7 +1308,7 @@ const AsyncStartExample: React.FC = () => {
1284
1308
  await new Promise((resolve) => setTimeout(resolve, 1000)); // Simulate delay
1285
1309
  console.log("Async task completed. `inView` will now be updated.");
1286
1310
  },
1287
- []
1311
+ [],
1288
1312
  );
1289
1313
 
1290
1314
  const { inView } = useInView(targetRef, { onIntersect });
@@ -1947,7 +1971,7 @@ const items: Item[] = [
1947
1971
 
1948
1972
  const MyComponent: React.FC = () => {
1949
1973
  const { setSelection, select, groupSelect, isSelected } = useSelection(
1950
- useMemo(() => items.map((item) => item.id), [])
1974
+ useMemo(() => items.map((item) => item.id), []),
1951
1975
  );
1952
1976
 
1953
1977
  const clickHandler = useCallback(
@@ -1959,10 +1983,10 @@ const MyComponent: React.FC = () => {
1959
1983
  return select(id); // toggle single item in selection
1960
1984
  }
1961
1985
  setSelection(
1962
- (prev) => (prev.includes(id) ? [] : [id]) // toggle single item selection
1986
+ (prev) => (prev.includes(id) ? [] : [id]), // toggle single item selection
1963
1987
  );
1964
1988
  },
1965
- [select, groupSelect, setSelection]
1989
+ [select, groupSelect, setSelection],
1966
1990
  );
1967
1991
 
1968
1992
  return (
@@ -2147,7 +2171,7 @@ const MyComponent: React.FC = () => {
2147
2171
  useCallback(() => {
2148
2172
  console.log("tick timer");
2149
2173
  }, []),
2150
- { delay: 1000 }
2174
+ { delay: 1000 },
2151
2175
  );
2152
2176
 
2153
2177
  return <button onClick={stop}>Stop timer</button>;
@@ -2174,7 +2198,7 @@ const MyComponent: React.FC = () => {
2174
2198
  autoplay: false,
2175
2199
  runOnStart: true,
2176
2200
  updateState: true,
2177
- }
2201
+ },
2178
2202
  );
2179
2203
 
2180
2204
  return (
@@ -2249,7 +2273,7 @@ const MyComponent: React.FC = () => {
2249
2273
  useCallback(() => {
2250
2274
  console.log("tick timer");
2251
2275
  }, []),
2252
- { delay: 1000 }
2276
+ { delay: 1000 },
2253
2277
  );
2254
2278
  };
2255
2279
  ```
@@ -2291,15 +2315,17 @@ The `Timeout` is automatically cancelled on unmount.
2291
2315
 
2292
2316
  <summary style="cursor:pointer">Parameters</summary>
2293
2317
 
2294
- | Parameter | Type | Default | Description |
2295
- | --------------------- | ----------------- | ------- | ----------------------------------------------------------------- |
2296
- | `callback` | `TimerHandler<T>` | - | The function to call when the timer elapses. |
2297
- | `options` | `TimerOptions<T>` | - | (Optional) An object defining custom timer options. |
2298
- | `options.delay` | `number` | `1` | The number of milliseconds to wait before calling the `callback`. |
2299
- | `options.args` | `T` | - | Optional arguments to pass when the `callback` is called. |
2300
- | `options.autoplay` | `boolean` | `true` | Indicates whether auto start the timer. |
2301
- | `options.updateState` | `boolean` | `false` | Whether to update React state about Timer running status. |
2302
- | `options.runOnStart` | `boolean` | `false` | Indicates whether to execute the callback when timer starts. |
2318
+ | Parameter | Type | Default | Description |
2319
+ | --------------------- | ----------------- | ------- | --------------------------------------------------------------------------- |
2320
+ | `callback` | `TimerHandler<T>` | - | The function to call when the timer elapses. |
2321
+ | `options` | `TimerOptions<T>` | - | (Optional) An object defining custom timer options. |
2322
+ | `options.delay` | `number` | `1` | The number of milliseconds to wait before calling the `callback`. |
2323
+ | `options.args` | `T` | - | Optional arguments to pass when the `callback` is called. |
2324
+ | `options.autoplay` | `boolean` | `true` | Indicates whether auto start the timer. |
2325
+ | `options.updateState` | `boolean` | `false` | Whether to update React state about Timer running status. |
2326
+ | | | | Passing a `callback` is optional if `updateState` |
2327
+ | | | | has been set to `true` if you're only interested about running timer state. |
2328
+ | `options.runOnStart` | `boolean` | `false` | Indicates whether to execute the callback when timer starts. |
2303
2329
 
2304
2330
  </details>
2305
2331
 
@@ -2341,7 +2367,7 @@ const MyComponent: React.FC = () => {
2341
2367
  useCallback(() => {
2342
2368
  console.log("tick timer");
2343
2369
  }, []),
2344
- { delay: 1000 }
2370
+ { delay: 1000 },
2345
2371
  );
2346
2372
 
2347
2373
  return <button onClick={stop}>Stop timer</button>;
@@ -2368,7 +2394,7 @@ const MyComponent: React.FC = () => {
2368
2394
  autoplay: false,
2369
2395
  runOnStart: true,
2370
2396
  updateState: true,
2371
- }
2397
+ },
2372
2398
  );
2373
2399
 
2374
2400
  return (
@@ -2384,6 +2410,36 @@ const MyComponent: React.FC = () => {
2384
2410
 
2385
2411
  ---
2386
2412
 
2413
+ ##### Rely on time state only
2414
+
2415
+ You can pass `undefined` instead of a callback if you're interested only in timer running states.
2416
+
2417
+ ```tsx
2418
+ "use client";
2419
+
2420
+ import { useCallback } from "react";
2421
+ import { useTimeout } from "@alessiofrittoli/react-hooks";
2422
+
2423
+ const MyComponent: React.FC = () => {
2424
+ const { isActive, start, stop } = useTimeout(undefined, {
2425
+ delay: 1000,
2426
+ autoplay: false,
2427
+ updateState: true,
2428
+ });
2429
+
2430
+ return (
2431
+ <>
2432
+ {!isActive && <button onClick={start}>Start timer</button>}
2433
+ {isActive && <button onClick={stop}>Stop timer</button>}
2434
+ </>
2435
+ );
2436
+ };
2437
+ ```
2438
+
2439
+ </details>
2440
+
2441
+ ---
2442
+
2387
2443
  #### `useLightTimeout`
2388
2444
 
2389
2445
  Schedules execution of a one-time `callback` after `delay` milliseconds.
@@ -2432,7 +2488,7 @@ const MyComponent: React.FC = () => {
2432
2488
  useCallback(() => {
2433
2489
  console.log("tick timer");
2434
2490
  }, []),
2435
- { delay: 1000 }
2491
+ { delay: 1000 },
2436
2492
  );
2437
2493
  };
2438
2494
  ```
package/dist/index.d.mts CHANGED
@@ -1,7 +1,6 @@
1
- import * as react from 'react';
2
1
  import { DeferredTask } from '@alessiofrittoli/web-utils';
3
- import * as _alessiofrittoli_math_utils_helpers from '@alessiofrittoli/math-utils/helpers';
4
- import { PaginateOptions } from '@alessiofrittoli/math-utils/helpers';
2
+ import * as _alessiofrittoli_math_utils from '@alessiofrittoli/math-utils';
3
+ import { PaginateOptions } from '@alessiofrittoli/math-utils';
5
4
 
6
5
  type Value<T> = T | undefined | null;
7
6
  type SetValue<T> = React.Dispatch<React.SetStateAction<T>>;
@@ -20,7 +19,7 @@ declare const useStorage: <T = string>(key: string, initial?: T, type?: "local"
20
19
  * @param key The local storage item key.
21
20
  * @param initial The local storage item initial value.
22
21
  */
23
- declare const useLocalStorage: <T = string>(key: string, initial?: T) => [T | null | undefined, (value: react.SetStateAction<T | null | undefined>) => void];
22
+ declare const useLocalStorage: <T = string>(key: string, initial?: T) => [Value<T>, SetValue<Value<T>>];
24
23
 
25
24
  /**
26
25
  * useSessionStorage hook.
@@ -28,7 +27,7 @@ declare const useLocalStorage: <T = string>(key: string, initial?: T) => [T | nu
28
27
  * @param key The session item key.
29
28
  * @param initial The session item initial value.
30
29
  */
31
- declare const useSessionStorage: <T = string>(key: string, initial?: T) => [T | null | undefined, (value: react.SetStateAction<T | null | undefined>) => void];
30
+ declare const useSessionStorage: <T = string>(key: string, initial?: T) => [Value<T>, SetValue<Value<T>>];
32
31
 
33
32
  type Connection = 'online' | 'offline';
34
33
  declare const getState: (online: boolean) => "online" | "offline";
@@ -1111,7 +1110,7 @@ declare const useIsFirstRender: () => boolean;
1111
1110
  * @param options An object defining pagination input data. See {@link PaginateOptions} for more information.
1112
1111
  * @returns A memoized object containing pagination informations based on the given options.
1113
1112
  */
1114
- declare const usePagination: (options?: PaginateOptions) => _alessiofrittoli_math_utils_helpers.Pagination;
1113
+ declare const usePagination: (options?: PaginateOptions) => _alessiofrittoli_math_utils.Pagination;
1115
1114
 
1116
1115
  /**
1117
1116
  * Check if the given `entry` is in the selection.
@@ -1473,7 +1472,7 @@ declare function useIntervalWhenVisible<T extends readonly unknown[]>(callback:
1473
1472
  *
1474
1473
  * @returns An object with timer utilities. See {@link StateTimerReturnType} for more info.
1475
1474
  */
1476
- declare function useTimeout<T extends readonly unknown[]>(callback: TimerHandler<T>, options?: StateTimerOptions<T>): StateTimerReturnType;
1475
+ declare function useTimeout<T extends readonly unknown[]>(callback?: TimerHandler<T>, options?: StateTimerOptions<T>): StateTimerReturnType;
1477
1476
  /**
1478
1477
  * Schedules execution of a one-time `callback` after `delay` milliseconds.
1479
1478
  *
@@ -1523,4 +1522,4 @@ declare function useTimeout<T extends readonly unknown[]>(callback: TimerHandler
1523
1522
  */
1524
1523
  declare const useLightTimeout: <T extends readonly unknown[]>(callback: TimerHandler<T>, options?: BasicTimerOptions<T>) => void;
1525
1524
 
1526
- export { type AddEventListenerOptions, type BasicTimerOptions, type ChangeHandler, type CommonListenerOptions, type Connection, type CustomEventListenerOptions, type DocumentEventListener, type DocumentListenerOptions, type ElementEventListener, type ElementListenerOptions, type GroupSelectHandler, type InputState, type InputType, type IntersectionState, type IsSelectedHandler, type ListenerOptions, type MarginType, type MarginValue, type MediaQueryChangeListener, type MediaQueryEventListener, type MediaQueryListenerOptions, type OnChangeHandler, type OnIntersectHandler, type OnIntersectStateHandler, type OnWakeLockRequestError, type ParseValueHandler, type ResetSelectionHandler, type SelectAllHandler, type SelectHandler, type SetSelectionHandler, type StartTimer, type StateDisabledUseDocumentVisibilityOptions, type StateTimerOptions, type StateTimerReturnType, type StopTimer, type TimerHandler, type TimerId, type TimerOptions, type TimerReturnType, type UseConnectionReturnType, type UseDarkModeOptions, type UseDarkModeOutput, type UseDocumentVisibilityOptions, type UseInViewOptions, type UseInViewReturnType, type UseInputOptions, type UseInputOutput, type UseIntervalWhenVisibleReturnType, type UseIntervalWhenVisibleStateReturnType, type UseMediaQueryOptions, type UseMediaQueryStateOptions, type UseSelectionReturnType, type UseWakeLock, type UseWakeLockBase, type UseWakeLockOptions, type ValidateValueHandler, type VisibilityChangeHandler, type WindowEventListener, type WindowListenerOptions, getState, useConnection, useDarkMode, useDebounce, useDeferCallback, useDocumentVisibility, useEffectOnce, useEventListener, useFocusTrap, useInView, useInput, useInterval, useIntervalWhenVisible, useIsClient, useIsFirstRender, useIsPortrait, useIsTouchDevice, useLightInterval, useLightTimeout, useLocalStorage, useMediaQuery, usePagination, useScrollBlock, useSelection, useSessionStorage, useStorage, useTimeout, useUpdateEffect, useWakeLock };
1525
+ export { type AddEventListenerOptions, type BasicTimerOptions, type ChangeHandler, type CommonListenerOptions, type Connection, type CustomEventListenerOptions, type DocumentEventListener, type DocumentListenerOptions, type ElementEventListener, type ElementListenerOptions, type GroupSelectHandler, type InputState, type InputType, type IntersectionState, type IsSelectedHandler, type ListenerOptions, type MarginType, type MarginValue, type MediaQueryChangeListener, type MediaQueryEventListener, type MediaQueryListenerOptions, type OnChangeHandler, type OnIntersectHandler, type OnIntersectStateHandler, type OnWakeLockRequestError, type ParseValueHandler, type ResetSelectionHandler, type SelectAllHandler, type SelectHandler, type SetSelectionHandler, type SetValue, type StartTimer, type StateDisabledUseDocumentVisibilityOptions, type StateTimerOptions, type StateTimerReturnType, type StopTimer, type TimerHandler, type TimerId, type TimerOptions, type TimerReturnType, type UseConnectionReturnType, type UseDarkModeOptions, type UseDarkModeOutput, type UseDocumentVisibilityOptions, type UseInViewOptions, type UseInViewReturnType, type UseInputOptions, type UseInputOutput, type UseIntervalWhenVisibleReturnType, type UseIntervalWhenVisibleStateReturnType, type UseMediaQueryOptions, type UseMediaQueryStateOptions, type UseSelectionReturnType, type UseWakeLock, type UseWakeLockBase, type UseWakeLockOptions, type ValidateValueHandler, type Value, type VisibilityChangeHandler, type WindowEventListener, type WindowListenerOptions, getState, useConnection, useDarkMode, useDebounce, useDeferCallback, useDocumentVisibility, useEffectOnce, useEventListener, useFocusTrap, useInView, useInput, useInterval, useIntervalWhenVisible, useIsClient, useIsFirstRender, useIsPortrait, useIsTouchDevice, useLightInterval, useLightTimeout, useLocalStorage, useMediaQuery, usePagination, useScrollBlock, useSelection, useSessionStorage, useStorage, useTimeout, useUpdateEffect, useWakeLock };
package/dist/index.d.ts CHANGED
@@ -1,7 +1,6 @@
1
- import * as react from 'react';
2
1
  import { DeferredTask } from '@alessiofrittoli/web-utils';
3
- import * as _alessiofrittoli_math_utils_helpers from '@alessiofrittoli/math-utils/helpers';
4
- import { PaginateOptions } from '@alessiofrittoli/math-utils/helpers';
2
+ import * as _alessiofrittoli_math_utils from '@alessiofrittoli/math-utils';
3
+ import { PaginateOptions } from '@alessiofrittoli/math-utils';
5
4
 
6
5
  type Value<T> = T | undefined | null;
7
6
  type SetValue<T> = React.Dispatch<React.SetStateAction<T>>;
@@ -20,7 +19,7 @@ declare const useStorage: <T = string>(key: string, initial?: T, type?: "local"
20
19
  * @param key The local storage item key.
21
20
  * @param initial The local storage item initial value.
22
21
  */
23
- declare const useLocalStorage: <T = string>(key: string, initial?: T) => [T | null | undefined, (value: react.SetStateAction<T | null | undefined>) => void];
22
+ declare const useLocalStorage: <T = string>(key: string, initial?: T) => [Value<T>, SetValue<Value<T>>];
24
23
 
25
24
  /**
26
25
  * useSessionStorage hook.
@@ -28,7 +27,7 @@ declare const useLocalStorage: <T = string>(key: string, initial?: T) => [T | nu
28
27
  * @param key The session item key.
29
28
  * @param initial The session item initial value.
30
29
  */
31
- declare const useSessionStorage: <T = string>(key: string, initial?: T) => [T | null | undefined, (value: react.SetStateAction<T | null | undefined>) => void];
30
+ declare const useSessionStorage: <T = string>(key: string, initial?: T) => [Value<T>, SetValue<Value<T>>];
32
31
 
33
32
  type Connection = 'online' | 'offline';
34
33
  declare const getState: (online: boolean) => "online" | "offline";
@@ -1111,7 +1110,7 @@ declare const useIsFirstRender: () => boolean;
1111
1110
  * @param options An object defining pagination input data. See {@link PaginateOptions} for more information.
1112
1111
  * @returns A memoized object containing pagination informations based on the given options.
1113
1112
  */
1114
- declare const usePagination: (options?: PaginateOptions) => _alessiofrittoli_math_utils_helpers.Pagination;
1113
+ declare const usePagination: (options?: PaginateOptions) => _alessiofrittoli_math_utils.Pagination;
1115
1114
 
1116
1115
  /**
1117
1116
  * Check if the given `entry` is in the selection.
@@ -1473,7 +1472,7 @@ declare function useIntervalWhenVisible<T extends readonly unknown[]>(callback:
1473
1472
  *
1474
1473
  * @returns An object with timer utilities. See {@link StateTimerReturnType} for more info.
1475
1474
  */
1476
- declare function useTimeout<T extends readonly unknown[]>(callback: TimerHandler<T>, options?: StateTimerOptions<T>): StateTimerReturnType;
1475
+ declare function useTimeout<T extends readonly unknown[]>(callback?: TimerHandler<T>, options?: StateTimerOptions<T>): StateTimerReturnType;
1477
1476
  /**
1478
1477
  * Schedules execution of a one-time `callback` after `delay` milliseconds.
1479
1478
  *
@@ -1523,4 +1522,4 @@ declare function useTimeout<T extends readonly unknown[]>(callback: TimerHandler
1523
1522
  */
1524
1523
  declare const useLightTimeout: <T extends readonly unknown[]>(callback: TimerHandler<T>, options?: BasicTimerOptions<T>) => void;
1525
1524
 
1526
- export { type AddEventListenerOptions, type BasicTimerOptions, type ChangeHandler, type CommonListenerOptions, type Connection, type CustomEventListenerOptions, type DocumentEventListener, type DocumentListenerOptions, type ElementEventListener, type ElementListenerOptions, type GroupSelectHandler, type InputState, type InputType, type IntersectionState, type IsSelectedHandler, type ListenerOptions, type MarginType, type MarginValue, type MediaQueryChangeListener, type MediaQueryEventListener, type MediaQueryListenerOptions, type OnChangeHandler, type OnIntersectHandler, type OnIntersectStateHandler, type OnWakeLockRequestError, type ParseValueHandler, type ResetSelectionHandler, type SelectAllHandler, type SelectHandler, type SetSelectionHandler, type StartTimer, type StateDisabledUseDocumentVisibilityOptions, type StateTimerOptions, type StateTimerReturnType, type StopTimer, type TimerHandler, type TimerId, type TimerOptions, type TimerReturnType, type UseConnectionReturnType, type UseDarkModeOptions, type UseDarkModeOutput, type UseDocumentVisibilityOptions, type UseInViewOptions, type UseInViewReturnType, type UseInputOptions, type UseInputOutput, type UseIntervalWhenVisibleReturnType, type UseIntervalWhenVisibleStateReturnType, type UseMediaQueryOptions, type UseMediaQueryStateOptions, type UseSelectionReturnType, type UseWakeLock, type UseWakeLockBase, type UseWakeLockOptions, type ValidateValueHandler, type VisibilityChangeHandler, type WindowEventListener, type WindowListenerOptions, getState, useConnection, useDarkMode, useDebounce, useDeferCallback, useDocumentVisibility, useEffectOnce, useEventListener, useFocusTrap, useInView, useInput, useInterval, useIntervalWhenVisible, useIsClient, useIsFirstRender, useIsPortrait, useIsTouchDevice, useLightInterval, useLightTimeout, useLocalStorage, useMediaQuery, usePagination, useScrollBlock, useSelection, useSessionStorage, useStorage, useTimeout, useUpdateEffect, useWakeLock };
1525
+ export { type AddEventListenerOptions, type BasicTimerOptions, type ChangeHandler, type CommonListenerOptions, type Connection, type CustomEventListenerOptions, type DocumentEventListener, type DocumentListenerOptions, type ElementEventListener, type ElementListenerOptions, type GroupSelectHandler, type InputState, type InputType, type IntersectionState, type IsSelectedHandler, type ListenerOptions, type MarginType, type MarginValue, type MediaQueryChangeListener, type MediaQueryEventListener, type MediaQueryListenerOptions, type OnChangeHandler, type OnIntersectHandler, type OnIntersectStateHandler, type OnWakeLockRequestError, type ParseValueHandler, type ResetSelectionHandler, type SelectAllHandler, type SelectHandler, type SetSelectionHandler, type SetValue, type StartTimer, type StateDisabledUseDocumentVisibilityOptions, type StateTimerOptions, type StateTimerReturnType, type StopTimer, type TimerHandler, type TimerId, type TimerOptions, type TimerReturnType, type UseConnectionReturnType, type UseDarkModeOptions, type UseDarkModeOutput, type UseDocumentVisibilityOptions, type UseInViewOptions, type UseInViewReturnType, type UseInputOptions, type UseInputOutput, type UseIntervalWhenVisibleReturnType, type UseIntervalWhenVisibleStateReturnType, type UseMediaQueryOptions, type UseMediaQueryStateOptions, type UseSelectionReturnType, type UseWakeLock, type UseWakeLockBase, type UseWakeLockOptions, type ValidateValueHandler, type Value, type VisibilityChangeHandler, type WindowEventListener, type WindowListenerOptions, getState, useConnection, useDarkMode, useDebounce, useDeferCallback, useDocumentVisibility, useEffectOnce, useEventListener, useFocusTrap, useInView, useInput, useInterval, useIntervalWhenVisible, useIsClient, useIsFirstRender, useIsPortrait, useIsTouchDevice, useLightInterval, useLightTimeout, useLocalStorage, useMediaQuery, usePagination, useScrollBlock, useSelection, useSessionStorage, useStorage, useTimeout, useUpdateEffect, useWakeLock };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _react = require('react');var _LocalStorage = require('@alessiofrittoli/web-utils/storage/LocalStorage');var _SessionStorage = require('@alessiofrittoli/web-utils/storage/SessionStorage');var I=(e,n,r="local")=>{let t=_react.useCallback.call(void 0, ()=>_nullishCoalesce((r==="local"?_LocalStorage.LocalStorage:_SessionStorage.SessionStorage).get(e), () => (n)),[r,e,n]),[i,a]=_react.useState.call(void 0, n),s=_react.useCallback.call(void 0, o=>{a(c=>{let p=o instanceof Function?o(c):o;return(typeof window<"u"&&r==="local"?_LocalStorage.LocalStorage:_SessionStorage.SessionStorage).set(e,p),p})},[r,e]);return _react.useEffect.call(void 0, ()=>{a(t())},[t]),[i,s]};var $=(e,n)=>I(e,n,"local");var at=(e,n)=>I(e,n,"session");var j=e=>e?"online":"offline",dt= exports.useConnection =()=>{let[e,n]=_react.useState.call(void 0, j(!0)),r=e==="online",t=e==="offline",i=_react.useCallback.call(void 0, ()=>n(j(navigator.onLine)),[]);return B(["online","offline"],{listener:i,onLoad:i}),{connection:e,isOnline:r,isOffline:t}};var V=()=>{let e=_react.useRef.call(void 0, !0);return e.current?(e.current=!1,!0):e.current};var L=(e,n)=>{let r=V();_react.useEffect.call(void 0, ()=>{if(!r)return e()},n)};var _webutils = require('@alessiofrittoli/web-utils');var H=e=>typeof e=="string"?_webutils.isEmpty.call(void 0, e):!e,w={value:"",isTouched:!1,isValid:!0},N=(e,n)=>{switch(n.type){case"TOUCHED":return{...e,isTouched:!0};case"CHANGE":return{...e,value:n.value};case"BLUR":return{...e,value:e.value,isTouched:!H(_nullishCoalesce(e.value, () => ("")))};case"RESET":return w}};var It=(e={})=>{let{inputRef:n}=e,{initialValue:r}=e,{touchTimeout:t=600}=e,{validate:i,parse:a}=e,{onChange:s}=e,[o,c]=_react.useReducer.call(void 0, N,{...w,value:r}),p=_react.useMemo.call(void 0, ()=>a?a(o.value):o.value,[o.value,a]),u=_react.useMemo.call(void 0, ()=>typeof i=="function"?i(p):!0,[p,i]),{isTouched:l}=o,d=H(p),f=!u&&l||!!r&&!u;L(()=>{let T=setTimeout(()=>{H(p)||c({type:"TOUCHED"})},t);return()=>clearTimeout(T)},[p,t]);let y=_react.useCallback.call(void 0, T=>{let{target:x}=T,{type:v}=x,k=v==="checkbox"?x.checked:x.value;c({type:"CHANGE",value:k}),_optionalChain([s, 'optionalCall', _2 => _2(a?a(k):k)])},[s,a]),S=_react.useCallback.call(void 0, ()=>{c({type:"BLUR"})},[]),b=_react.useCallback.call(void 0, ()=>{c({type:"TOUCHED"})},[]),E=_react.useCallback.call(void 0, T=>{c({type:"CHANGE",value:T})},[]),O=_react.useCallback.call(void 0, ()=>{_optionalChain([n, 'optionalAccess', _3 => _3.current, 'optionalAccess', _4 => _4.focus, 'call', _5 => _5()])},[n]),D=_react.useCallback.call(void 0, ()=>{c({type:"RESET"})},[]);return{value:p,isTouched:l,isValid:u,isEmpty:d,hasError:f,changeHandler:y,blurHandler:S,setValue:E,submit:b,focus:O,reset:D}};var Dt=(e,n)=>_react.useCallback.call(void 0, _webutils.deferCallback.call(void 0, e),n);var R=e=>{let n=V();_react.useEffect.call(void 0, ()=>{if(n)return e()},[])};var _=()=>{let[e,n]=_react.useState.call(void 0, !1);return _react.useEffect.call(void 0, ()=>n(!0),[]),e};var _helpers = require('@alessiofrittoli/math-utils/helpers');var Bt=(e={})=>_react.useMemo.call(void 0, ()=>_helpers.paginate.call(void 0, e),[e]);var zt=(e,n=[])=>{let[r,t]=_react.useState.call(void 0, n),i=r.length>0,a=u=>r.includes(u),s=_react.useCallback.call(void 0, u=>t(l=>{let d=new Set(l);return d.has(u)?d.delete(u):d.add(u),Array.from(d.values())}),[]),o=_react.useCallback.call(void 0, u=>{t(l=>{if(l.length===0)return[u];let d=[...e],f=d.indexOf(l.at(0)),y=d.indexOf(u);if(f>y){let S=[...d].reverse(),b=S.indexOf(l.at(0)),E=S.indexOf(u);return S.slice(b,E+1)}return d.slice(f,y+1)})},[e]),c=_react.useCallback.call(void 0, ()=>{t(e)},[e]),p=_react.useCallback.call(void 0, u=>t(u?n:[]),[n]);return{selection:r,hasSelection:i,isSelected:a,setSelection:t,select:s,groupSelect:o,selectAll:c,resetSelection:p}};var _browserapi = require('@alessiofrittoli/web-utils/browser-api');function M(e,n={}){let{updateState:r=!0,onChange:t}=n,[i,a]=_react.useState.call(void 0, _browserapi.getMediaMatches.call(void 0, e)),s=_react.useCallback.call(void 0, ()=>{let o=_browserapi.getMediaMatches.call(void 0, e);r&&a(o),_optionalChain([t, 'optionalCall', _6 => _6(o)])},[e,r,t]);if(_react.useEffect.call(void 0, ()=>{let o=window.matchMedia(e),{matches:c}=o;return r&&a(c),_optionalChain([t, 'optionalCall', _7 => _7(c)]),o.addEventListener("change",s),()=>{o.removeEventListener("change",s)}},[e,r,t,s]),!!r)return i}var an=(e={})=>{let n=_(),r=M("(prefers-color-scheme: dark)"),{initial:t=r,docClassNames:i=[]}=e,[a,s]=$("dark-mode",t),o=_nullishCoalesce(a, () => (r)),[c,p]=i,u=_react.useRef.call(void 0, {light:"",dark:""});return L(()=>{s(r)},[r,s]),_react.useEffect.call(void 0, ()=>{c&&document.documentElement.classList.toggle(c,o),p&&document.documentElement.classList.toggle(p,!o)},[o,c,p]),_react.useEffect.call(void 0, ()=>{document.head.querySelectorAll('meta[name="theme-color"]').forEach(l=>{let d=l.getAttribute("media"),f=l.getAttribute("content");if(f){if(!d||d==="(prefers-color-scheme: light)"){u.current.light=f;return}u.current.dark=f}})},[]),L(()=>{let l=u.current.dark,d=u.current.light;a&&!l||!a&&!d||document.head.querySelectorAll('meta[name="theme-color"]').forEach(f=>{f.setAttribute("content",a?l:d)})},[a]),{isDarkMode:n?o:!1,isDarkOS:n?r:!1,toggleDarkMode:_react.useCallback.call(void 0, ()=>s(l=>!l),[s]),enableDarkMode:_react.useCallback.call(void 0, ()=>s(!0),[s]),disableDarkMode:_react.useCallback.call(void 0, ()=>s(!1),[s])}};function X(e={}){let{updateState:n=!0,onVisibilityChange:r}=e,[t,i]=_react.useState.call(void 0, !1),a=_react.useCallback.call(void 0, ()=>{let s=!document.hidden;n&&i(s),_optionalChain([r, 'optionalCall', _8 => _8(s)])},[n,r]);if(R(()=>{n&&i(!document.hidden)}),_react.useEffect.call(void 0, ()=>(document.addEventListener("visibilitychange",a),()=>document.removeEventListener("visibilitychange",a)),[a]),n)return t}function B(e,n){let{target:r,query:t,options:i,listener:a,onLoad:s,onCleanUp:o}=n;_react.useEffect.call(void 0, ()=>{let c=Array.isArray(e)?e:[e],p=_nullishCoalesce((t?window.matchMedia(t):r&&"current"in r?r.current:r), () => (window));if(p.addEventListener)return _optionalChain([s, 'optionalCall', _9 => _9()]),c.map(u=>{p.addEventListener(u,a,i)}),()=>{c.map(u=>{p.removeEventListener(u,a,i)}),_optionalChain([o, 'optionalCall', _10 => _10()])}},[e,r,t,i,a,s,o])}var _device = require('@alessiofrittoli/web-utils/device');var xn=()=>M(_device.portraitMediaQuery);var kn=()=>M("(pointer: coarse)");var Vn=(e={})=>{let{onMount:n=!0,onError:r}=e,[t,i]=_react.useState.call(void 0, null),a=_react.useRef.call(void 0, n),s=t&&!t.released||!1,o=_react.useCallback.call(void 0, async l=>!t||t.released?navigator.wakeLock.request("screen").then(d=>{i(d),_optionalChain([l, 'optionalCall', _11 => _11()])}).catch(r||console.error):t,[t,r]),c=_react.useCallback.call(void 0, async()=>_optionalChain([t, 'optionalAccess', _12 => _12.release, 'call', _13 => _13()]),[t]),p=_react.useCallback.call(void 0, async()=>{o(()=>{a.current=!0})},[o]),u=_react.useCallback.call(void 0, async()=>{a.current=!1,c()},[c]);return X({updateState:!1,onVisibilityChange:_react.useCallback.call(void 0, l=>{if(l&&!s&&a.current)return o();if(!l)return c()},[s,o,c])}),R(()=>{s||!n||o()}),_react.useEffect.call(void 0, ()=>{if(!t)return;let l=()=>{t.released&&i(null)};return t.addEventListener("release",l),()=>{t.removeEventListener("release",l),!t.released&&t.release()}},[t]),{wakeLock:t,enabled:s,requestWakeLock:p,releaseWakeLock:u}};var Ue=["input","select","textarea","button","[href]",'[tabindex]:not([tabindex="-1"])'].join(", "),Dn= exports.useFocusTrap =e=>{let n=_react.useMemo.call(void 0, ()=>_optionalChain([e, 'optionalAccess', _14 => _14.current]),[e]),[r,t]=_react.useState.call(void 0, !1),i=_react.useRef.call(void 0, null),a=_react.useCallback.call(void 0, o=>{i.current=document.activeElement;let c=o||n||!1;if(c)return t(c)},[n]),s=_react.useCallback.call(void 0, ()=>{_optionalChain([i, 'access', _15 => _15.current, 'optionalAccess', _16 => _16.focus, 'call', _17 => _17()]),t(!1)},[]);return _react.useEffect.call(void 0, ()=>{if(!r)return;let o=c=>{if(c.key!=="Tab")return;let p=Array.from(r.querySelectorAll(Ue)),u=p.at(0),l=p.at(-1);if(!c.shiftKey){document.activeElement===l&&(c.preventDefault(),_optionalChain([u, 'optionalAccess', _18 => _18.focus, 'call', _19 => _19()]));return}document.activeElement===u&&(c.preventDefault(),_optionalChain([l, 'optionalAccess', _20 => _20.focus, 'call', _21 => _21()]))};return document.addEventListener("keydown",o),()=>{document.removeEventListener("keydown",o)}},[r]),[a,s]};var Kn=(e,n={})=>{let{initial:r=!1,once:t,amount:i,margin:a,root:s,enable:o=!0}=n,{onEnter:c,onExit:p,onIntersect:u}=n,l=_react.useRef.call(void 0, !0),[d,f]=_react.useState.call(void 0, r),[y,S]=_react.useState.call(void 0, o),b=_react.useRef.call(void 0, null),E=_react.useRef.call(void 0, !1),O=_react.useMemo.call(void 0, ()=>{if(!y||typeof IntersectionObserver>"u")return;let D=i==="all"?1:i==="some"?.5:i;try{return new IntersectionObserver(async([T],x)=>{if(!T)return;let v=T.isIntersecting;try{if(E.current=!v&&!!b.current,v&&c&&await c({entry:T,observer:x}),E.current&&p&&await p({entry:T,observer:x}),u&&(v||!v&&b.current!=null)){let k={isEntering:v,isExiting:E.current};await u({entry:T,observer:x,...k})}if(b.current=v,!l.current)return;f(v)}catch(k){console.error(k)}v&&t&&x.disconnect()},{root:s||void 0,rootMargin:a,threshold:D})}catch(T){console.error(T)}},[s,a,i,t,y,c,p,u]);return _react.useEffect.call(void 0, ()=>{if(l.current=!0,!(!y||!e.current||!O))return O.observe(e.current),()=>{l.current=!1,O.disconnect()}},[e,O,y]),{inView:d,enabled:y,observer:O,isExiting:E.current,setInView:f,setEnabled:S}};var _dom = require('@alessiofrittoli/web-utils/dom');var Pn=e=>{let n=_react.useMemo.call(void 0, ()=>_optionalChain([e, 'optionalAccess', _22 => _22.current]),[e]),r=_react.useCallback.call(void 0, ()=>_dom.blockScroll.call(void 0, n||void 0),[n]),t=_react.useCallback.call(void 0, ()=>_dom.restoreScroll.call(void 0, n||void 0),[n]);return[r,t]};var te=(e,n={})=>{let{delay:r=1,args:t}=n;_react.useEffect.call(void 0, ()=>{let i=setTimeout(e,r,...t||[]);return()=>clearTimeout(i)},[r,t,e])};var Jn=(e,n=500)=>{let[r,t]=_react.useState.call(void 0, e),i=_react.useMemo.call(void 0, ()=>[e],[e]);return te(t,{delay:n,args:i}),r};function ne(e,n={}){let{delay:r=1,args:t,autoplay:i=!0,runOnStart:a=!1,updateState:s=!1}=n,o=_react.useRef.call(void 0, void 0),[c,p]=_react.useState.call(void 0, i),u=_react.useCallback.call(void 0, ()=>o.current?(clearInterval(o.current),o.current=void 0,!0):!1,[]),l=_react.useCallback.call(void 0, ()=>{let f=u();return a&&(t?e(...t):e()),o.current=setInterval(e,r,...t||[]),!f&&s&&p(!0),o.current},[r,t,s,a,e,u]),d=_react.useCallback.call(void 0, ()=>{u()&&s&&p(!1)},[s,u]);return _react.useEffect.call(void 0, ()=>{if(i)return l(),()=>d()},[i,l,d]),s?{isActive:c,start:l,stop:d}:{start:l,stop:d}}var rr=(e,n={})=>{let{delay:r=1,args:t}=n;_react.useEffect.call(void 0, ()=>{let i=setInterval(e,r,...t||[]);return()=>clearInterval(i)},[r,t,e])};function cr(e,n={}){let{autoplay:r=!0}=n,t=ne(e,{autoplay:!1,...n}),{start:i,stop:a}=t,s=_react.useCallback.call(void 0, ()=>document.hidden?a():i(),[i,a]),o=_react.useCallback.call(void 0, ()=>{if(document.addEventListener("visibilitychange",s),!document.hidden)return i()},[i,s]),c=_react.useCallback.call(void 0, ()=>{a(),document.removeEventListener("visibilitychange",s)},[a,s]);return _react.useEffect.call(void 0, ()=>{if(r)return o(),()=>c()},[r,o,c]),{...t,start:o,stop:c}}function dr(e,n={}){let{delay:r=1,args:t,autoplay:i=!0,runOnStart:a=!1,updateState:s=!1}=n,o=_react.useRef.call(void 0, void 0),[c,p]=_react.useState.call(void 0, i),u=_react.useCallback.call(void 0, ()=>o.current?(clearTimeout(o.current),o.current=void 0,!0):!1,[]),l=_react.useCallback.call(void 0, ()=>{let f=u();return a&&(t?e(...t):e()),o.current=setTimeout(()=>{if(o.current=void 0,s&&p(!1),t)return e(...t);e()},r),!f&&s&&p(!0),o.current},[r,t,s,a,e,u]),d=_react.useCallback.call(void 0, ()=>{u()&&s&&p(!1)},[s,u]);return _react.useEffect.call(void 0, ()=>{if(i)return l(),()=>d()},[i,l,d]),s?{isActive:c,start:l,stop:d}:{start:l,stop:d}}exports.getState = j; exports.useConnection = dt; exports.useDarkMode = an; exports.useDebounce = Jn; exports.useDeferCallback = Dt; exports.useDocumentVisibility = X; exports.useEffectOnce = R; exports.useEventListener = B; exports.useFocusTrap = Dn; exports.useInView = Kn; exports.useInput = It; exports.useInterval = ne; exports.useIntervalWhenVisible = cr; exports.useIsClient = _; exports.useIsFirstRender = V; exports.useIsPortrait = xn; exports.useIsTouchDevice = kn; exports.useLightInterval = rr; exports.useLightTimeout = te; exports.useLocalStorage = $; exports.useMediaQuery = M; exports.usePagination = Bt; exports.useScrollBlock = Pn; exports.useSelection = zt; exports.useSessionStorage = at; exports.useStorage = I; exports.useTimeout = dr; exports.useUpdateEffect = L; exports.useWakeLock = Vn;
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _react = require('react');var _webutils = require('@alessiofrittoli/web-utils');var I=(e,n,r="local")=>{let t=_react.useCallback.call(void 0, ()=>_nullishCoalesce((r==="local"?_webutils.LocalStorage:_webutils.SessionStorage).get(e), () => (n)),[r,e,n]),[i,a]=_react.useState.call(void 0, n),s=_react.useCallback.call(void 0, o=>{a(c=>{let p=o instanceof Function?o(c):o;return(typeof window<"u"&&r==="local"?_webutils.LocalStorage:_webutils.SessionStorage).set(e,p),p})},[r,e]);return _react.useEffect.call(void 0, ()=>{a(t())},[t]),[i,s]};var $=(e,n)=>I(e,n,"local");var it=(e,n)=>I(e,n,"session");var j=e=>e?"online":"offline",pt= exports.useConnection =()=>{let[e,n]=_react.useState.call(void 0, j(!0)),r=e==="online",t=e==="offline",i=_react.useCallback.call(void 0, ()=>n(j(navigator.onLine)),[]);return B(["online","offline"],{listener:i,onLoad:i}),{connection:e,isOnline:r,isOffline:t}};var V=()=>{let e=_react.useRef.call(void 0, !0);return e.current?(e.current=!1,!0):e.current};var L=(e,n)=>{let r=V();_react.useEffect.call(void 0, ()=>{if(!r)return e()},n)};var H=e=>typeof e=="string"?_webutils.isEmpty.call(void 0, e):!e,w={value:"",isTouched:!1,isValid:!0},N=(e,n)=>{switch(n.type){case"TOUCHED":return{...e,isTouched:!0};case"CHANGE":return{...e,value:n.value};case"BLUR":return{...e,value:e.value,isTouched:!H(_nullishCoalesce(e.value, () => ("")))};case"RESET":return w}};var ht=(e={})=>{let{inputRef:n}=e,{initialValue:r}=e,{touchTimeout:t=600}=e,{validate:i,parse:a}=e,{onChange:s}=e,[o,c]=_react.useReducer.call(void 0, N,{...w,value:r}),p=_react.useMemo.call(void 0, ()=>a?a(o.value):o.value,[o.value,a]),u=_react.useMemo.call(void 0, ()=>typeof i=="function"?i(p):!0,[p,i]),{isTouched:l}=o,d=H(p),f=!u&&l||!!r&&!u;L(()=>{let T=setTimeout(()=>{H(p)||c({type:"TOUCHED"})},t);return()=>clearTimeout(T)},[p,t]);let y=_react.useCallback.call(void 0, T=>{let{target:x}=T,{type:v}=x,k=v==="checkbox"?x.checked:x.value;c({type:"CHANGE",value:k}),_optionalChain([s, 'optionalCall', _2 => _2(a?a(k):k)])},[s,a]),S=_react.useCallback.call(void 0, ()=>{c({type:"BLUR"})},[]),b=_react.useCallback.call(void 0, ()=>{c({type:"TOUCHED"})},[]),E=_react.useCallback.call(void 0, T=>{c({type:"CHANGE",value:T})},[]),O=_react.useCallback.call(void 0, ()=>{_optionalChain([n, 'optionalAccess', _3 => _3.current, 'optionalAccess', _4 => _4.focus, 'call', _5 => _5()])},[n]),D=_react.useCallback.call(void 0, ()=>{c({type:"RESET"})},[]);return{value:p,isTouched:l,isValid:u,isEmpty:d,hasError:f,changeHandler:y,blurHandler:S,setValue:E,submit:b,focus:O,reset:D}};var Ct=(e,n)=>_react.useCallback.call(void 0, _webutils.deferCallback.call(void 0, e),n);var R=e=>{let n=V();_react.useEffect.call(void 0, ()=>{if(n)return e()},[])};var _=()=>{let[e,n]=_react.useState.call(void 0, !1);return _react.useEffect.call(void 0, ()=>n(!0),[]),e};var _mathutils = require('@alessiofrittoli/math-utils');var jt=(e={})=>_react.useMemo.call(void 0, ()=>_mathutils.paginate.call(void 0, e),[e]);var _t=(e,n=[])=>{let[r,t]=_react.useState.call(void 0, n),i=r.length>0,a=u=>r.includes(u),s=_react.useCallback.call(void 0, u=>t(l=>{let d=new Set(l);return d.has(u)?d.delete(u):d.add(u),Array.from(d.values())}),[]),o=_react.useCallback.call(void 0, u=>{t(l=>{if(l.length===0)return[u];let d=[...e],f=d.indexOf(l.at(0)),y=d.indexOf(u);if(f>y){let S=[...d].reverse(),b=S.indexOf(l.at(0)),E=S.indexOf(u);return S.slice(b,E+1)}return d.slice(f,y+1)})},[e]),c=_react.useCallback.call(void 0, ()=>{t(e)},[e]),p=_react.useCallback.call(void 0, u=>t(u?n:[]),[n]);return{selection:r,hasSelection:i,isSelected:a,setSelection:t,select:s,groupSelect:o,selectAll:c,resetSelection:p}};function M(e,n={}){let{updateState:r=!0,onChange:t}=n,[i,a]=_react.useState.call(void 0, _webutils.getMediaMatches.call(void 0, e)),s=_react.useCallback.call(void 0, ()=>{let o=_webutils.getMediaMatches.call(void 0, e);r&&a(o),_optionalChain([t, 'optionalCall', _6 => _6(o)])},[e,r,t]);if(_react.useEffect.call(void 0, ()=>{let o=window.matchMedia(e),{matches:c}=o;return r&&a(c),_optionalChain([t, 'optionalCall', _7 => _7(c)]),o.addEventListener("change",s),()=>{o.removeEventListener("change",s)}},[e,r,t,s]),!!r)return i}var sn=(e={})=>{let n=_(),r=M("(prefers-color-scheme: dark)"),{initial:t=r,docClassNames:i=[]}=e,[a,s]=$("dark-mode",t),o=_nullishCoalesce(a, () => (r)),[c,p]=i,u=_react.useRef.call(void 0, {light:"",dark:""});return L(()=>{s(r)},[r,s]),_react.useEffect.call(void 0, ()=>{c&&document.documentElement.classList.toggle(c,o),p&&document.documentElement.classList.toggle(p,!o)},[o,c,p]),_react.useEffect.call(void 0, ()=>{document.head.querySelectorAll('meta[name="theme-color"]').forEach(l=>{let d=l.getAttribute("media"),f=l.getAttribute("content");if(f){if(!d||d==="(prefers-color-scheme: light)"){u.current.light=f;return}u.current.dark=f}})},[]),L(()=>{let l=u.current.dark,d=u.current.light;a&&!l||!a&&!d||document.head.querySelectorAll('meta[name="theme-color"]').forEach(f=>{f.setAttribute("content",a?l:d)})},[a]),{isDarkMode:n?o:!1,isDarkOS:n?r:!1,toggleDarkMode:_react.useCallback.call(void 0, ()=>s(l=>!l),[s]),enableDarkMode:_react.useCallback.call(void 0, ()=>s(!0),[s]),disableDarkMode:_react.useCallback.call(void 0, ()=>s(!1),[s])}};function X(e={}){let{updateState:n=!0,onVisibilityChange:r}=e,[t,i]=_react.useState.call(void 0, !1),a=_react.useCallback.call(void 0, ()=>{let s=!document.hidden;n&&i(s),_optionalChain([r, 'optionalCall', _8 => _8(s)])},[n,r]);if(R(()=>{n&&i(!document.hidden)}),_react.useEffect.call(void 0, ()=>(document.addEventListener("visibilitychange",a),()=>document.removeEventListener("visibilitychange",a)),[a]),n)return t}function B(e,n){let{target:r,query:t,options:i,listener:a,onLoad:s,onCleanUp:o}=n;_react.useEffect.call(void 0, ()=>{let c=Array.isArray(e)?e:[e],p=_nullishCoalesce((t?window.matchMedia(t):r&&"current"in r?r.current:r), () => (window));if(p.addEventListener)return _optionalChain([s, 'optionalCall', _9 => _9()]),c.map(u=>{p.addEventListener(u,a,i)}),()=>{c.map(u=>{p.removeEventListener(u,a,i)}),_optionalChain([o, 'optionalCall', _10 => _10()])}},[e,r,t,i,a,s,o])}var En=()=>M(_webutils.portraitMediaQuery);var On=()=>M("(pointer: coarse)");var In=(e={})=>{let{onMount:n=!0,onError:r}=e,[t,i]=_react.useState.call(void 0, null),a=_react.useRef.call(void 0, n),s=t&&!t.released||!1,o=_react.useCallback.call(void 0, async l=>!t||t.released?navigator.wakeLock.request("screen").then(d=>{i(d),_optionalChain([l, 'optionalCall', _11 => _11()])}).catch(r||console.error):t,[t,r]),c=_react.useCallback.call(void 0, async()=>_optionalChain([t, 'optionalAccess', _12 => _12.release, 'call', _13 => _13()]),[t]),p=_react.useCallback.call(void 0, async()=>{o(()=>{a.current=!0})},[o]),u=_react.useCallback.call(void 0, async()=>{a.current=!1,c()},[c]);return X({updateState:!1,onVisibilityChange:_react.useCallback.call(void 0, l=>{if(l&&!s&&a.current)return o();if(!l)return c()},[s,o,c])}),R(()=>{s||!n||o()}),_react.useEffect.call(void 0, ()=>{if(!t)return;let l=()=>{t.released&&i(null)};return t.addEventListener("release",l),()=>{t.removeEventListener("release",l),!t.released&&t.release()}},[t]),{wakeLock:t,enabled:s,requestWakeLock:p,releaseWakeLock:u}};var Ue=["input","select","textarea","button","[href]",'[tabindex]:not([tabindex="-1"])'].join(", "),Cn= exports.useFocusTrap =e=>{let n=_react.useMemo.call(void 0, ()=>_optionalChain([e, 'optionalAccess', _14 => _14.current]),[e]),[r,t]=_react.useState.call(void 0, !1),i=_react.useRef.call(void 0, null),a=_react.useCallback.call(void 0, o=>{i.current=document.activeElement;let c=o||n||!1;if(c)return t(c)},[n]),s=_react.useCallback.call(void 0, ()=>{_optionalChain([i, 'access', _15 => _15.current, 'optionalAccess', _16 => _16.focus, 'call', _17 => _17()]),t(!1)},[]);return _react.useEffect.call(void 0, ()=>{if(!r)return;let o=c=>{if(c.key!=="Tab")return;let p=Array.from(r.querySelectorAll(Ue)),u=p.at(0),l=p.at(-1);if(!c.shiftKey){document.activeElement===l&&(c.preventDefault(),_optionalChain([u, 'optionalAccess', _18 => _18.focus, 'call', _19 => _19()]));return}document.activeElement===u&&(c.preventDefault(),_optionalChain([l, 'optionalAccess', _20 => _20.focus, 'call', _21 => _21()]))};return document.addEventListener("keydown",o),()=>{document.removeEventListener("keydown",o)}},[r]),[a,s]};var Wn=(e,n={})=>{let{initial:r=!1,once:t,amount:i,margin:a,root:s,enable:o=!0}=n,{onEnter:c,onExit:p,onIntersect:u}=n,l=_react.useRef.call(void 0, !0),[d,f]=_react.useState.call(void 0, r),[y,S]=_react.useState.call(void 0, o),b=_react.useRef.call(void 0, null),E=_react.useRef.call(void 0, !1),O=_react.useMemo.call(void 0, ()=>{if(!y||typeof IntersectionObserver>"u")return;let D=i==="all"?1:i==="some"?.5:i;try{return new IntersectionObserver(async([T],x)=>{if(!T)return;let v=T.isIntersecting;try{if(E.current=!v&&!!b.current,v&&c&&await c({entry:T,observer:x}),E.current&&p&&await p({entry:T,observer:x}),u&&(v||!v&&b.current!=null)){let k={isEntering:v,isExiting:E.current};await u({entry:T,observer:x,...k})}if(b.current=v,!l.current)return;f(v)}catch(k){console.error(k)}v&&t&&x.disconnect()},{root:s||void 0,rootMargin:a,threshold:D})}catch(T){console.error(T)}},[s,a,i,t,y,c,p,u]);return _react.useEffect.call(void 0, ()=>{if(l.current=!0,!(!y||!e.current||!O))return O.observe(e.current),()=>{l.current=!1,O.disconnect()}},[e,O,y]),{inView:d,enabled:y,observer:O,isExiting:E.current,setInView:f,setEnabled:S}};var qn=e=>{let n=_react.useMemo.call(void 0, ()=>_optionalChain([e, 'optionalAccess', _22 => _22.current]),[e]),r=_react.useCallback.call(void 0, ()=>_webutils.blockScroll.call(void 0, n||void 0),[n]),t=_react.useCallback.call(void 0, ()=>_webutils.restoreScroll.call(void 0, n||void 0),[n]);return[r,t]};var te=(e,n={})=>{let{delay:r=1,args:t}=n;_react.useEffect.call(void 0, ()=>{let i=setTimeout(e,r,...t||[]);return()=>clearTimeout(i)},[r,t,e])};var zn=(e,n=500)=>{let[r,t]=_react.useState.call(void 0, e),i=_react.useMemo.call(void 0, ()=>[e],[e]);return te(t,{delay:n,args:i}),r};function ne(e,n={}){let{delay:r=1,args:t,autoplay:i=!0,runOnStart:a=!1,updateState:s=!1}=n,o=_react.useRef.call(void 0, void 0),[c,p]=_react.useState.call(void 0, i),u=_react.useCallback.call(void 0, ()=>o.current?(clearInterval(o.current),o.current=void 0,!0):!1,[]),l=_react.useCallback.call(void 0, ()=>{let f=u();return a&&(t?e(...t):e()),o.current=setInterval(e,r,...t||[]),!f&&s&&p(!0),o.current},[r,t,s,a,e,u]),d=_react.useCallback.call(void 0, ()=>{u()&&s&&p(!1)},[s,u]);return _react.useEffect.call(void 0, ()=>(i&&l(),()=>d()),[i,l,d]),s?{isActive:c,start:l,stop:d}:{start:l,stop:d}}var nr=(e,n={})=>{let{delay:r=1,args:t}=n;_react.useEffect.call(void 0, ()=>{let i=setInterval(e,r,...t||[]);return()=>clearInterval(i)},[r,t,e])};function ar(e,n={}){let{autoplay:r=!0}=n,t=ne(e,{autoplay:!1,...n}),{start:i,stop:a}=t,s=_react.useCallback.call(void 0, ()=>document.hidden?a():i(),[i,a]),o=_react.useCallback.call(void 0, ()=>{if(document.addEventListener("visibilitychange",s),!document.hidden)return i()},[i,s]),c=_react.useCallback.call(void 0, ()=>{a(),document.removeEventListener("visibilitychange",s)},[a,s]);return _react.useEffect.call(void 0, ()=>(r&&o(),()=>c()),[r,o,c]),{...t,start:o,stop:c}}function pr(e,n={}){let{delay:r=1,args:t,autoplay:i=!0,runOnStart:a=!1,updateState:s=!1}=n,o=_react.useRef.call(void 0, void 0),[c,p]=_react.useState.call(void 0, i),u=_react.useCallback.call(void 0, ()=>o.current?(clearTimeout(o.current),o.current=void 0,!0):!1,[]),l=_react.useCallback.call(void 0, ()=>{let f=u();return a&&(t?_optionalChain([e, 'optionalCall', _23 => _23(...t)]):_optionalChain([e, 'optionalCall', _24 => _24()])),o.current=setTimeout(()=>{if(o.current=void 0,s&&p(!1),t)return _optionalChain([e, 'optionalCall', _25 => _25(...t)]);_optionalChain([e, 'optionalCall', _26 => _26()])},r),!f&&s&&p(!0),o.current},[r,t,s,a,e,u]),d=_react.useCallback.call(void 0, ()=>{u()&&s&&p(!1)},[s,u]);return _react.useEffect.call(void 0, ()=>(i&&l(),()=>d()),[i,l,d]),s?{isActive:c,start:l,stop:d}:{start:l,stop:d}}exports.getState = j; exports.useConnection = pt; exports.useDarkMode = sn; exports.useDebounce = zn; exports.useDeferCallback = Ct; exports.useDocumentVisibility = X; exports.useEffectOnce = R; exports.useEventListener = B; exports.useFocusTrap = Cn; exports.useInView = Wn; exports.useInput = ht; exports.useInterval = ne; exports.useIntervalWhenVisible = ar; exports.useIsClient = _; exports.useIsFirstRender = V; exports.useIsPortrait = En; exports.useIsTouchDevice = On; exports.useLightInterval = nr; exports.useLightTimeout = te; exports.useLocalStorage = $; exports.useMediaQuery = M; exports.usePagination = jt; exports.useScrollBlock = qn; exports.useSelection = _t; exports.useSessionStorage = it; exports.useStorage = I; exports.useTimeout = pr; exports.useUpdateEffect = L; exports.useWakeLock = In;
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{useCallback as q,useEffect as oe,useState as se}from"react";import{LocalStorage as P}from"@alessiofrittoli/web-utils/storage/LocalStorage";import{SessionStorage as $}from"@alessiofrittoli/web-utils/storage/SessionStorage";var V=(e,n,r="local")=>{let t=q(()=>(r==="local"?P:$).get(e)??n,[r,e,n]),[i,a]=se(n),s=q(o=>{a(c=>{let p=o instanceof Function?o(c):o;return(typeof window<"u"&&r==="local"?P:$).set(e,p),p})},[r,e]);return oe(()=>{a(t())},[t]),[i,s]};var j=(e,n)=>V(e,n,"local");var ct=(e,n)=>V(e,n,"session");import{useCallback as ie,useState as ae}from"react";var B=e=>e?"online":"offline",mt=()=>{let[e,n]=ae(B(!0)),r=e==="online",t=e==="offline",i=ie(()=>n(B(navigator.onLine)),[]);return N(["online","offline"],{listener:i,onLoad:i}),{connection:e,isOnline:r,isOffline:t}};import{useCallback as W,useEffect as X,useRef as ke}from"react";import{useCallback as M,useMemo as _,useReducer as pe}from"react";import{useEffect as ue}from"react";import{useRef as ce}from"react";var H=()=>{let e=ce(!0);return e.current?(e.current=!1,!0):e.current};var h=(e,n)=>{let r=H();ue(()=>{if(!r)return e()},n)};import{isEmpty as le}from"@alessiofrittoli/web-utils";var R=e=>typeof e=="string"?le(e):!e,U={value:"",isTouched:!1,isValid:!0},G=(e,n)=>{switch(n.type){case"TOUCHED":return{...e,isTouched:!0};case"CHANGE":return{...e,value:n.value};case"BLUR":return{...e,value:e.value,isTouched:!R(e.value??"")};case"RESET":return U}};var Vt=(e={})=>{let{inputRef:n}=e,{initialValue:r}=e,{touchTimeout:t=600}=e,{validate:i,parse:a}=e,{onChange:s}=e,[o,c]=pe(G,{...U,value:r}),p=_(()=>a?a(o.value):o.value,[o.value,a]),u=_(()=>typeof i=="function"?i(p):!0,[p,i]),{isTouched:l}=o,d=R(p),T=!u&&l||!!r&&!u;h(()=>{let y=setTimeout(()=>{R(p)||c({type:"TOUCHED"})},t);return()=>clearTimeout(y)},[p,t]);let v=M(y=>{let{target:S}=y,{type:E}=S,g=E==="checkbox"?S.checked:S.value;c({type:"CHANGE",value:g}),s?.(a?a(g):g)},[s,a]),b=M(()=>{c({type:"BLUR"})},[]),O=M(()=>{c({type:"TOUCHED"})},[]),x=M(y=>{c({type:"CHANGE",value:y})},[]),k=M(()=>{n?.current?.focus()},[n]),w=M(()=>{c({type:"RESET"})},[]);return{value:p,isTouched:l,isValid:u,isEmpty:d,hasError:T,changeHandler:v,blurHandler:b,setValue:x,submit:O,focus:k,reset:w}};import{useCallback as de}from"react";import{deferCallback as me}from"@alessiofrittoli/web-utils";var wt=(e,n)=>de(me(e),n);import{useEffect as fe}from"react";var C=e=>{let n=H();fe(()=>{if(n)return e()},[])};import{useEffect as Te,useState as ye}from"react";var z=()=>{let[e,n]=ye(!1);return Te(()=>n(!0),[]),e};import{useMemo as ve}from"react";import{paginate as Ee}from"@alessiofrittoli/math-utils/helpers";var Nt=(e={})=>ve(()=>Ee(e),[e]);import{useCallback as D,useState as xe}from"react";var Jt=(e,n=[])=>{let[r,t]=xe(n),i=r.length>0,a=u=>r.includes(u),s=D(u=>t(l=>{let d=new Set(l);return d.has(u)?d.delete(u):d.add(u),Array.from(d.values())}),[]),o=D(u=>{t(l=>{if(l.length===0)return[u];let d=[...e],T=d.indexOf(l.at(0)),v=d.indexOf(u);if(T>v){let b=[...d].reverse(),O=b.indexOf(l.at(0)),x=b.indexOf(u);return b.slice(O,x+1)}return d.slice(T,v+1)})},[e]),c=D(()=>{t(e)},[e]),p=D(u=>t(u?n:[]),[n]);return{selection:r,hasSelection:i,isSelected:a,setSelection:t,select:s,groupSelect:o,selectAll:c,resetSelection:p}};import{useCallback as Se,useEffect as be,useState as Oe}from"react";import{getMediaMatches as J}from"@alessiofrittoli/web-utils/browser-api";function L(e,n={}){let{updateState:r=!0,onChange:t}=n,[i,a]=Oe(J(e)),s=Se(()=>{let o=J(e);r&&a(o),t?.(o)},[e,r,t]);if(be(()=>{let o=window.matchMedia(e),{matches:c}=o;return r&&a(c),t?.(c),o.addEventListener("change",s),()=>{o.removeEventListener("change",s)}},[e,r,t,s]),!!r)return i}var cn=(e={})=>{let n=z(),r=L("(prefers-color-scheme: dark)"),{initial:t=r,docClassNames:i=[]}=e,[a,s]=j("dark-mode",t),o=a??r,[c,p]=i,u=ke({light:"",dark:""});return h(()=>{s(r)},[r,s]),X(()=>{c&&document.documentElement.classList.toggle(c,o),p&&document.documentElement.classList.toggle(p,!o)},[o,c,p]),X(()=>{document.head.querySelectorAll('meta[name="theme-color"]').forEach(l=>{let d=l.getAttribute("media"),T=l.getAttribute("content");if(T){if(!d||d==="(prefers-color-scheme: light)"){u.current.light=T;return}u.current.dark=T}})},[]),h(()=>{let l=u.current.dark,d=u.current.light;a&&!l||!a&&!d||document.head.querySelectorAll('meta[name="theme-color"]').forEach(T=>{T.setAttribute("content",a?l:d)})},[a]),{isDarkMode:n?o:!1,isDarkOS:n?r:!1,toggleDarkMode:W(()=>s(l=>!l),[s]),enableDarkMode:W(()=>s(!0),[s]),disableDarkMode:W(()=>s(!1),[s])}};import{useCallback as ge,useEffect as Me,useState as Le}from"react";function Y(e={}){let{updateState:n=!0,onVisibilityChange:r}=e,[t,i]=Le(!1),a=ge(()=>{let s=!document.hidden;n&&i(s),r?.(s)},[n,r]);if(C(()=>{n&&i(!document.hidden)}),Me(()=>(document.addEventListener("visibilitychange",a),()=>document.removeEventListener("visibilitychange",a)),[a]),n)return t}import{useEffect as he}from"react";function N(e,n){let{target:r,query:t,options:i,listener:a,onLoad:s,onCleanUp:o}=n;he(()=>{let c=Array.isArray(e)?e:[e],p=(t?window.matchMedia(t):r&&"current"in r?r.current:r)??window;if(p.addEventListener)return s?.(),c.map(u=>{p.addEventListener(u,a,i)}),()=>{c.map(u=>{p.removeEventListener(u,a,i)}),o?.()}},[e,r,t,i,a,s,o])}import{portraitMediaQuery as Ie}from"@alessiofrittoli/web-utils/device";var Sn=()=>L(Ie);var gn=()=>L("(pointer: coarse)");import{useCallback as I,useEffect as Ve,useRef as He,useState as Re}from"react";var Hn=(e={})=>{let{onMount:n=!0,onError:r}=e,[t,i]=Re(null),a=He(n),s=t&&!t.released||!1,o=I(async l=>!t||t.released?navigator.wakeLock.request("screen").then(d=>{i(d),l?.()}).catch(r||console.error):t,[t,r]),c=I(async()=>t?.release(),[t]),p=I(async()=>{o(()=>{a.current=!0})},[o]),u=I(async()=>{a.current=!1,c()},[c]);return Y({updateState:!1,onVisibilityChange:I(l=>{if(l&&!s&&a.current)return o();if(!l)return c()},[s,o,c])}),C(()=>{s||!n||o()}),Ve(()=>{if(!t)return;let l=()=>{t.released&&i(null)};return t.addEventListener("release",l),()=>{t.removeEventListener("release",l),!t.released&&t.release()}},[t]),{wakeLock:t,enabled:s,requestWakeLock:p,releaseWakeLock:u}};import{useCallback as Z,useEffect as Ce,useMemo as De,useRef as we,useState as Ue}from"react";var We=["input","select","textarea","button","[href]",'[tabindex]:not([tabindex="-1"])'].join(", "),wn=e=>{let n=De(()=>e?.current,[e]),[r,t]=Ue(!1),i=we(null),a=Z(o=>{i.current=document.activeElement;let c=o||n||!1;if(c)return t(c)},[n]),s=Z(()=>{i.current?.focus(),t(!1)},[]);return Ce(()=>{if(!r)return;let o=c=>{if(c.key!=="Tab")return;let p=Array.from(r.querySelectorAll(We)),u=p.at(0),l=p.at(-1);if(!c.shiftKey){document.activeElement===l&&(c.preventDefault(),u?.focus());return}document.activeElement===u&&(c.preventDefault(),l?.focus())};return document.addEventListener("keydown",o),()=>{document.removeEventListener("keydown",o)}},[r]),[a,s]};import{useEffect as Ke,useMemo as Ae,useRef as K,useState as ee}from"react";var An=(e,n={})=>{let{initial:r=!1,once:t,amount:i,margin:a,root:s,enable:o=!0}=n,{onEnter:c,onExit:p,onIntersect:u}=n,l=K(!0),[d,T]=ee(r),[v,b]=ee(o),O=K(null),x=K(!1),k=Ae(()=>{if(!v||typeof IntersectionObserver>"u")return;let w=i==="all"?1:i==="some"?.5:i;try{return new IntersectionObserver(async([y],S)=>{if(!y)return;let E=y.isIntersecting;try{if(x.current=!E&&!!O.current,E&&c&&await c({entry:y,observer:S}),x.current&&p&&await p({entry:y,observer:S}),u&&(E||!E&&O.current!=null)){let g={isEntering:E,isExiting:x.current};await u({entry:y,observer:S,...g})}if(O.current=E,!l.current)return;T(E)}catch(g){console.error(g)}E&&t&&S.disconnect()},{root:s||void 0,rootMargin:a,threshold:w})}catch(y){console.error(y)}},[s,a,i,t,v,c,p,u]);return Ke(()=>{if(l.current=!0,!(!v||!e.current||!k))return k.observe(e.current),()=>{l.current=!1,k.disconnect()}},[e,k,v]),{inView:d,enabled:v,observer:k,isExiting:x.current,setInView:T,setEnabled:b}};import{useCallback as te,useMemo as Qe}from"react";import{blockScroll as Fe,restoreScroll as qe}from"@alessiofrittoli/web-utils/dom";var $n=e=>{let n=Qe(()=>e?.current,[e]),r=te(()=>Fe(n||void 0),[n]),t=te(()=>qe(n||void 0),[n]);return[r,t]};import{useMemo as $e,useState as je}from"react";import{useEffect as Pe}from"react";var ne=(e,n={})=>{let{delay:r=1,args:t}=n;Pe(()=>{let i=setTimeout(e,r,...t||[]);return()=>clearTimeout(i)},[r,t,e])};var Xn=(e,n=500)=>{let[r,t]=je(e),i=$e(()=>[e],[e]);return ne(t,{delay:n,args:i}),r};import{useCallback as A,useEffect as Be,useRef as Ne,useState as Ge}from"react";function re(e,n={}){let{delay:r=1,args:t,autoplay:i=!0,runOnStart:a=!1,updateState:s=!1}=n,o=Ne(void 0),[c,p]=Ge(i),u=A(()=>o.current?(clearInterval(o.current),o.current=void 0,!0):!1,[]),l=A(()=>{let T=u();return a&&(t?e(...t):e()),o.current=setInterval(e,r,...t||[]),!T&&s&&p(!0),o.current},[r,t,s,a,e,u]),d=A(()=>{u()&&s&&p(!1)},[s,u]);return Be(()=>{if(i)return l(),()=>d()},[i,l,d]),s?{isActive:c,start:l,stop:d}:{start:l,stop:d}}import{useEffect as _e}from"react";var or=(e,n={})=>{let{delay:r=1,args:t}=n;_e(()=>{let i=setInterval(e,r,...t||[]);return()=>clearInterval(i)},[r,t,e])};import{useCallback as Q,useEffect as ze}from"react";function ur(e,n={}){let{autoplay:r=!0}=n,t=re(e,{autoplay:!1,...n}),{start:i,stop:a}=t,s=Q(()=>document.hidden?a():i(),[i,a]),o=Q(()=>{if(document.addEventListener("visibilitychange",s),!document.hidden)return i()},[i,s]),c=Q(()=>{a(),document.removeEventListener("visibilitychange",s)},[a,s]);return ze(()=>{if(r)return o(),()=>c()},[r,o,c]),{...t,start:o,stop:c}}import{useCallback as F,useEffect as Je,useRef as Xe,useState as Ye}from"react";function mr(e,n={}){let{delay:r=1,args:t,autoplay:i=!0,runOnStart:a=!1,updateState:s=!1}=n,o=Xe(void 0),[c,p]=Ye(i),u=F(()=>o.current?(clearTimeout(o.current),o.current=void 0,!0):!1,[]),l=F(()=>{let T=u();return a&&(t?e(...t):e()),o.current=setTimeout(()=>{if(o.current=void 0,s&&p(!1),t)return e(...t);e()},r),!T&&s&&p(!0),o.current},[r,t,s,a,e,u]),d=F(()=>{u()&&s&&p(!1)},[s,u]);return Je(()=>{if(i)return l(),()=>d()},[i,l,d]),s?{isActive:c,start:l,stop:d}:{start:l,stop:d}}export{B as getState,mt as useConnection,cn as useDarkMode,Xn as useDebounce,wt as useDeferCallback,Y as useDocumentVisibility,C as useEffectOnce,N as useEventListener,wn as useFocusTrap,An as useInView,Vt as useInput,re as useInterval,ur as useIntervalWhenVisible,z as useIsClient,H as useIsFirstRender,Sn as useIsPortrait,gn as useIsTouchDevice,or as useLightInterval,ne as useLightTimeout,j as useLocalStorage,L as useMediaQuery,Nt as usePagination,$n as useScrollBlock,Jt as useSelection,ct as useSessionStorage,V as useStorage,mr as useTimeout,h as useUpdateEffect,Hn as useWakeLock};
1
+ import{useCallback as q,useEffect as oe,useState as se}from"react";import{LocalStorage as P,SessionStorage as $}from"@alessiofrittoli/web-utils";var V=(e,n,r="local")=>{let t=q(()=>(r==="local"?P:$).get(e)??n,[r,e,n]),[i,a]=se(n),s=q(o=>{a(c=>{let p=o instanceof Function?o(c):o;return(typeof window<"u"&&r==="local"?P:$).set(e,p),p})},[r,e]);return oe(()=>{a(t())},[t]),[i,s]};var j=(e,n)=>V(e,n,"local");var at=(e,n)=>V(e,n,"session");import{useCallback as ie,useState as ae}from"react";var B=e=>e?"online":"offline",dt=()=>{let[e,n]=ae(B(!0)),r=e==="online",t=e==="offline",i=ie(()=>n(B(navigator.onLine)),[]);return N(["online","offline"],{listener:i,onLoad:i}),{connection:e,isOnline:r,isOffline:t}};import{useCallback as W,useEffect as X,useRef as ke}from"react";import{useCallback as M,useMemo as _,useReducer as pe}from"react";import{useEffect as ue}from"react";import{useRef as ce}from"react";var H=()=>{let e=ce(!0);return e.current?(e.current=!1,!0):e.current};var h=(e,n)=>{let r=H();ue(()=>{if(!r)return e()},n)};import{isEmpty as le}from"@alessiofrittoli/web-utils";var R=e=>typeof e=="string"?le(e):!e,U={value:"",isTouched:!1,isValid:!0},G=(e,n)=>{switch(n.type){case"TOUCHED":return{...e,isTouched:!0};case"CHANGE":return{...e,value:n.value};case"BLUR":return{...e,value:e.value,isTouched:!R(e.value??"")};case"RESET":return U}};var It=(e={})=>{let{inputRef:n}=e,{initialValue:r}=e,{touchTimeout:t=600}=e,{validate:i,parse:a}=e,{onChange:s}=e,[o,c]=pe(G,{...U,value:r}),p=_(()=>a?a(o.value):o.value,[o.value,a]),u=_(()=>typeof i=="function"?i(p):!0,[p,i]),{isTouched:l}=o,d=R(p),T=!u&&l||!!r&&!u;h(()=>{let y=setTimeout(()=>{R(p)||c({type:"TOUCHED"})},t);return()=>clearTimeout(y)},[p,t]);let v=M(y=>{let{target:S}=y,{type:E}=S,g=E==="checkbox"?S.checked:S.value;c({type:"CHANGE",value:g}),s?.(a?a(g):g)},[s,a]),b=M(()=>{c({type:"BLUR"})},[]),O=M(()=>{c({type:"TOUCHED"})},[]),x=M(y=>{c({type:"CHANGE",value:y})},[]),k=M(()=>{n?.current?.focus()},[n]),w=M(()=>{c({type:"RESET"})},[]);return{value:p,isTouched:l,isValid:u,isEmpty:d,hasError:T,changeHandler:v,blurHandler:b,setValue:x,submit:O,focus:k,reset:w}};import{useCallback as de}from"react";import{deferCallback as me}from"@alessiofrittoli/web-utils";var Dt=(e,n)=>de(me(e),n);import{useEffect as fe}from"react";var C=e=>{let n=H();fe(()=>{if(n)return e()},[])};import{useEffect as Te,useState as ye}from"react";var z=()=>{let[e,n]=ye(!1);return Te(()=>n(!0),[]),e};import{useMemo as ve}from"react";import{paginate as Ee}from"@alessiofrittoli/math-utils";var Bt=(e={})=>ve(()=>Ee(e),[e]);import{useCallback as D,useState as xe}from"react";var zt=(e,n=[])=>{let[r,t]=xe(n),i=r.length>0,a=u=>r.includes(u),s=D(u=>t(l=>{let d=new Set(l);return d.has(u)?d.delete(u):d.add(u),Array.from(d.values())}),[]),o=D(u=>{t(l=>{if(l.length===0)return[u];let d=[...e],T=d.indexOf(l.at(0)),v=d.indexOf(u);if(T>v){let b=[...d].reverse(),O=b.indexOf(l.at(0)),x=b.indexOf(u);return b.slice(O,x+1)}return d.slice(T,v+1)})},[e]),c=D(()=>{t(e)},[e]),p=D(u=>t(u?n:[]),[n]);return{selection:r,hasSelection:i,isSelected:a,setSelection:t,select:s,groupSelect:o,selectAll:c,resetSelection:p}};import{useCallback as Se,useEffect as be,useState as Oe}from"react";import{getMediaMatches as J}from"@alessiofrittoli/web-utils";function L(e,n={}){let{updateState:r=!0,onChange:t}=n,[i,a]=Oe(J(e)),s=Se(()=>{let o=J(e);r&&a(o),t?.(o)},[e,r,t]);if(be(()=>{let o=window.matchMedia(e),{matches:c}=o;return r&&a(c),t?.(c),o.addEventListener("change",s),()=>{o.removeEventListener("change",s)}},[e,r,t,s]),!!r)return i}var an=(e={})=>{let n=z(),r=L("(prefers-color-scheme: dark)"),{initial:t=r,docClassNames:i=[]}=e,[a,s]=j("dark-mode",t),o=a??r,[c,p]=i,u=ke({light:"",dark:""});return h(()=>{s(r)},[r,s]),X(()=>{c&&document.documentElement.classList.toggle(c,o),p&&document.documentElement.classList.toggle(p,!o)},[o,c,p]),X(()=>{document.head.querySelectorAll('meta[name="theme-color"]').forEach(l=>{let d=l.getAttribute("media"),T=l.getAttribute("content");if(T){if(!d||d==="(prefers-color-scheme: light)"){u.current.light=T;return}u.current.dark=T}})},[]),h(()=>{let l=u.current.dark,d=u.current.light;a&&!l||!a&&!d||document.head.querySelectorAll('meta[name="theme-color"]').forEach(T=>{T.setAttribute("content",a?l:d)})},[a]),{isDarkMode:n?o:!1,isDarkOS:n?r:!1,toggleDarkMode:W(()=>s(l=>!l),[s]),enableDarkMode:W(()=>s(!0),[s]),disableDarkMode:W(()=>s(!1),[s])}};import{useCallback as ge,useEffect as Me,useState as Le}from"react";function Y(e={}){let{updateState:n=!0,onVisibilityChange:r}=e,[t,i]=Le(!1),a=ge(()=>{let s=!document.hidden;n&&i(s),r?.(s)},[n,r]);if(C(()=>{n&&i(!document.hidden)}),Me(()=>(document.addEventListener("visibilitychange",a),()=>document.removeEventListener("visibilitychange",a)),[a]),n)return t}import{useEffect as he}from"react";function N(e,n){let{target:r,query:t,options:i,listener:a,onLoad:s,onCleanUp:o}=n;he(()=>{let c=Array.isArray(e)?e:[e],p=(t?window.matchMedia(t):r&&"current"in r?r.current:r)??window;if(p.addEventListener)return s?.(),c.map(u=>{p.addEventListener(u,a,i)}),()=>{c.map(u=>{p.removeEventListener(u,a,i)}),o?.()}},[e,r,t,i,a,s,o])}import{portraitMediaQuery as Ie}from"@alessiofrittoli/web-utils";var xn=()=>L(Ie);var kn=()=>L("(pointer: coarse)");import{useCallback as I,useEffect as Ve,useRef as He,useState as Re}from"react";var Vn=(e={})=>{let{onMount:n=!0,onError:r}=e,[t,i]=Re(null),a=He(n),s=t&&!t.released||!1,o=I(async l=>!t||t.released?navigator.wakeLock.request("screen").then(d=>{i(d),l?.()}).catch(r||console.error):t,[t,r]),c=I(async()=>t?.release(),[t]),p=I(async()=>{o(()=>{a.current=!0})},[o]),u=I(async()=>{a.current=!1,c()},[c]);return Y({updateState:!1,onVisibilityChange:I(l=>{if(l&&!s&&a.current)return o();if(!l)return c()},[s,o,c])}),C(()=>{s||!n||o()}),Ve(()=>{if(!t)return;let l=()=>{t.released&&i(null)};return t.addEventListener("release",l),()=>{t.removeEventListener("release",l),!t.released&&t.release()}},[t]),{wakeLock:t,enabled:s,requestWakeLock:p,releaseWakeLock:u}};import{useCallback as Z,useEffect as Ce,useMemo as De,useRef as we,useState as Ue}from"react";var We=["input","select","textarea","button","[href]",'[tabindex]:not([tabindex="-1"])'].join(", "),Dn=e=>{let n=De(()=>e?.current,[e]),[r,t]=Ue(!1),i=we(null),a=Z(o=>{i.current=document.activeElement;let c=o||n||!1;if(c)return t(c)},[n]),s=Z(()=>{i.current?.focus(),t(!1)},[]);return Ce(()=>{if(!r)return;let o=c=>{if(c.key!=="Tab")return;let p=Array.from(r.querySelectorAll(We)),u=p.at(0),l=p.at(-1);if(!c.shiftKey){document.activeElement===l&&(c.preventDefault(),u?.focus());return}document.activeElement===u&&(c.preventDefault(),l?.focus())};return document.addEventListener("keydown",o),()=>{document.removeEventListener("keydown",o)}},[r]),[a,s]};import{useEffect as Ke,useMemo as Ae,useRef as K,useState as ee}from"react";var Kn=(e,n={})=>{let{initial:r=!1,once:t,amount:i,margin:a,root:s,enable:o=!0}=n,{onEnter:c,onExit:p,onIntersect:u}=n,l=K(!0),[d,T]=ee(r),[v,b]=ee(o),O=K(null),x=K(!1),k=Ae(()=>{if(!v||typeof IntersectionObserver>"u")return;let w=i==="all"?1:i==="some"?.5:i;try{return new IntersectionObserver(async([y],S)=>{if(!y)return;let E=y.isIntersecting;try{if(x.current=!E&&!!O.current,E&&c&&await c({entry:y,observer:S}),x.current&&p&&await p({entry:y,observer:S}),u&&(E||!E&&O.current!=null)){let g={isEntering:E,isExiting:x.current};await u({entry:y,observer:S,...g})}if(O.current=E,!l.current)return;T(E)}catch(g){console.error(g)}E&&t&&S.disconnect()},{root:s||void 0,rootMargin:a,threshold:w})}catch(y){console.error(y)}},[s,a,i,t,v,c,p,u]);return Ke(()=>{if(l.current=!0,!(!v||!e.current||!k))return k.observe(e.current),()=>{l.current=!1,k.disconnect()}},[e,k,v]),{inView:d,enabled:v,observer:k,isExiting:x.current,setInView:T,setEnabled:b}};import{useCallback as te,useMemo as Qe}from"react";import{blockScroll as Fe,restoreScroll as qe}from"@alessiofrittoli/web-utils";var Pn=e=>{let n=Qe(()=>e?.current,[e]),r=te(()=>Fe(n||void 0),[n]),t=te(()=>qe(n||void 0),[n]);return[r,t]};import{useMemo as $e,useState as je}from"react";import{useEffect as Pe}from"react";var ne=(e,n={})=>{let{delay:r=1,args:t}=n;Pe(()=>{let i=setTimeout(e,r,...t||[]);return()=>clearTimeout(i)},[r,t,e])};var Jn=(e,n=500)=>{let[r,t]=je(e),i=$e(()=>[e],[e]);return ne(t,{delay:n,args:i}),r};import{useCallback as A,useEffect as Be,useRef as Ne,useState as Ge}from"react";function re(e,n={}){let{delay:r=1,args:t,autoplay:i=!0,runOnStart:a=!1,updateState:s=!1}=n,o=Ne(void 0),[c,p]=Ge(i),u=A(()=>o.current?(clearInterval(o.current),o.current=void 0,!0):!1,[]),l=A(()=>{let T=u();return a&&(t?e(...t):e()),o.current=setInterval(e,r,...t||[]),!T&&s&&p(!0),o.current},[r,t,s,a,e,u]),d=A(()=>{u()&&s&&p(!1)},[s,u]);return Be(()=>(i&&l(),()=>d()),[i,l,d]),s?{isActive:c,start:l,stop:d}:{start:l,stop:d}}import{useEffect as _e}from"react";var rr=(e,n={})=>{let{delay:r=1,args:t}=n;_e(()=>{let i=setInterval(e,r,...t||[]);return()=>clearInterval(i)},[r,t,e])};import{useCallback as Q,useEffect as ze}from"react";function cr(e,n={}){let{autoplay:r=!0}=n,t=re(e,{autoplay:!1,...n}),{start:i,stop:a}=t,s=Q(()=>document.hidden?a():i(),[i,a]),o=Q(()=>{if(document.addEventListener("visibilitychange",s),!document.hidden)return i()},[i,s]),c=Q(()=>{a(),document.removeEventListener("visibilitychange",s)},[a,s]);return ze(()=>(r&&o(),()=>c()),[r,o,c]),{...t,start:o,stop:c}}import{useCallback as F,useEffect as Je,useRef as Xe,useState as Ye}from"react";function dr(e,n={}){let{delay:r=1,args:t,autoplay:i=!0,runOnStart:a=!1,updateState:s=!1}=n,o=Xe(void 0),[c,p]=Ye(i),u=F(()=>o.current?(clearTimeout(o.current),o.current=void 0,!0):!1,[]),l=F(()=>{let T=u();return a&&(t?e?.(...t):e?.()),o.current=setTimeout(()=>{if(o.current=void 0,s&&p(!1),t)return e?.(...t);e?.()},r),!T&&s&&p(!0),o.current},[r,t,s,a,e,u]),d=F(()=>{u()&&s&&p(!1)},[s,u]);return Je(()=>(i&&l(),()=>d()),[i,l,d]),s?{isActive:c,start:l,stop:d}:{start:l,stop:d}}export{B as getState,dt as useConnection,an as useDarkMode,Jn as useDebounce,Dt as useDeferCallback,Y as useDocumentVisibility,C as useEffectOnce,N as useEventListener,Dn as useFocusTrap,Kn as useInView,It as useInput,re as useInterval,cr as useIntervalWhenVisible,z as useIsClient,H as useIsFirstRender,xn as useIsPortrait,kn as useIsTouchDevice,rr as useLightInterval,ne as useLightTimeout,j as useLocalStorage,L as useMediaQuery,Bt as usePagination,Pn as useScrollBlock,zt as useSelection,at as useSessionStorage,V as useStorage,dr as useTimeout,h as useUpdateEffect,Vn as useWakeLock};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alessiofrittoli/react-hooks",
3
- "version": "3.7.0",
3
+ "version": "3.8.0",
4
4
  "description": "TypeScript React utility Hooks",
5
5
  "author": {
6
6
  "name": "Alessio Frittoli",
@@ -97,7 +97,7 @@
97
97
  "@alessiofrittoli/event-emitter": "^1.6.0",
98
98
  "@alessiofrittoli/node-scripts": "^3.3.0",
99
99
  "@eslint/compat": "^2.0.2",
100
- "@eslint/eslintrc": "^3.3.3",
100
+ "@eslint/eslintrc": "^3.3.4",
101
101
  "@eslint/js": "^10.0.1",
102
102
  "@jest/globals": "^30.2.0",
103
103
  "@testing-library/dom": "^10.4.1",
@@ -105,13 +105,13 @@
105
105
  "@testing-library/react": "^16.3.2",
106
106
  "@testing-library/user-event": "^14.6.1",
107
107
  "@types/jest": "^30.0.0",
108
- "@types/node": "^25.2.3",
108
+ "@types/node": "^25.3.3",
109
109
  "@types/react": "^19.2.14",
110
110
  "@types/react-dom": "^19.2.3",
111
111
  "concurrently": "^9.2.1",
112
112
  "cross-env": "^10.1.0",
113
113
  "dotenv": "^17.3.1",
114
- "eslint": "^10.0.0",
114
+ "eslint": "^10.0.2",
115
115
  "eslint-plugin-react": "^7.37.5",
116
116
  "eslint-plugin-react-hooks": "^7.0.1",
117
117
  "globals": "^17.3.0",
@@ -124,11 +124,11 @@
124
124
  "ts-node": "^10.9.2",
125
125
  "tsup": "^8.5.1",
126
126
  "typescript": "^5.9.3",
127
- "typescript-eslint": "^8.55.0"
127
+ "typescript-eslint": "^8.56.1"
128
128
  },
129
129
  "dependencies": {
130
- "@alessiofrittoli/math-utils": "^1.18.0",
130
+ "@alessiofrittoli/math-utils": "^2.0.0",
131
131
  "@alessiofrittoli/type-utils": "^1.9.0",
132
- "@alessiofrittoli/web-utils": "^1.20.0"
132
+ "@alessiofrittoli/web-utils": "^2.0.1"
133
133
  }
134
134
  }