@alessiofrittoli/react-hooks 3.7.1 → 4.0.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 +136 -40
- package/dist/index.d.mts +46 -35
- package/dist/index.d.ts +46 -35
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +8 -8
package/README.md
CHANGED
|
@@ -1,23 +1,47 @@
|
|
|
1
|
-
|
|
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)
|
|
@@ -107,6 +131,16 @@ export default config;
|
|
|
107
131
|
|
|
108
132
|
#### Updates in the latest release 🎉
|
|
109
133
|
|
|
134
|
+
- Improved `useConnection` hook. It now returns
|
|
135
|
+
[`NetworkInformation`](https://github.com/alessiofrittoli/web-utils?tab=readme-ov-file#network-information) when available.
|
|
136
|
+
See [API Reference](#useconnection) for more info.
|
|
137
|
+
- Improved `useEventListener` hook types. It now supports `EventTarget` as listener targets.
|
|
138
|
+
See [API Reference](#useeventlistener) for more info.
|
|
139
|
+
|
|
140
|
+
---
|
|
141
|
+
|
|
142
|
+
Old updates
|
|
143
|
+
|
|
110
144
|
- Added `useDocumentVisibility`. See [API Reference](#usedocumentvisibility) for more info.
|
|
111
145
|
- Added `useWakeLock`. See [API Reference](#usewakelock) for more info.
|
|
112
146
|
- Added `useDeferCallback`. See [API Reference](#usedefercallback) for more info.
|
|
@@ -294,13 +328,11 @@ Get states about Internet Connection.
|
|
|
294
328
|
|
|
295
329
|
<summary style="cursor:pointer">Returns</summary>
|
|
296
330
|
|
|
297
|
-
Type: `
|
|
331
|
+
Type: `Connection`
|
|
298
332
|
|
|
299
|
-
An object
|
|
333
|
+
An object defining network status and `NetworkInformation`.
|
|
300
334
|
|
|
301
|
-
-
|
|
302
|
-
- `isOnline`: `boolean` - Indicates whether the current device is online.
|
|
303
|
-
- `isOffline`: `boolean` - Indicates whether the current device is offline.
|
|
335
|
+
- See [`Connection`](https://github.com/alessiofrittoli/web-utils?tab=readme-ov-file#connection-interface) interface from [`@alessiofrittoli/web-utils`](https://www.npmjs.com/package/@alessiofrittoli/web-utils)
|
|
304
336
|
|
|
305
337
|
</details>
|
|
306
338
|
|
|
@@ -472,6 +504,8 @@ Attach a new Event listener to the `Window`, `Document`, `MediaQueryList` or an
|
|
|
472
504
|
| Parameter | Type | Description |
|
|
473
505
|
| ------------------- | -------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
474
506
|
| `type` | `K\|K[]` | The `Window` event name or an array of event names. |
|
|
507
|
+
| | | ⚠️ Please, make sure to memoize the event names array with `useMemo` |
|
|
508
|
+
| | | or declare that array outside your Component/hook in order to avoid infinite loops when a React state changes. |
|
|
475
509
|
| `options` | `WindowListenerOptions<K>` | An object defining init options. |
|
|
476
510
|
| `options.listener` | `WindowEventListener<K>` | The Window Event listener. |
|
|
477
511
|
| `options.onLoad` | `() => void` | A custom callback executed before event listener get attached. |
|
|
@@ -489,6 +523,8 @@ Attach a new Event listener to the `Window`, `Document`, `MediaQueryList` or an
|
|
|
489
523
|
| Parameter | Type | Description |
|
|
490
524
|
| ------------------- | ------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
491
525
|
| `type` | `K\|K[]` | The `Document` event name or an array of event names. |
|
|
526
|
+
| | | ⚠️ Please, make sure to memoize the event names array with `useMemo` |
|
|
527
|
+
| | | or declare that array outside your Component/hook in order to avoid infinite loops when a React state changes. |
|
|
492
528
|
| `options` | `DocumentListenerOptions<K>` | An object defining init options. |
|
|
493
529
|
| `options.target` | `Document\|null\|React.RefObject<Document\|null>` | The `Document` reference or a React RefObject of the `Document`. |
|
|
494
530
|
| `options.listener` | `DocumentEventListener<K>` | The Document Event listener. |
|
|
@@ -507,6 +543,8 @@ Attach a new Event listener to the `Window`, `Document`, `MediaQueryList` or an
|
|
|
507
543
|
| Parameter | Type | Description |
|
|
508
544
|
| ------------------- | ------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
509
545
|
| `type` | `K\|K[]` | The `HTMLElement` event name or an array of event names. |
|
|
546
|
+
| | | ⚠️ Please, make sure to memoize the event names array with `useMemo` |
|
|
547
|
+
| | | or declare that array outside your Component/hook in order to avoid infinite loops when a React state changes. |
|
|
510
548
|
| `options` | `ElementListenerOptions<K>` | An object defining init options. |
|
|
511
549
|
| `options.target` | `T\|React.RefObject<T\| null>` | The React RefObject of the target where the listener get attached to. |
|
|
512
550
|
| `options.listener` | `ElementEventListener<K>` | The HTMLElement Event listener. |
|
|
@@ -543,6 +581,8 @@ Attach a new Event listener to the `Window`, `Document`, `MediaQueryList` or an
|
|
|
543
581
|
| Parameter | Type | Description |
|
|
544
582
|
| ------------------- | --------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
545
583
|
| `type` | `K\|K[]` | The custom event name or an array of event names. |
|
|
584
|
+
| | | ⚠️ Please, make sure to memoize the event names array with `useMemo` |
|
|
585
|
+
| | | or declare that array outside your Component/hook in order to avoid infinite loops when a React state changes. |
|
|
546
586
|
| `options` | `CustomEventListenerOptions<T, K>` | An object defining init options. |
|
|
547
587
|
| `options.target` | `Document\|HTMLElement\|null\|React.RefObject<Document\|HTMLElement\|null>` | (Optional) The target where the listener get attached to. If not set, the listener will get attached to the `Window` object. |
|
|
548
588
|
| `options.listener` | `( event: T[ K ] ) => void` | The Event listener. |
|
|
@@ -701,6 +741,30 @@ export const MyComponent: React.FC = () => {
|
|
|
701
741
|
|
|
702
742
|
---
|
|
703
743
|
|
|
744
|
+
###### Attach listeners to multiple events
|
|
745
|
+
|
|
746
|
+
```tsx
|
|
747
|
+
import { useCallback, useState } from "react";
|
|
748
|
+
import { useEventListener } from "@alessiofrittoli/react-hooks";
|
|
749
|
+
|
|
750
|
+
/**
|
|
751
|
+
* We define events outside the Component to avoid array recreation when a state update is triggered.
|
|
752
|
+
*
|
|
753
|
+
* This prevents infinite loops for `useEventListener` life-cycle
|
|
754
|
+
*/
|
|
755
|
+
const events: (keyof WindowEventMap)[] = ["resize", "scroll"];
|
|
756
|
+
|
|
757
|
+
export const MyComponent: React.FC = () => {
|
|
758
|
+
const [isInteracting, setIsIntercting] = useState(false);
|
|
759
|
+
|
|
760
|
+
useEventListener(events, {
|
|
761
|
+
listener: useCallback(() => {
|
|
762
|
+
setIsIntercting(true);
|
|
763
|
+
}, []),
|
|
764
|
+
});
|
|
765
|
+
};
|
|
766
|
+
```
|
|
767
|
+
|
|
704
768
|
</details>
|
|
705
769
|
|
|
706
770
|
---
|
|
@@ -1284,7 +1348,7 @@ const AsyncStartExample: React.FC = () => {
|
|
|
1284
1348
|
await new Promise((resolve) => setTimeout(resolve, 1000)); // Simulate delay
|
|
1285
1349
|
console.log("Async task completed. `inView` will now be updated.");
|
|
1286
1350
|
},
|
|
1287
|
-
[]
|
|
1351
|
+
[],
|
|
1288
1352
|
);
|
|
1289
1353
|
|
|
1290
1354
|
const { inView } = useInView(targetRef, { onIntersect });
|
|
@@ -1947,7 +2011,7 @@ const items: Item[] = [
|
|
|
1947
2011
|
|
|
1948
2012
|
const MyComponent: React.FC = () => {
|
|
1949
2013
|
const { setSelection, select, groupSelect, isSelected } = useSelection(
|
|
1950
|
-
useMemo(() => items.map((item) => item.id), [])
|
|
2014
|
+
useMemo(() => items.map((item) => item.id), []),
|
|
1951
2015
|
);
|
|
1952
2016
|
|
|
1953
2017
|
const clickHandler = useCallback(
|
|
@@ -1959,10 +2023,10 @@ const MyComponent: React.FC = () => {
|
|
|
1959
2023
|
return select(id); // toggle single item in selection
|
|
1960
2024
|
}
|
|
1961
2025
|
setSelection(
|
|
1962
|
-
(prev) => (prev.includes(id) ? [] : [id]) // toggle single item selection
|
|
2026
|
+
(prev) => (prev.includes(id) ? [] : [id]), // toggle single item selection
|
|
1963
2027
|
);
|
|
1964
2028
|
},
|
|
1965
|
-
[select, groupSelect, setSelection]
|
|
2029
|
+
[select, groupSelect, setSelection],
|
|
1966
2030
|
);
|
|
1967
2031
|
|
|
1968
2032
|
return (
|
|
@@ -2147,7 +2211,7 @@ const MyComponent: React.FC = () => {
|
|
|
2147
2211
|
useCallback(() => {
|
|
2148
2212
|
console.log("tick timer");
|
|
2149
2213
|
}, []),
|
|
2150
|
-
{ delay: 1000 }
|
|
2214
|
+
{ delay: 1000 },
|
|
2151
2215
|
);
|
|
2152
2216
|
|
|
2153
2217
|
return <button onClick={stop}>Stop timer</button>;
|
|
@@ -2174,7 +2238,7 @@ const MyComponent: React.FC = () => {
|
|
|
2174
2238
|
autoplay: false,
|
|
2175
2239
|
runOnStart: true,
|
|
2176
2240
|
updateState: true,
|
|
2177
|
-
}
|
|
2241
|
+
},
|
|
2178
2242
|
);
|
|
2179
2243
|
|
|
2180
2244
|
return (
|
|
@@ -2249,7 +2313,7 @@ const MyComponent: React.FC = () => {
|
|
|
2249
2313
|
useCallback(() => {
|
|
2250
2314
|
console.log("tick timer");
|
|
2251
2315
|
}, []),
|
|
2252
|
-
{ delay: 1000 }
|
|
2316
|
+
{ delay: 1000 },
|
|
2253
2317
|
);
|
|
2254
2318
|
};
|
|
2255
2319
|
```
|
|
@@ -2291,15 +2355,17 @@ The `Timeout` is automatically cancelled on unmount.
|
|
|
2291
2355
|
|
|
2292
2356
|
<summary style="cursor:pointer">Parameters</summary>
|
|
2293
2357
|
|
|
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
|
-
|
|
|
2358
|
+
| Parameter | Type | Default | Description |
|
|
2359
|
+
| --------------------- | ----------------- | ------- | --------------------------------------------------------------------------- |
|
|
2360
|
+
| `callback` | `TimerHandler<T>` | - | The function to call when the timer elapses. |
|
|
2361
|
+
| `options` | `TimerOptions<T>` | - | (Optional) An object defining custom timer options. |
|
|
2362
|
+
| `options.delay` | `number` | `1` | The number of milliseconds to wait before calling the `callback`. |
|
|
2363
|
+
| `options.args` | `T` | - | Optional arguments to pass when the `callback` is called. |
|
|
2364
|
+
| `options.autoplay` | `boolean` | `true` | Indicates whether auto start the timer. |
|
|
2365
|
+
| `options.updateState` | `boolean` | `false` | Whether to update React state about Timer running status. |
|
|
2366
|
+
| | | | Passing a `callback` is optional if `updateState` |
|
|
2367
|
+
| | | | has been set to `true` if you're only interested about running timer state. |
|
|
2368
|
+
| `options.runOnStart` | `boolean` | `false` | Indicates whether to execute the callback when timer starts. |
|
|
2303
2369
|
|
|
2304
2370
|
</details>
|
|
2305
2371
|
|
|
@@ -2341,7 +2407,7 @@ const MyComponent: React.FC = () => {
|
|
|
2341
2407
|
useCallback(() => {
|
|
2342
2408
|
console.log("tick timer");
|
|
2343
2409
|
}, []),
|
|
2344
|
-
{ delay: 1000 }
|
|
2410
|
+
{ delay: 1000 },
|
|
2345
2411
|
);
|
|
2346
2412
|
|
|
2347
2413
|
return <button onClick={stop}>Stop timer</button>;
|
|
@@ -2368,8 +2434,38 @@ const MyComponent: React.FC = () => {
|
|
|
2368
2434
|
autoplay: false,
|
|
2369
2435
|
runOnStart: true,
|
|
2370
2436
|
updateState: true,
|
|
2371
|
-
}
|
|
2437
|
+
},
|
|
2438
|
+
);
|
|
2439
|
+
|
|
2440
|
+
return (
|
|
2441
|
+
<>
|
|
2442
|
+
{!isActive && <button onClick={start}>Start timer</button>}
|
|
2443
|
+
{isActive && <button onClick={stop}>Stop timer</button>}
|
|
2444
|
+
</>
|
|
2372
2445
|
);
|
|
2446
|
+
};
|
|
2447
|
+
```
|
|
2448
|
+
|
|
2449
|
+
</details>
|
|
2450
|
+
|
|
2451
|
+
---
|
|
2452
|
+
|
|
2453
|
+
##### Rely on time state only
|
|
2454
|
+
|
|
2455
|
+
You can pass `undefined` instead of a callback if you're interested only in timer running states.
|
|
2456
|
+
|
|
2457
|
+
```tsx
|
|
2458
|
+
"use client";
|
|
2459
|
+
|
|
2460
|
+
import { useCallback } from "react";
|
|
2461
|
+
import { useTimeout } from "@alessiofrittoli/react-hooks";
|
|
2462
|
+
|
|
2463
|
+
const MyComponent: React.FC = () => {
|
|
2464
|
+
const { isActive, start, stop } = useTimeout(undefined, {
|
|
2465
|
+
delay: 1000,
|
|
2466
|
+
autoplay: false,
|
|
2467
|
+
updateState: true,
|
|
2468
|
+
});
|
|
2373
2469
|
|
|
2374
2470
|
return (
|
|
2375
2471
|
<>
|
|
@@ -2432,7 +2528,7 @@ const MyComponent: React.FC = () => {
|
|
|
2432
2528
|
useCallback(() => {
|
|
2433
2529
|
console.log("tick timer");
|
|
2434
2530
|
}, []),
|
|
2435
|
-
{ delay: 1000 }
|
|
2531
|
+
{ delay: 1000 },
|
|
2436
2532
|
);
|
|
2437
2533
|
};
|
|
2438
2534
|
```
|
package/dist/index.d.mts
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
|
-
import
|
|
2
|
-
import
|
|
3
|
-
import
|
|
4
|
-
import { PaginateOptions } from '@alessiofrittoli/math-utils/helpers';
|
|
1
|
+
import { Connection, DeferredTask } from '@alessiofrittoli/web-utils';
|
|
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
|
|
22
|
+
declare const useLocalStorage: <T = string>(key: string, initial?: T) => [Value<T>, SetValue<Value<T>>];
|
|
24
23
|
|
|
25
24
|
/**
|
|
26
25
|
* useSessionStorage hook.
|
|
@@ -28,33 +27,14 @@ 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
|
|
30
|
+
declare const useSessionStorage: <T = string>(key: string, initial?: T) => [Value<T>, SetValue<Value<T>>];
|
|
32
31
|
|
|
33
|
-
type Connection = 'online' | 'offline';
|
|
34
|
-
declare const getState: (online: boolean) => "online" | "offline";
|
|
35
|
-
interface UseConnectionReturnType {
|
|
36
|
-
/**
|
|
37
|
-
* Indicates the connections status.
|
|
38
|
-
*
|
|
39
|
-
*/
|
|
40
|
-
connection: Connection;
|
|
41
|
-
/**
|
|
42
|
-
* Indicates whether the current device is online.
|
|
43
|
-
*
|
|
44
|
-
*/
|
|
45
|
-
isOnline: boolean;
|
|
46
|
-
/**
|
|
47
|
-
* Indicates whether the current device is offline.
|
|
48
|
-
*
|
|
49
|
-
*/
|
|
50
|
-
isOffline: boolean;
|
|
51
|
-
}
|
|
52
32
|
/**
|
|
53
33
|
* Get states about Internet Connection.
|
|
54
34
|
*
|
|
55
|
-
* @returns An object defining
|
|
35
|
+
* @returns An object defining network status and `NetworkInformation`. See {@link Connection} for more info.
|
|
56
36
|
*/
|
|
57
|
-
declare const useConnection: () =>
|
|
37
|
+
declare const useConnection: () => Connection;
|
|
58
38
|
|
|
59
39
|
interface UseDarkModeOutput {
|
|
60
40
|
/**
|
|
@@ -169,6 +149,7 @@ declare function useDocumentVisibility(otpions: StateDisabledUseDocumentVisibili
|
|
|
169
149
|
*/
|
|
170
150
|
declare function useDocumentVisibility(otpions?: UseDocumentVisibilityOptions): boolean;
|
|
171
151
|
|
|
152
|
+
type EventListenerTarget = (Document | HTMLElement | EventTarget | null | undefined);
|
|
172
153
|
/**
|
|
173
154
|
* Specifies characteristics about the event listener.
|
|
174
155
|
*
|
|
@@ -289,7 +270,7 @@ interface DocumentListenerOptions<K extends keyof DocumentEventMap> extends Comm
|
|
|
289
270
|
* The `Document` reference or a React RefObject of the `Document`.
|
|
290
271
|
*
|
|
291
272
|
*/
|
|
292
|
-
target
|
|
273
|
+
target?: Document | null | React.RefObject<Document | null | undefined>;
|
|
293
274
|
/**
|
|
294
275
|
* The Document Event listener.
|
|
295
276
|
*
|
|
@@ -297,14 +278,22 @@ interface DocumentListenerOptions<K extends keyof DocumentEventMap> extends Comm
|
|
|
297
278
|
*/
|
|
298
279
|
listener: DocumentEventListener<K>;
|
|
299
280
|
}
|
|
300
|
-
interface
|
|
281
|
+
interface EventTargetListenerOptions<T extends EventTarget, K extends keyof HTMLElementEventMap> extends CommonListenerOptions {
|
|
301
282
|
/**
|
|
302
283
|
* The React RefObject of the target where the listener get attached to.
|
|
303
284
|
*
|
|
304
285
|
*/
|
|
305
|
-
target
|
|
286
|
+
target?: T | React.RefObject<T | null | undefined>;
|
|
306
287
|
/**
|
|
307
|
-
* The
|
|
288
|
+
* The `EventTarget` Event listener.
|
|
289
|
+
*
|
|
290
|
+
* @param event The event object that implements the [`Event`](https://developer.mozilla.org/en-US/docs/Web/API/Event) interface.
|
|
291
|
+
*/
|
|
292
|
+
listener: ElementEventListener<K>;
|
|
293
|
+
}
|
|
294
|
+
interface ElementListenerOptions<T extends HTMLElement, K extends keyof HTMLElementEventMap> extends Omit<EventTargetListenerOptions<T, K>, 'listener'> {
|
|
295
|
+
/**
|
|
296
|
+
* The `HTMLElement` Event listener.
|
|
308
297
|
*
|
|
309
298
|
* @param event The event object that implements the [`Event`](https://developer.mozilla.org/en-US/docs/Web/API/Event) interface.
|
|
310
299
|
*/
|
|
@@ -329,7 +318,7 @@ interface CustomEventListenerOptions<T extends Record<string, Event>, K extends
|
|
|
329
318
|
*
|
|
330
319
|
* If not set, the listener will get attached to the `Window` object.
|
|
331
320
|
*/
|
|
332
|
-
target?:
|
|
321
|
+
target?: EventListenerTarget | React.RefObject<EventListenerTarget>;
|
|
333
322
|
/**
|
|
334
323
|
* The Event listener.
|
|
335
324
|
*
|
|
@@ -404,6 +393,28 @@ declare function useEventListener<K extends keyof WindowEventMap>(type: K | K[],
|
|
|
404
393
|
* ```
|
|
405
394
|
*/
|
|
406
395
|
declare function useEventListener<K extends keyof DocumentEventMap>(type: K | K[], options: DocumentListenerOptions<K>): void;
|
|
396
|
+
/**
|
|
397
|
+
* Attach a new Event listener to an `EventTarget` object.
|
|
398
|
+
*
|
|
399
|
+
* @param type The event name or an array of event names.
|
|
400
|
+
* @param options An object defining init options. See {@link EventTargetListenerOptions} for more info.
|
|
401
|
+
*
|
|
402
|
+
* @example
|
|
403
|
+
*
|
|
404
|
+
* #### Add a new `EventTarget` event listener
|
|
405
|
+
*
|
|
406
|
+
* ```ts
|
|
407
|
+
* // A React.RefObject<EventTarget | null> can be used too.
|
|
408
|
+
*
|
|
409
|
+
* useEventListener( 'click', {
|
|
410
|
+
* target: new EventTarget(),
|
|
411
|
+
* listener: useCallback( () => {
|
|
412
|
+
* console.log( 'click event on `EventTarget` dispatched.' )
|
|
413
|
+
* }, [] )
|
|
414
|
+
* } )
|
|
415
|
+
* ```
|
|
416
|
+
*/
|
|
417
|
+
declare function useEventListener<T extends EventTarget, K extends keyof HTMLElementEventMap>(type: K | K[], options: EventTargetListenerOptions<T, K>): void;
|
|
407
418
|
/**
|
|
408
419
|
* Attach a new Event listener to a `HTMLElement` object.
|
|
409
420
|
*
|
|
@@ -1111,7 +1122,7 @@ declare const useIsFirstRender: () => boolean;
|
|
|
1111
1122
|
* @param options An object defining pagination input data. See {@link PaginateOptions} for more information.
|
|
1112
1123
|
* @returns A memoized object containing pagination informations based on the given options.
|
|
1113
1124
|
*/
|
|
1114
|
-
declare const usePagination: (options?: PaginateOptions) =>
|
|
1125
|
+
declare const usePagination: (options?: PaginateOptions) => _alessiofrittoli_math_utils.Pagination;
|
|
1115
1126
|
|
|
1116
1127
|
/**
|
|
1117
1128
|
* Check if the given `entry` is in the selection.
|
|
@@ -1473,7 +1484,7 @@ declare function useIntervalWhenVisible<T extends readonly unknown[]>(callback:
|
|
|
1473
1484
|
*
|
|
1474
1485
|
* @returns An object with timer utilities. See {@link StateTimerReturnType} for more info.
|
|
1475
1486
|
*/
|
|
1476
|
-
declare function useTimeout<T extends readonly unknown[]>(callback
|
|
1487
|
+
declare function useTimeout<T extends readonly unknown[]>(callback?: TimerHandler<T>, options?: StateTimerOptions<T>): StateTimerReturnType;
|
|
1477
1488
|
/**
|
|
1478
1489
|
* Schedules execution of a one-time `callback` after `delay` milliseconds.
|
|
1479
1490
|
*
|
|
@@ -1523,4 +1534,4 @@ declare function useTimeout<T extends readonly unknown[]>(callback: TimerHandler
|
|
|
1523
1534
|
*/
|
|
1524
1535
|
declare const useLightTimeout: <T extends readonly unknown[]>(callback: TimerHandler<T>, options?: BasicTimerOptions<T>) => void;
|
|
1525
1536
|
|
|
1526
|
-
export { type AddEventListenerOptions, type BasicTimerOptions, type ChangeHandler, type CommonListenerOptions, type
|
|
1537
|
+
export { type AddEventListenerOptions, type BasicTimerOptions, type ChangeHandler, type CommonListenerOptions, type CustomEventListenerOptions, type DocumentEventListener, type DocumentListenerOptions, type ElementEventListener, type ElementListenerOptions, type EventListenerTarget, type EventTargetListenerOptions, 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 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, 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
|
|
2
|
-
import
|
|
3
|
-
import
|
|
4
|
-
import { PaginateOptions } from '@alessiofrittoli/math-utils/helpers';
|
|
1
|
+
import { Connection, DeferredTask } from '@alessiofrittoli/web-utils';
|
|
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
|
|
22
|
+
declare const useLocalStorage: <T = string>(key: string, initial?: T) => [Value<T>, SetValue<Value<T>>];
|
|
24
23
|
|
|
25
24
|
/**
|
|
26
25
|
* useSessionStorage hook.
|
|
@@ -28,33 +27,14 @@ 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
|
|
30
|
+
declare const useSessionStorage: <T = string>(key: string, initial?: T) => [Value<T>, SetValue<Value<T>>];
|
|
32
31
|
|
|
33
|
-
type Connection = 'online' | 'offline';
|
|
34
|
-
declare const getState: (online: boolean) => "online" | "offline";
|
|
35
|
-
interface UseConnectionReturnType {
|
|
36
|
-
/**
|
|
37
|
-
* Indicates the connections status.
|
|
38
|
-
*
|
|
39
|
-
*/
|
|
40
|
-
connection: Connection;
|
|
41
|
-
/**
|
|
42
|
-
* Indicates whether the current device is online.
|
|
43
|
-
*
|
|
44
|
-
*/
|
|
45
|
-
isOnline: boolean;
|
|
46
|
-
/**
|
|
47
|
-
* Indicates whether the current device is offline.
|
|
48
|
-
*
|
|
49
|
-
*/
|
|
50
|
-
isOffline: boolean;
|
|
51
|
-
}
|
|
52
32
|
/**
|
|
53
33
|
* Get states about Internet Connection.
|
|
54
34
|
*
|
|
55
|
-
* @returns An object defining
|
|
35
|
+
* @returns An object defining network status and `NetworkInformation`. See {@link Connection} for more info.
|
|
56
36
|
*/
|
|
57
|
-
declare const useConnection: () =>
|
|
37
|
+
declare const useConnection: () => Connection;
|
|
58
38
|
|
|
59
39
|
interface UseDarkModeOutput {
|
|
60
40
|
/**
|
|
@@ -169,6 +149,7 @@ declare function useDocumentVisibility(otpions: StateDisabledUseDocumentVisibili
|
|
|
169
149
|
*/
|
|
170
150
|
declare function useDocumentVisibility(otpions?: UseDocumentVisibilityOptions): boolean;
|
|
171
151
|
|
|
152
|
+
type EventListenerTarget = (Document | HTMLElement | EventTarget | null | undefined);
|
|
172
153
|
/**
|
|
173
154
|
* Specifies characteristics about the event listener.
|
|
174
155
|
*
|
|
@@ -289,7 +270,7 @@ interface DocumentListenerOptions<K extends keyof DocumentEventMap> extends Comm
|
|
|
289
270
|
* The `Document` reference or a React RefObject of the `Document`.
|
|
290
271
|
*
|
|
291
272
|
*/
|
|
292
|
-
target
|
|
273
|
+
target?: Document | null | React.RefObject<Document | null | undefined>;
|
|
293
274
|
/**
|
|
294
275
|
* The Document Event listener.
|
|
295
276
|
*
|
|
@@ -297,14 +278,22 @@ interface DocumentListenerOptions<K extends keyof DocumentEventMap> extends Comm
|
|
|
297
278
|
*/
|
|
298
279
|
listener: DocumentEventListener<K>;
|
|
299
280
|
}
|
|
300
|
-
interface
|
|
281
|
+
interface EventTargetListenerOptions<T extends EventTarget, K extends keyof HTMLElementEventMap> extends CommonListenerOptions {
|
|
301
282
|
/**
|
|
302
283
|
* The React RefObject of the target where the listener get attached to.
|
|
303
284
|
*
|
|
304
285
|
*/
|
|
305
|
-
target
|
|
286
|
+
target?: T | React.RefObject<T | null | undefined>;
|
|
306
287
|
/**
|
|
307
|
-
* The
|
|
288
|
+
* The `EventTarget` Event listener.
|
|
289
|
+
*
|
|
290
|
+
* @param event The event object that implements the [`Event`](https://developer.mozilla.org/en-US/docs/Web/API/Event) interface.
|
|
291
|
+
*/
|
|
292
|
+
listener: ElementEventListener<K>;
|
|
293
|
+
}
|
|
294
|
+
interface ElementListenerOptions<T extends HTMLElement, K extends keyof HTMLElementEventMap> extends Omit<EventTargetListenerOptions<T, K>, 'listener'> {
|
|
295
|
+
/**
|
|
296
|
+
* The `HTMLElement` Event listener.
|
|
308
297
|
*
|
|
309
298
|
* @param event The event object that implements the [`Event`](https://developer.mozilla.org/en-US/docs/Web/API/Event) interface.
|
|
310
299
|
*/
|
|
@@ -329,7 +318,7 @@ interface CustomEventListenerOptions<T extends Record<string, Event>, K extends
|
|
|
329
318
|
*
|
|
330
319
|
* If not set, the listener will get attached to the `Window` object.
|
|
331
320
|
*/
|
|
332
|
-
target?:
|
|
321
|
+
target?: EventListenerTarget | React.RefObject<EventListenerTarget>;
|
|
333
322
|
/**
|
|
334
323
|
* The Event listener.
|
|
335
324
|
*
|
|
@@ -404,6 +393,28 @@ declare function useEventListener<K extends keyof WindowEventMap>(type: K | K[],
|
|
|
404
393
|
* ```
|
|
405
394
|
*/
|
|
406
395
|
declare function useEventListener<K extends keyof DocumentEventMap>(type: K | K[], options: DocumentListenerOptions<K>): void;
|
|
396
|
+
/**
|
|
397
|
+
* Attach a new Event listener to an `EventTarget` object.
|
|
398
|
+
*
|
|
399
|
+
* @param type The event name or an array of event names.
|
|
400
|
+
* @param options An object defining init options. See {@link EventTargetListenerOptions} for more info.
|
|
401
|
+
*
|
|
402
|
+
* @example
|
|
403
|
+
*
|
|
404
|
+
* #### Add a new `EventTarget` event listener
|
|
405
|
+
*
|
|
406
|
+
* ```ts
|
|
407
|
+
* // A React.RefObject<EventTarget | null> can be used too.
|
|
408
|
+
*
|
|
409
|
+
* useEventListener( 'click', {
|
|
410
|
+
* target: new EventTarget(),
|
|
411
|
+
* listener: useCallback( () => {
|
|
412
|
+
* console.log( 'click event on `EventTarget` dispatched.' )
|
|
413
|
+
* }, [] )
|
|
414
|
+
* } )
|
|
415
|
+
* ```
|
|
416
|
+
*/
|
|
417
|
+
declare function useEventListener<T extends EventTarget, K extends keyof HTMLElementEventMap>(type: K | K[], options: EventTargetListenerOptions<T, K>): void;
|
|
407
418
|
/**
|
|
408
419
|
* Attach a new Event listener to a `HTMLElement` object.
|
|
409
420
|
*
|
|
@@ -1111,7 +1122,7 @@ declare const useIsFirstRender: () => boolean;
|
|
|
1111
1122
|
* @param options An object defining pagination input data. See {@link PaginateOptions} for more information.
|
|
1112
1123
|
* @returns A memoized object containing pagination informations based on the given options.
|
|
1113
1124
|
*/
|
|
1114
|
-
declare const usePagination: (options?: PaginateOptions) =>
|
|
1125
|
+
declare const usePagination: (options?: PaginateOptions) => _alessiofrittoli_math_utils.Pagination;
|
|
1115
1126
|
|
|
1116
1127
|
/**
|
|
1117
1128
|
* Check if the given `entry` is in the selection.
|
|
@@ -1473,7 +1484,7 @@ declare function useIntervalWhenVisible<T extends readonly unknown[]>(callback:
|
|
|
1473
1484
|
*
|
|
1474
1485
|
* @returns An object with timer utilities. See {@link StateTimerReturnType} for more info.
|
|
1475
1486
|
*/
|
|
1476
|
-
declare function useTimeout<T extends readonly unknown[]>(callback
|
|
1487
|
+
declare function useTimeout<T extends readonly unknown[]>(callback?: TimerHandler<T>, options?: StateTimerOptions<T>): StateTimerReturnType;
|
|
1477
1488
|
/**
|
|
1478
1489
|
* Schedules execution of a one-time `callback` after `delay` milliseconds.
|
|
1479
1490
|
*
|
|
@@ -1523,4 +1534,4 @@ declare function useTimeout<T extends readonly unknown[]>(callback: TimerHandler
|
|
|
1523
1534
|
*/
|
|
1524
1535
|
declare const useLightTimeout: <T extends readonly unknown[]>(callback: TimerHandler<T>, options?: BasicTimerOptions<T>) => void;
|
|
1525
1536
|
|
|
1526
|
-
export { type AddEventListenerOptions, type BasicTimerOptions, type ChangeHandler, type CommonListenerOptions, type
|
|
1537
|
+
export { type AddEventListenerOptions, type BasicTimerOptions, type ChangeHandler, type CommonListenerOptions, type CustomEventListenerOptions, type DocumentEventListener, type DocumentListenerOptions, type ElementEventListener, type ElementListenerOptions, type EventListenerTarget, type EventTargetListenerOptions, 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 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, 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, ()=>(i&&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, ()=>(r&&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, ()=>(i&&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 j=(e,n)=>I(e,n,"local");var ct=(e,n)=>I(e,n,"session");var ae={onLine:!0},ce=["online","offline"],ft= exports.useConnection =()=>{let[e,n]=_react.useState.call(void 0, ae),r=_react.useCallback.call(void 0, ()=>{n(_webutils.getConnection.call(void 0, ))},[]);return w("change",{target:e.network,listener:r,onLoad:r}),w(ce,{listener:r}),e};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,U={value:"",isTouched:!1,isValid:!0},B=(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 U}};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, B,{...U,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"})},[]),g=_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:g,focus:O,reset:D}};var Ut=(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 G=()=>{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 Gt=(e={})=>_react.useMemo.call(void 0, ()=>_mathutils.paginate.call(void 0, e),[e]);var Xt=(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(),g=S.indexOf(l.at(0)),E=S.indexOf(u);return S.slice(g,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 un=(e={})=>{let n=G(),r=M("(prefers-color-scheme: dark)"),{initial:t=r,docClassNames:i=[]}=e,[a,s]=j("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 J(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 w(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 gn=()=>M(_webutils.portraitMediaQuery);var Mn=()=>M("(pointer: coarse)");var Rn=(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 J({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 Ke=["input","select","textarea","button","[href]",'[tabindex]:not([tabindex="-1"])'].join(", "),Un= 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(Ke)),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 Qn=(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),g=_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&&!!g.current,v&&c&&await c({entry:T,observer:x}),E.current&&p&&await p({entry:T,observer:x}),u&&(v||!v&&g.current!=null)){let k={isEntering:v,isExiting:E.current};await u({entry:T,observer:x,...k})}if(g.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 jn=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 ee=(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 Yn=(e,n=500)=>{let[r,t]=_react.useState.call(void 0, e),i=_react.useMemo.call(void 0, ()=>[e],[e]);return ee(t,{delay:n,args:i}),r};function te(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 sr=(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 lr(e,n={}){let{autoplay:r=!0}=n,t=te(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 fr(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.useConnection = ft; exports.useDarkMode = un; exports.useDebounce = Yn; exports.useDeferCallback = Ut; exports.useDocumentVisibility = J; exports.useEffectOnce = R; exports.useEventListener = w; exports.useFocusTrap = Un; exports.useInView = Qn; exports.useInput = Ht; exports.useInterval = te; exports.useIntervalWhenVisible = lr; exports.useIsClient = G; exports.useIsFirstRender = V; exports.useIsPortrait = gn; exports.useIsTouchDevice = Mn; exports.useLightInterval = sr; exports.useLightTimeout = ee; exports.useLocalStorage = j; exports.useMediaQuery = M; exports.usePagination = Gt; exports.useScrollBlock = jn; exports.useSelection = Xt; exports.useSessionStorage = ct; exports.useStorage = I; exports.useTimeout = fr; exports.useUpdateEffect = L; exports.useWakeLock = Rn;
|
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(()=>(i&&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(()=>(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 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(()=>(i&&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 P,useEffect as re,useState as oe}from"react";import{LocalStorage as $,SessionStorage as j}from"@alessiofrittoli/web-utils";var V=(e,n,r="local")=>{let t=P(()=>(r==="local"?$:j).get(e)??n,[r,e,n]),[i,a]=oe(n),s=P(o=>{a(c=>{let p=o instanceof Function?o(c):o;return(typeof window<"u"&&r==="local"?$:j).set(e,p),p})},[r,e]);return re(()=>{a(t())},[t]),[i,s]};var B=(e,n)=>V(e,n,"local");var ut=(e,n)=>V(e,n,"session");import{useCallback as se,useState as ie}from"react";import{getConnection as ae}from"@alessiofrittoli/web-utils";var ce={onLine:!0},ue=["online","offline"],Tt=()=>{let[e,n]=ie(ce),r=se(()=>{n(ae())},[]);return U("change",{target:e.network,listener:r,onLoad:r}),U(ue,{listener:r}),e};import{useCallback as K,useEffect as J,useRef as Me}from"react";import{useCallback as M,useMemo as G,useReducer as me}from"react";import{useEffect as pe}from"react";import{useRef as le}from"react";var H=()=>{let e=le(!0);return e.current?(e.current=!1,!0):e.current};var h=(e,n)=>{let r=H();pe(()=>{if(!r)return e()},n)};import{isEmpty as de}from"@alessiofrittoli/web-utils";var R=e=>typeof e=="string"?de(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:!R(e.value??"")};case"RESET":return W}};var Rt=(e={})=>{let{inputRef:n}=e,{initialValue:r}=e,{touchTimeout:t=600}=e,{validate:i,parse:a}=e,{onChange:s}=e,[o,c]=me(N,{...W,value:r}),p=G(()=>a?a(o.value):o.value,[o.value,a]),u=G(()=>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,b=E==="checkbox"?S.checked:S.value;c({type:"CHANGE",value:b}),s?.(a?a(b):b)},[s,a]),g=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:g,setValue:x,submit:O,focus:k,reset:w}};import{useCallback as fe}from"react";import{deferCallback as Te}from"@alessiofrittoli/web-utils";var Wt=(e,n)=>fe(Te(e),n);import{useEffect as ye}from"react";var C=e=>{let n=H();ye(()=>{if(n)return e()},[])};import{useEffect as ve,useState as Ee}from"react";var _=()=>{let[e,n]=Ee(!1);return ve(()=>n(!0),[]),e};import{useMemo as xe}from"react";import{paginate as Se}from"@alessiofrittoli/math-utils";var _t=(e={})=>xe(()=>Se(e),[e]);import{useCallback as D,useState as ge}from"react";var Yt=(e,n=[])=>{let[r,t]=ge(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 g=[...d].reverse(),O=g.indexOf(l.at(0)),x=g.indexOf(u);return g.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 Oe,useEffect as ke,useState as be}from"react";import{getMediaMatches as z}from"@alessiofrittoli/web-utils";function L(e,n={}){let{updateState:r=!0,onChange:t}=n,[i,a]=be(z(e)),s=Oe(()=>{let o=z(e);r&&a(o),t?.(o)},[e,r,t]);if(ke(()=>{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 ln=(e={})=>{let n=_(),r=L("(prefers-color-scheme: dark)"),{initial:t=r,docClassNames:i=[]}=e,[a,s]=B("dark-mode",t),o=a??r,[c,p]=i,u=Me({light:"",dark:""});return h(()=>{s(r)},[r,s]),J(()=>{c&&document.documentElement.classList.toggle(c,o),p&&document.documentElement.classList.toggle(p,!o)},[o,c,p]),J(()=>{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:K(()=>s(l=>!l),[s]),enableDarkMode:K(()=>s(!0),[s]),disableDarkMode:K(()=>s(!1),[s])}};import{useCallback as Le,useEffect as he,useState as Ie}from"react";function X(e={}){let{updateState:n=!0,onVisibilityChange:r}=e,[t,i]=Ie(!1),a=Le(()=>{let s=!document.hidden;n&&i(s),r?.(s)},[n,r]);if(C(()=>{n&&i(!document.hidden)}),he(()=>(document.addEventListener("visibilitychange",a),()=>document.removeEventListener("visibilitychange",a)),[a]),n)return t}import{useEffect as Ve}from"react";function U(e,n){let{target:r,query:t,options:i,listener:a,onLoad:s,onCleanUp:o}=n;Ve(()=>{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 He}from"@alessiofrittoli/web-utils";var On=()=>L(He);var Ln=()=>L("(pointer: coarse)");import{useCallback as I,useEffect as Re,useRef as Ce,useState as De}from"react";var Cn=(e={})=>{let{onMount:n=!0,onError:r}=e,[t,i]=De(null),a=Ce(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 X({updateState:!1,onVisibilityChange:I(l=>{if(l&&!s&&a.current)return o();if(!l)return c()},[s,o,c])}),C(()=>{s||!n||o()}),Re(()=>{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 Y,useEffect as we,useMemo as Ue,useRef as We,useState as Ke}from"react";var Ae=["input","select","textarea","button","[href]",'[tabindex]:not([tabindex="-1"])'].join(", "),Wn=e=>{let n=Ue(()=>e?.current,[e]),[r,t]=Ke(!1),i=We(null),a=Y(o=>{i.current=document.activeElement;let c=o||n||!1;if(c)return t(c)},[n]),s=Y(()=>{i.current?.focus(),t(!1)},[]);return we(()=>{if(!r)return;let o=c=>{if(c.key!=="Tab")return;let p=Array.from(r.querySelectorAll(Ae)),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 Qe,useMemo as Fe,useRef as A,useState as Z}from"react";var Fn=(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=A(!0),[d,T]=Z(r),[v,g]=Z(o),O=A(null),x=A(!1),k=Fe(()=>{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 b={isEntering:E,isExiting:x.current};await u({entry:y,observer:S,...b})}if(O.current=E,!l.current)return;T(E)}catch(b){console.error(b)}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 Qe(()=>{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:g}};import{useCallback as ee,useMemo as qe}from"react";import{blockScroll as Pe,restoreScroll as $e}from"@alessiofrittoli/web-utils";var Bn=e=>{let n=qe(()=>e?.current,[e]),r=ee(()=>Pe(n||void 0),[n]),t=ee(()=>$e(n||void 0),[n]);return[r,t]};import{useMemo as Be,useState as Ne}from"react";import{useEffect as je}from"react";var te=(e,n={})=>{let{delay:r=1,args:t}=n;je(()=>{let i=setTimeout(e,r,...t||[]);return()=>clearTimeout(i)},[r,t,e])};var Zn=(e,n=500)=>{let[r,t]=Ne(e),i=Be(()=>[e],[e]);return te(t,{delay:n,args:i}),r};import{useCallback as Q,useEffect as Ge,useRef as _e,useState as ze}from"react";function ne(e,n={}){let{delay:r=1,args:t,autoplay:i=!0,runOnStart:a=!1,updateState:s=!1}=n,o=_e(void 0),[c,p]=ze(i),u=Q(()=>o.current?(clearInterval(o.current),o.current=void 0,!0):!1,[]),l=Q(()=>{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=Q(()=>{u()&&s&&p(!1)},[s,u]);return Ge(()=>(i&&l(),()=>d()),[i,l,d]),s?{isActive:c,start:l,stop:d}:{start:l,stop:d}}import{useEffect as Je}from"react";var ir=(e,n={})=>{let{delay:r=1,args:t}=n;Je(()=>{let i=setInterval(e,r,...t||[]);return()=>clearInterval(i)},[r,t,e])};import{useCallback as F,useEffect as Xe}from"react";function pr(e,n={}){let{autoplay:r=!0}=n,t=ne(e,{autoplay:!1,...n}),{start:i,stop:a}=t,s=F(()=>document.hidden?a():i(),[i,a]),o=F(()=>{if(document.addEventListener("visibilitychange",s),!document.hidden)return i()},[i,s]),c=F(()=>{a(),document.removeEventListener("visibilitychange",s)},[a,s]);return Xe(()=>(r&&o(),()=>c()),[r,o,c]),{...t,start:o,stop:c}}import{useCallback as q,useEffect as Ye,useRef as Ze,useState as et}from"react";function Tr(e,n={}){let{delay:r=1,args:t,autoplay:i=!0,runOnStart:a=!1,updateState:s=!1}=n,o=Ze(void 0),[c,p]=et(i),u=q(()=>o.current?(clearTimeout(o.current),o.current=void 0,!0):!1,[]),l=q(()=>{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=q(()=>{u()&&s&&p(!1)},[s,u]);return Ye(()=>(i&&l(),()=>d()),[i,l,d]),s?{isActive:c,start:l,stop:d}:{start:l,stop:d}}export{Tt as useConnection,ln as useDarkMode,Zn as useDebounce,Wt as useDeferCallback,X as useDocumentVisibility,C as useEffectOnce,U as useEventListener,Wn as useFocusTrap,Fn as useInView,Rt as useInput,ne as useInterval,pr as useIntervalWhenVisible,_ as useIsClient,H as useIsFirstRender,On as useIsPortrait,Ln as useIsTouchDevice,ir as useLightInterval,te as useLightTimeout,B as useLocalStorage,L as useMediaQuery,_t as usePagination,Bn as useScrollBlock,Yt as useSelection,ut as useSessionStorage,V as useStorage,Tr as useTimeout,h as useUpdateEffect,Cn as useWakeLock};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@alessiofrittoli/react-hooks",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "4.0.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.
|
|
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,16 +105,16 @@
|
|
|
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.
|
|
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.
|
|
114
|
+
"eslint": "^10.0.2",
|
|
115
115
|
"eslint-plugin-react": "^7.37.5",
|
|
116
116
|
"eslint-plugin-react-hooks": "^7.0.1",
|
|
117
|
-
"globals": "^17.
|
|
117
|
+
"globals": "^17.4.0",
|
|
118
118
|
"http-server": "^14.1.1",
|
|
119
119
|
"jest": "^30.2.0",
|
|
120
120
|
"jest-environment-jsdom": "^30.2.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.
|
|
127
|
+
"typescript-eslint": "^8.56.1"
|
|
128
128
|
},
|
|
129
129
|
"dependencies": {
|
|
130
|
-
"@alessiofrittoli/math-utils": "^
|
|
130
|
+
"@alessiofrittoli/math-utils": "^2.0.0",
|
|
131
131
|
"@alessiofrittoli/type-utils": "^1.9.0",
|
|
132
|
-
"@alessiofrittoli/web-utils": "^1.
|
|
132
|
+
"@alessiofrittoli/web-utils": "^2.1.0"
|
|
133
133
|
}
|
|
134
134
|
}
|