@siberiacancode/reactuse 0.3.13 → 0.3.15
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 +71 -71
- package/dist/cjs/helpers/createContext/createContext.cjs.map +1 -1
- package/dist/cjs/helpers/createContextHook/createContextHook.cjs +2 -0
- package/dist/cjs/helpers/createContextHook/createContextHook.cjs.map +1 -0
- package/dist/cjs/helpers/createSharedHook/createSharedHook.cjs +2 -0
- package/dist/cjs/helpers/createSharedHook/createSharedHook.cjs.map +1 -0
- package/dist/cjs/hooks/useBatchedCallback/useBatchedCallback.cjs +1 -1
- package/dist/cjs/hooks/useBatchedCallback/useBatchedCallback.cjs.map +1 -1
- package/dist/cjs/hooks/useDropZone/useDropZone.cjs +1 -1
- package/dist/cjs/hooks/useDropZone/useDropZone.cjs.map +1 -1
- package/dist/cjs/hooks/useField/useField.cjs +1 -1
- package/dist/cjs/hooks/useField/useField.cjs.map +1 -1
- package/dist/cjs/hooks/useHotkeys/useHotkeys.cjs.map +1 -1
- package/dist/cjs/hooks/useImage/useImage.cjs.map +1 -1
- package/dist/cjs/hooks/useMediaQuery/useMediaQuery.cjs.map +1 -1
- package/dist/cjs/hooks/useMouse/useMouse.cjs +1 -1
- package/dist/cjs/hooks/useMouse/useMouse.cjs.map +1 -1
- package/dist/cjs/hooks/useMutation/useMutation.cjs +1 -1
- package/dist/cjs/hooks/useMutation/useMutation.cjs.map +1 -1
- package/dist/cjs/hooks/useNetwork/useNetwork.cjs.map +1 -1
- package/dist/cjs/hooks/useOptimistic/useOptimistic.cjs.map +1 -1
- package/dist/cjs/hooks/useOrientation/useOrientation.cjs.map +1 -1
- package/dist/cjs/hooks/useOtpCredential/useOtpCredential.cjs.map +1 -1
- package/dist/cjs/hooks/useParallax/useParallax.cjs.map +1 -1
- package/dist/cjs/hooks/usePostMessage/usePostMessage.cjs.map +1 -1
- package/dist/cjs/hooks/useProgress/useProgress.cjs +1 -1
- package/dist/cjs/hooks/useProgress/useProgress.cjs.map +1 -1
- package/dist/cjs/hooks/useScroll/useScroll.cjs +1 -1
- package/dist/cjs/hooks/useScroll/useScroll.cjs.map +1 -1
- package/dist/cjs/hooks/useSticky/useSticky.cjs.map +1 -1
- package/dist/cjs/hooks/useStorage/useStorage.cjs.map +1 -1
- package/dist/cjs/hooks/useTextDirection/useTextDirection.cjs.map +1 -1
- package/dist/cjs/hooks/useTextareaAutosize/useTextareaAutosize.cjs.map +1 -1
- package/dist/cjs/hooks/useUrlSearchParam/useUrlSearchParam.cjs.map +1 -1
- package/dist/cjs/hooks/useUrlSearchParams/useUrlSearchParams.cjs.map +1 -1
- package/dist/cjs/hooks/useVirtualKeyboard/useVirtualKeyboard.cjs.map +1 -1
- package/dist/cjs/hooks/useVisibility/useVisibility.cjs.map +1 -1
- package/dist/cjs/hooks/useWakeLock/useWakeLock.cjs.map +1 -1
- package/dist/cjs/hooks/useWebSocket/useWebSocket.cjs.map +1 -1
- package/dist/cjs/index.cjs +1 -1
- package/dist/cjs/utils/helpers/isTarget.cjs.map +1 -1
- package/dist/esm/helpers/createContext/createContext.mjs.map +1 -1
- package/dist/esm/helpers/createContextHook/createContextHook.mjs +13 -0
- package/dist/esm/helpers/createContextHook/createContextHook.mjs.map +1 -0
- package/dist/esm/helpers/createSharedHook/createSharedHook.mjs +42 -0
- package/dist/esm/helpers/createSharedHook/createSharedHook.mjs.map +1 -0
- package/dist/esm/hooks/useBatchedCallback/useBatchedCallback.mjs.map +1 -1
- package/dist/esm/hooks/useDropZone/useDropZone.mjs +27 -27
- package/dist/esm/hooks/useDropZone/useDropZone.mjs.map +1 -1
- package/dist/esm/hooks/useField/useField.mjs +42 -42
- package/dist/esm/hooks/useField/useField.mjs.map +1 -1
- package/dist/esm/hooks/useHotkeys/useHotkeys.mjs.map +1 -1
- package/dist/esm/hooks/useImage/useImage.mjs.map +1 -1
- package/dist/esm/hooks/useMediaQuery/useMediaQuery.mjs.map +1 -1
- package/dist/esm/hooks/useMouse/useMouse.mjs +37 -32
- package/dist/esm/hooks/useMouse/useMouse.mjs.map +1 -1
- package/dist/esm/hooks/useMutation/useMutation.mjs +29 -28
- package/dist/esm/hooks/useMutation/useMutation.mjs.map +1 -1
- package/dist/esm/hooks/useNetwork/useNetwork.mjs.map +1 -1
- package/dist/esm/hooks/useOptimistic/useOptimistic.mjs.map +1 -1
- package/dist/esm/hooks/useOrientation/useOrientation.mjs.map +1 -1
- package/dist/esm/hooks/useOtpCredential/useOtpCredential.mjs.map +1 -1
- package/dist/esm/hooks/useParallax/useParallax.mjs.map +1 -1
- package/dist/esm/hooks/usePostMessage/usePostMessage.mjs.map +1 -1
- package/dist/esm/hooks/useProgress/useProgress.mjs +13 -13
- package/dist/esm/hooks/useProgress/useProgress.mjs.map +1 -1
- package/dist/esm/hooks/useScroll/useScroll.mjs +62 -44
- package/dist/esm/hooks/useScroll/useScroll.mjs.map +1 -1
- package/dist/esm/hooks/useSticky/useSticky.mjs.map +1 -1
- package/dist/esm/hooks/useStorage/useStorage.mjs.map +1 -1
- package/dist/esm/hooks/useTextDirection/useTextDirection.mjs.map +1 -1
- package/dist/esm/hooks/useTextareaAutosize/useTextareaAutosize.mjs.map +1 -1
- package/dist/esm/hooks/useUrlSearchParam/useUrlSearchParam.mjs.map +1 -1
- package/dist/esm/hooks/useUrlSearchParams/useUrlSearchParams.mjs.map +1 -1
- package/dist/esm/hooks/useVirtualKeyboard/useVirtualKeyboard.mjs.map +1 -1
- package/dist/esm/hooks/useVisibility/useVisibility.mjs.map +1 -1
- package/dist/esm/hooks/useWakeLock/useWakeLock.mjs.map +1 -1
- package/dist/esm/hooks/useWebSocket/useWebSocket.mjs.map +1 -1
- package/dist/esm/index.mjs +389 -384
- package/dist/esm/index.mjs.map +1 -1
- package/dist/esm/utils/helpers/isTarget.mjs.map +1 -1
- package/dist/types/helpers/createContextHook/createContextHook.d.ts +26 -0
- package/dist/types/helpers/createSharedHook/createSharedHook.d.ts +21 -0
- package/dist/types/helpers/index.d.ts +2 -0
- package/dist/types/hooks/useField/useField.d.ts +7 -9
- package/dist/types/hooks/useMouse/useMouse.d.ts +17 -7
- package/dist/types/hooks/useProgress/useProgress.d.ts +4 -2
- package/dist/types/hooks/useScroll/useScroll.d.ts +13 -11
- package/dist/types/hooks/useUrlSearchParams/useUrlSearchParams.d.ts +0 -1
- package/package.json +5 -4
package/README.md
CHANGED
|
@@ -1,71 +1,71 @@
|
|
|
1
|
-
<div align="center">
|
|
2
|
-
<a href="https://siberiacancode.github.io/reactuse/">
|
|
3
|
-
<picture>
|
|
4
|
-
<img alt="React Use logo" src="https://siberiacancode.github.io/reactuse/logo.svg" height="128">
|
|
5
|
-
</picture>
|
|
6
|
-
</a>
|
|
7
|
-
<h1>React Use</h1>
|
|
8
|
-
|
|
9
|
-
<a href="https://www.npmjs.com/package/@siberiacancode/reactuse"><img alt="NPM version" src="https://img.shields.io/npm/v/@siberiacancode/reactuse.svg?style=for-the-badge&labelColor=000000"></a>
|
|
10
|
-
<a href="https://github.com/siberiacancode/reactuse/blob/main/LICENSE"><img alt="License" src="https://img.shields.io/npm/l/@siberiacancode/reactuse.svg?style=for-the-badge&labelColor=000000"></a>
|
|
11
|
-
<a href="https://github.com/siberiacancode/reactuse/discussions"><img alt="Join the community on GitHub" src="https://img.shields.io/badge/Join%20the%20community-blueviolet.svg?style=for-the-badge&logo=React&labelColor=000000&logoWidth=20"></a>
|
|
12
|
-
|
|
13
|
-
</div>
|
|
14
|
-
|
|
15
|
-
React Use delivers **production-ready hooks** that solve real-world problems. Built with **TypeScript-first** approach, **SSR compatibility**, and **tree-shaking optimization** - everything you need to build modern React applications. Improve your react applications with our library 📦 designed for comfort and speed.
|
|
16
|
-
|
|
17
|
-
## Documentation
|
|
18
|
-
|
|
19
|
-
Visit https://siberiacancode.github.io/reactuse to view the full documentation.
|
|
20
|
-
|
|
21
|
-
## Getting Started
|
|
22
|
-
|
|
23
|
-
```bash
|
|
24
|
-
npm install @siberiacancode/reactuse
|
|
25
|
-
```
|
|
26
|
-
|
|
27
|
-
```tsx
|
|
28
|
-
import { useCounter } from '@siberiacancode/reactuse';
|
|
29
|
-
|
|
30
|
-
const App = () => {
|
|
31
|
-
const counter = useCounter(0);
|
|
32
|
-
|
|
33
|
-
return (
|
|
34
|
-
<div>
|
|
35
|
-
<h1>Count: {counter.value}</h1>
|
|
36
|
-
<button onClick={() => counter.inc()}>+1</button>
|
|
37
|
-
<button onClick={() => counter.dec()}>-1</button>
|
|
38
|
-
</div>
|
|
39
|
-
);
|
|
40
|
-
};
|
|
41
|
-
```
|
|
42
|
-
|
|
43
|
-
## CLI installation
|
|
44
|
-
|
|
45
|
-
Use the CLI to add hooks to your project with [useverse](https://www.npmjs.com/package/useverse).
|
|
46
|
-
|
|
47
|
-
```bash
|
|
48
|
-
npx useverse@latest init
|
|
49
|
-
```
|
|
50
|
-
|
|
51
|
-
```bash
|
|
52
|
-
npx useverse@latest add [hook]
|
|
53
|
-
```
|
|
54
|
-
|
|
55
|
-
You will be presented with a list of hooks to choose from:
|
|
56
|
-
|
|
57
|
-
```bash
|
|
58
|
-
Which hooks would you like to add? › Space to select. A to toggle all.
|
|
59
|
-
Enter to submit.
|
|
60
|
-
|
|
61
|
-
◯ useActiveElement
|
|
62
|
-
◯ useAsync
|
|
63
|
-
◯ useBattery
|
|
64
|
-
◯ useBluetooth
|
|
65
|
-
◯ useBoolean
|
|
66
|
-
◯ useBreakpoints
|
|
67
|
-
◯ useBrowserLanguage
|
|
68
|
-
◯ useClickOutside
|
|
69
|
-
◯ useClipboard
|
|
70
|
-
◯ useConst
|
|
71
|
-
```
|
|
1
|
+
<div align="center">
|
|
2
|
+
<a href="https://siberiacancode.github.io/reactuse/">
|
|
3
|
+
<picture>
|
|
4
|
+
<img alt="React Use logo" src="https://siberiacancode.github.io/reactuse/logo.svg" height="128">
|
|
5
|
+
</picture>
|
|
6
|
+
</a>
|
|
7
|
+
<h1>React Use</h1>
|
|
8
|
+
|
|
9
|
+
<a href="https://www.npmjs.com/package/@siberiacancode/reactuse"><img alt="NPM version" src="https://img.shields.io/npm/v/@siberiacancode/reactuse.svg?style=for-the-badge&labelColor=000000"></a>
|
|
10
|
+
<a href="https://github.com/siberiacancode/reactuse/blob/main/LICENSE"><img alt="License" src="https://img.shields.io/npm/l/@siberiacancode/reactuse.svg?style=for-the-badge&labelColor=000000"></a>
|
|
11
|
+
<a href="https://github.com/siberiacancode/reactuse/discussions"><img alt="Join the community on GitHub" src="https://img.shields.io/badge/Join%20the%20community-blueviolet.svg?style=for-the-badge&logo=React&labelColor=000000&logoWidth=20"></a>
|
|
12
|
+
|
|
13
|
+
</div>
|
|
14
|
+
|
|
15
|
+
React Use delivers **production-ready hooks** that solve real-world problems. Built with **TypeScript-first** approach, **SSR compatibility**, and **tree-shaking optimization** - everything you need to build modern React applications. Improve your react applications with our library 📦 designed for comfort and speed.
|
|
16
|
+
|
|
17
|
+
## Documentation
|
|
18
|
+
|
|
19
|
+
Visit https://siberiacancode.github.io/reactuse to view the full documentation.
|
|
20
|
+
|
|
21
|
+
## Getting Started
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
npm install @siberiacancode/reactuse
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
```tsx
|
|
28
|
+
import { useCounter } from '@siberiacancode/reactuse';
|
|
29
|
+
|
|
30
|
+
const App = () => {
|
|
31
|
+
const counter = useCounter(0);
|
|
32
|
+
|
|
33
|
+
return (
|
|
34
|
+
<div>
|
|
35
|
+
<h1>Count: {counter.value}</h1>
|
|
36
|
+
<button onClick={() => counter.inc()}>+1</button>
|
|
37
|
+
<button onClick={() => counter.dec()}>-1</button>
|
|
38
|
+
</div>
|
|
39
|
+
);
|
|
40
|
+
};
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
## CLI installation
|
|
44
|
+
|
|
45
|
+
Use the CLI to add hooks to your project with [useverse](https://www.npmjs.com/package/useverse).
|
|
46
|
+
|
|
47
|
+
```bash
|
|
48
|
+
npx useverse@latest init
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
npx useverse@latest add [hook]
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
You will be presented with a list of hooks to choose from:
|
|
56
|
+
|
|
57
|
+
```bash
|
|
58
|
+
Which hooks would you like to add? › Space to select. A to toggle all.
|
|
59
|
+
Enter to submit.
|
|
60
|
+
|
|
61
|
+
◯ useActiveElement
|
|
62
|
+
◯ useAsync
|
|
63
|
+
◯ useBattery
|
|
64
|
+
◯ useBluetooth
|
|
65
|
+
◯ useBoolean
|
|
66
|
+
◯ useBreakpoints
|
|
67
|
+
◯ useBrowserLanguage
|
|
68
|
+
◯ useClickOutside
|
|
69
|
+
◯ useClipboard
|
|
70
|
+
◯ useConst
|
|
71
|
+
```
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createContext.cjs","sources":["../../../../src/helpers/createContext/createContext.tsx"],"sourcesContent":["import type { JSX, ReactNode } from 'react';\n\nimport { createContext as createReactContext, useContext, useMemo, useState } from 'react';\n\n/** The create context options type */\nexport interface CreateContextOptions {\n /** Display name for the context (useful for debugging) */\n name?: string;\n /** Whether to throw an error if context is used outside of Provider */\n strict?: boolean;\n}\n\n/** The context value type */\nexport interface ContextValue<Value> {\n /** The context value */\n value: Value | undefined;\n /** The context set function */\n set: (value: Value) => void;\n}\n\n/** The provider props type */\nexport interface ProviderProps<Value> {\n /** The children */\n children?: ReactNode;\n /** The initial value */\n initialValue?: Value;\n}\n\n/** The create context return type */\nexport interface CreateContextReturn<Value> {\n /** The context instance */\n instance: React.Context<ContextValue<Value>>;\n /** The provider component */\n Provider: (props: ProviderProps<Value>) => JSX.Element;\n /** The selector hook */\n useSelect: {\n <Selected>(selector: (value: Value) => Selected): Selected;\n (): ContextValue<Value>;\n };\n}\n\n/**\n * @name createContext\n * @description - Creates a typed context with additional utilities\n * @category Helpers\n * @usage high\n *\n * @template Value - The type of value that will be stored in the context\n * @param {Value | undefined} [defaultValue] - Default value for the context\n * @param {CreateContextOptions<Value>} [options] - Additional options for context creation\n * @returns {CreateContextReturn<Value>} Object containing context utilities and components\n *\n * @example\n * const { useSelect, instance, Provider } = createContext<number>(0);\n */\nexport const createContext = <Value,>(\n defaultValue: Value | undefined = undefined,\n options: CreateContextOptions = {}\n): CreateContextReturn<Value> => {\n const Context = createReactContext<{\n value: Value | undefined;\n set: (value: Value) => void;\n }>({\n value: defaultValue,\n set: () => {}\n });\n\n Context.displayName = options.name;\n\n function useSelect(): ContextValue<Value>;\n function useSelect<Selected>(selector: (value: Value) => Selected): Selected;\n function useSelect<Selected>(selector?: (value: Value) => Selected) {\n const context = useContext(Context);\n\n if (!context && options.strict) {\n throw new Error(`Context hook ${options.name} must be used inside a Provider`);\n }\n\n if (!selector) {\n return context;\n }\n\n return selector(context.value as Value);\n }\n\n const Provider = ({ children, initialValue }: ProviderProps<Value>) => {\n const [profile, setProfile] = useState<Value | undefined>(initialValue ?? defaultValue);\n\n const value = useMemo(\n () => ({\n value: profile,\n set: setProfile\n }),\n [profile]\n );\n\n return <Context value={value}>{children}</Context>;\n };\n\n return {\n useSelect,\n instance: Context,\n Provider\n } as const;\n};\n"],"names":["createContext","defaultValue","options","Context","createReactContext","useSelect","selector","context","useContext","children","initialValue","profile","setProfile","useState","value","useMemo","jsx"],"mappings":"wIAuDaA,EAAgB,CAC3BC,EAAkC,OAClCC,EAAgC,CAAA,IACD,CAC/B,MAAMC,EAAUC,EAAAA,cAGb,CACD,MAAOH,EACP,IAAK,IAAM,CAAA,CAAC,CACb,EAEDE,EAAQ,YAAcD,EAAQ,KAI9B,SAASG,EAAoBC,EAAuC,CAClE,MAAMC,EAAUC,EAAAA,WAAWL,CAAO,EAElC,GAAI,CAACI,GAAWL,EAAQ,OACtB,MAAM,IAAI,MAAM,gBAAgBA,EAAQ,IAAI,iCAAiC,EAG/E,OAAKI,EAIEA,EAASC,EAAQ,KAAc,EAH7BA,CAG6B,CAiBxC,MAAO,CACL,UAAAF,EACA,SAAUF,EACV,SAjBe,CAAC,CAAE,SAAAM,EAAU,aAAAC,KAAyC,CACrE,KAAM,CAACC,EAASC,CAAU,EAAIC,EAAAA,SAA4BH,GAAgBT,CAAY,EAEhFa,EAAQC,EAAAA,QACZ,KAAO,CACL,MAAOJ,EACP,IAAKC,CAAA,GAEP,CAACD,CAAO,CAAA,EAGV,OAAOK,EAAAA,IAACb,EAAA,CAAQ,MAAAW,EAAe,SAAAL,CAAA,CAAS,CAAA,CAMxC,CAEJ"}
|
|
1
|
+
{"version":3,"file":"createContext.cjs","sources":["../../../../src/helpers/createContext/createContext.tsx"],"sourcesContent":["import type { JSX, ReactNode } from 'react';\r\n\r\nimport { createContext as createReactContext, useContext, useMemo, useState } from 'react';\r\n\r\n/** The create context options type */\r\nexport interface CreateContextOptions {\r\n /** Display name for the context (useful for debugging) */\r\n name?: string;\r\n /** Whether to throw an error if context is used outside of Provider */\r\n strict?: boolean;\r\n}\r\n\r\n/** The context value type */\r\nexport interface ContextValue<Value> {\r\n /** The context value */\r\n value: Value | undefined;\r\n /** The context set function */\r\n set: (value: Value) => void;\r\n}\r\n\r\n/** The provider props type */\r\nexport interface ProviderProps<Value> {\r\n /** The children */\r\n children?: ReactNode;\r\n /** The initial value */\r\n initialValue?: Value;\r\n}\r\n\r\n/** The create context return type */\r\nexport interface CreateContextReturn<Value> {\r\n /** The context instance */\r\n instance: React.Context<ContextValue<Value>>;\r\n /** The provider component */\r\n Provider: (props: ProviderProps<Value>) => JSX.Element;\r\n /** The selector hook */\r\n useSelect: {\r\n <Selected>(selector: (value: Value) => Selected): Selected;\r\n (): ContextValue<Value>;\r\n };\r\n}\r\n\r\n/**\r\n * @name createContext\r\n * @description - Creates a typed context with additional utilities\r\n * @category Helpers\r\n * @usage high\r\n *\r\n * @template Value - The type of value that will be stored in the context\r\n * @param {Value | undefined} [defaultValue] - Default value for the context\r\n * @param {CreateContextOptions<Value>} [options] - Additional options for context creation\r\n * @returns {CreateContextReturn<Value>} Object containing context utilities and components\r\n *\r\n * @example\r\n * const { useSelect, instance, Provider } = createContext<number>(0);\r\n */\r\nexport const createContext = <Value,>(\r\n defaultValue: Value | undefined = undefined,\r\n options: CreateContextOptions = {}\r\n): CreateContextReturn<Value> => {\r\n const Context = createReactContext<{\r\n value: Value | undefined;\r\n set: (value: Value) => void;\r\n }>({\r\n value: defaultValue,\r\n set: () => {}\r\n });\r\n\r\n Context.displayName = options.name;\r\n\r\n function useSelect(): ContextValue<Value>;\r\n function useSelect<Selected>(selector: (value: Value) => Selected): Selected;\r\n function useSelect<Selected>(selector?: (value: Value) => Selected) {\r\n const context = useContext(Context);\r\n\r\n if (!context && options.strict) {\r\n throw new Error(`Context hook ${options.name} must be used inside a Provider`);\r\n }\r\n\r\n if (!selector) {\r\n return context;\r\n }\r\n\r\n return selector(context.value as Value);\r\n }\r\n\r\n const Provider = ({ children, initialValue }: ProviderProps<Value>) => {\r\n const [profile, setProfile] = useState<Value | undefined>(initialValue ?? defaultValue);\r\n\r\n const value = useMemo(\r\n () => ({\r\n value: profile,\r\n set: setProfile\r\n }),\r\n [profile]\r\n );\r\n\r\n return <Context value={value}>{children}</Context>;\r\n };\r\n\r\n return {\r\n useSelect,\r\n instance: Context,\r\n Provider\r\n } as const;\r\n};\r\n"],"names":["createContext","defaultValue","options","Context","createReactContext","useSelect","selector","context","useContext","children","initialValue","profile","setProfile","useState","value","useMemo","jsx"],"mappings":"wIAuDaA,EAAgB,CAC3BC,EAAkC,OAClCC,EAAgC,CAAA,IACD,CAC/B,MAAMC,EAAUC,EAAAA,cAGb,CACD,MAAOH,EACP,IAAK,IAAM,CAAA,CAAC,CACb,EAEDE,EAAQ,YAAcD,EAAQ,KAI9B,SAASG,EAAoBC,EAAuC,CAClE,MAAMC,EAAUC,EAAAA,WAAWL,CAAO,EAElC,GAAI,CAACI,GAAWL,EAAQ,OACtB,MAAM,IAAI,MAAM,gBAAgBA,EAAQ,IAAI,iCAAiC,EAG/E,OAAKI,EAIEA,EAASC,EAAQ,KAAc,EAH7BA,CAG6B,CAiBxC,MAAO,CACL,UAAAF,EACA,SAAUF,EACV,SAjBe,CAAC,CAAE,SAAAM,EAAU,aAAAC,KAAyC,CACrE,KAAM,CAACC,EAASC,CAAU,EAAIC,EAAAA,SAA4BH,GAAgBT,CAAY,EAEhFa,EAAQC,EAAAA,QACZ,KAAO,CACL,MAAOJ,EACP,IAAKC,CAAA,GAEP,CAACD,CAAO,CAAA,EAGV,OAAOK,EAAAA,IAACb,EAAA,CAAQ,MAAAW,EAAe,SAAAL,CAAA,CAAS,CAAA,CAMxC,CAEJ"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const c=require("react/jsx-runtime"),t=require("react"),u=o=>{const e=t.createContext(null);return{Provider:({children:r,params:n})=>{const s=o(...n);return c.jsx(e.Provider,{value:s,children:r})},use:()=>t.useContext(e)}};exports.createContextHook=u;
|
|
2
|
+
//# sourceMappingURL=createContextHook.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"createContextHook.cjs","sources":["../../../../src/helpers/createContextHook/createContextHook.tsx"],"sourcesContent":["import type { ReactNode } from 'react';\n\nimport { createContext, useContext } from 'react';\n\n/**\n * @name createContextHook\n * @description - Hook that runs inside a Provider; Provider accepts params (the hook's arguments). Use when you need a scoped instance per subtree.\n * @category Helpers\n * @usage low\n *\n * @warning - For complex interfaces, we strongly recommend using state management solutions outside of React like createStore, reatom, effector, or zustand instead of context\n *\n * @param useHook - The hook to run in the Provider (e.g. useMediaQuery)\n * @returns { Provider, use } — Provider takes params; use() returns the value and must be used inside Provider\n *\n * @example\n * const { Provider, use } = createContextHook(useMediaQuery);\n * <Provider params={[\"(max-width: 768px)\"]}>\n * <Component />\n * </Provider>\n * const matches = use();\n */\nexport const createContextHook = <Hook extends (...args: any[]) => any>(useHook: Hook) => {\n type Value = ReturnType<Hook>;\n const Context = createContext<Value | null>(null);\n\n const Provider = ({ children, params }: { children: ReactNode; params: Parameters<Hook> }) => {\n const value = useHook(...params) as Value;\n return <Context.Provider value={value}>{children}</Context.Provider>;\n };\n\n const use = () => useContext(Context);\n\n return { Provider, use };\n};\n"],"names":["createContextHook","useHook","Context","createContext","children","params","value","jsx","useContext"],"mappings":"wIAsBaA,EAA2DC,GAAkB,CAExF,MAAMC,EAAUC,EAAAA,cAA4B,IAAI,EAShD,MAAO,CAAE,SAPQ,CAAC,CAAE,SAAAC,EAAU,OAAAC,KAAgE,CAC5F,MAAMC,EAAQL,EAAQ,GAAGI,CAAM,EAC/B,OAAOE,EAAAA,IAACL,EAAQ,SAAR,CAAiB,MAAAI,EAAe,SAAAF,CAAA,CAAS,CAAA,EAKhC,IAFP,IAAMI,EAAAA,WAAWN,CAAO,CAEjB,CACrB"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const a=require("react/jsx-runtime"),s=require("react"),d=require("react-dom/client"),i=n=>{const e=document.createElement("div"),t=d.createRoot(e);return t.render(n),()=>{t.unmount(),e.remove()}},m=n=>{if(typeof window>"u"){const t=(...r)=>n(...r);return t.useShared=t,t}const e={state:void 0,listeners:new Set,mounted:!1,unmount:void 0};return function(...r){return e.mounted||(e.mounted=!0,queueMicrotask(()=>{const o=()=>{const u=n(...r);return s.useEffect(()=>{e.state=u,e.listeners.forEach(c=>c())},[u]),null};e.unmount=i(a.jsx(o,{}))})),s.useSyncExternalStore(o=>(e.listeners.add(o),()=>{e.listeners.delete(o),e.listeners.size<0&&e.unmount&&(e.unmount(),e.unmount=void 0,e.state=void 0,e.mounted=!1)}),()=>e.state,()=>e.state)}};exports.createSharedHook=m;exports.mount=i;
|
|
2
|
+
//# sourceMappingURL=createSharedHook.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"createSharedHook.cjs","sources":["../../../../src/helpers/createSharedHook/createSharedHook.tsx"],"sourcesContent":["import { useEffect, useSyncExternalStore } from 'react';\nimport { createRoot } from 'react-dom/client';\n\nexport const mount = (component: React.ReactNode) => {\n const container = document.createElement('div');\n const root = createRoot(container);\n root.render(component);\n return () => {\n root.unmount();\n container.remove();\n };\n};\n\n/**\n * @name createSharedHook\n * @description - One shared instance of the hook globally. First subscriber's args are used; when subscribers hit zero, the runner unmounts.\n * @category Helpers\n * @usage low\n *\n * @warning - For complex interfaces, we strongly recommend using state management solutions outside of React like createStore, reatom, effector, or zustand instead of context\n *\n * @template Hook - The hook to create a shared instance of\n * @param {Hook} useHook - The hook to create a shared instance of\n * @returns {Hook & { useShared: typeof useShared }} - The shared hook\n *\n * @example\n * const useSharedMediaQuery = createSharedHook(useMediaQuery);\n * const matches = useSharedMediaQuery(\"(max-width: 768px)\");\n */\nexport const createSharedHook = <Hook extends (...args: any[]) => any>(useHook: Hook) => {\n if (typeof window === 'undefined') {\n const fn = (...args: Parameters<Hook>) => useHook(...args);\n fn.useShared = fn;\n return fn;\n }\n\n type Value = ReturnType<Hook>;\n const store = {\n state: undefined as Value | undefined,\n listeners: new Set<() => void>(),\n mounted: false,\n unmount: undefined as (() => void) | undefined\n };\n\n return function useShared(...args: Parameters<Hook>): Value {\n if (!store.mounted) {\n store.mounted = true;\n queueMicrotask(() => {\n const HookContainer = () => {\n const value = useHook(...args) as Value;\n useEffect(() => {\n store.state = value;\n store.listeners.forEach((l) => l());\n }, [value]);\n return null;\n };\n\n store.unmount = mount(<HookContainer />);\n });\n }\n\n return useSyncExternalStore(\n (callback) => {\n store.listeners.add(callback);\n return () => {\n store.listeners.delete(callback);\n if (store.listeners.size < 0 && store.unmount) {\n store.unmount();\n store.unmount = undefined;\n store.state = undefined;\n store.mounted = false;\n }\n };\n },\n () => store.state,\n () => store.state\n ) as Value;\n };\n};\n"],"names":["mount","component","container","root","createRoot","createSharedHook","useHook","fn","args","store","HookContainer","value","useEffect","l","jsx","useSyncExternalStore","callback"],"mappings":"sKAGaA,EAASC,GAA+B,CACnD,MAAMC,EAAY,SAAS,cAAc,KAAK,EACxCC,EAAOC,EAAAA,WAAWF,CAAS,EACjC,OAAAC,EAAK,OAAOF,CAAS,EACd,IAAM,CACXE,EAAK,QAAA,EACLD,EAAU,OAAA,CAAO,CAErB,EAkBaG,EAA0DC,GAAkB,CACvF,GAAI,OAAO,OAAW,IAAa,CACjC,MAAMC,EAAK,IAAIC,IAA2BF,EAAQ,GAAGE,CAAI,EACzD,OAAAD,EAAG,UAAYA,EACRA,CAAA,CAIT,MAAME,EAAQ,CACZ,MAAO,OACP,cAAe,IACf,QAAS,GACT,QAAS,MAAA,EAGX,OAAO,YAAsBD,EAA+B,CAC1D,OAAKC,EAAM,UACTA,EAAM,QAAU,GAChB,eAAe,IAAM,CACnB,MAAMC,EAAgB,IAAM,CAC1B,MAAMC,EAAQL,EAAQ,GAAGE,CAAI,EAC7BI,OAAAA,EAAAA,UAAU,IAAM,CACdH,EAAM,MAAQE,EACdF,EAAM,UAAU,QAASI,GAAMA,GAAG,CAAA,EACjC,CAACF,CAAK,CAAC,EACH,IAAA,EAGTF,EAAM,QAAUT,EAAMc,EAAAA,IAACJ,EAAA,CAAA,CAAc,CAAE,CAAA,CACxC,GAGIK,EAAAA,qBACJC,IACCP,EAAM,UAAU,IAAIO,CAAQ,EACrB,IAAM,CACXP,EAAM,UAAU,OAAOO,CAAQ,EAC3BP,EAAM,UAAU,KAAO,GAAKA,EAAM,UACpCA,EAAM,QAAA,EACNA,EAAM,QAAU,OAChBA,EAAM,MAAQ,OACdA,EAAM,QAAU,GAClB,GAGJ,IAAMA,EAAM,MACZ,IAAMA,EAAM,KAAA,CACd,CAEJ"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("react"),o=(c,n)=>{const u=r.useRef(c),s=r.useRef(n),e=r.useRef([]);u.current=c,s.current=n;const a=()=>{if(!e.current.length)return;const t=e.current;e.current=[],u.current(t)};return r.useMemo(()=>{const t=(...l)=>{e.current.push(l),e.current.length>=s.current&&a()};return t.flush=a,t.cancel=()=>e.current=[],t},[])};exports.useBatchedCallback=o;
|
|
2
2
|
//# sourceMappingURL=useBatchedCallback.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useBatchedCallback.cjs","sources":["../../../../src/hooks/useBatchedCallback/useBatchedCallback.ts"],"sourcesContent":["import { useMemo, useRef } from 'react';\n\nexport type BatchedCallback<Params extends unknown[]> = ((...args: Params) => void) & {\n flush: () => void;\n cancel: () => void;\n};\n\n/**\n * @name useBatchedCallback\n * @description - Hook that batches calls and forwards them to a callback\n * @category Utilities\n * @usage medium\n *\n * @template Params The type of the params\n * @param {(batch: Params[]) => void} callback The callback that receives a batch of calls\n * @param {number} batchSize The maximum size of a batch before it is flushed\n * @returns {BatchedCallback<Params>} The batched callback with flush and cancel helpers\n *\n * @example\n * const batched = useBatchedCallback((batch) => console.log(batch), 5);\n */\nexport const useBatchedCallback = <Params extends unknown[]>(\n callback: (batch: Params[]) => void,\n size: number\n): BatchedCallback<Params> => {\n const
|
|
1
|
+
{"version":3,"file":"useBatchedCallback.cjs","sources":["../../../../src/hooks/useBatchedCallback/useBatchedCallback.ts"],"sourcesContent":["import { useMemo, useRef } from 'react';\n\nexport type BatchedCallback<Params extends unknown[]> = ((...args: Params) => void) & {\n flush: () => void;\n cancel: () => void;\n};\n\n/**\n * @name useBatchedCallback\n * @description - Hook that batches calls and forwards them to a callback\n * @category Utilities\n * @usage medium\n *\n * @template Params The type of the params\n * @param {(batch: Params[]) => void} callback The callback that receives a batch of calls\n * @param {number} batchSize The maximum size of a batch before it is flushed\n * @returns {BatchedCallback<Params>} The batched callback with flush and cancel helpers\n *\n * @example\n * const batched = useBatchedCallback((batch) => console.log(batch), 5);\n */\nexport const useBatchedCallback = <Params extends unknown[]>(\n callback: (batch: Params[]) => void,\n size: number\n): BatchedCallback<Params> => {\n const internalCallbackRef = useRef(callback);\n const sizeRef = useRef(size);\n const queueRef = useRef<Params[]>([]);\n\n internalCallbackRef.current = callback;\n sizeRef.current = size;\n\n const flush = () => {\n if (!queueRef.current.length) return;\n const batch = queueRef.current;\n queueRef.current = [];\n internalCallbackRef.current(batch);\n };\n\n const batched = useMemo(() => {\n const batchedCallback = (...args: Params) => {\n queueRef.current.push(args);\n if (queueRef.current.length >= sizeRef.current) flush();\n };\n\n batchedCallback.flush = flush;\n batchedCallback.cancel = () => (queueRef.current = []);\n\n return batchedCallback as BatchedCallback<Params>;\n }, []);\n\n return batched;\n};\n"],"names":["useBatchedCallback","callback","size","internalCallbackRef","useRef","sizeRef","queueRef","flush","batch","useMemo","batchedCallback","args"],"mappings":"yGAqBaA,EAAqB,CAChCC,EACAC,IAC4B,CAC5B,MAAMC,EAAsBC,EAAAA,OAAOH,CAAQ,EACrCI,EAAUD,EAAAA,OAAOF,CAAI,EACrBI,EAAWF,EAAAA,OAAiB,EAAE,EAEpCD,EAAoB,QAAUF,EAC9BI,EAAQ,QAAUH,EAElB,MAAMK,EAAQ,IAAM,CAClB,GAAI,CAACD,EAAS,QAAQ,OAAQ,OAC9B,MAAME,EAAQF,EAAS,QACvBA,EAAS,QAAU,CAAA,EACnBH,EAAoB,QAAQK,CAAK,CAAA,EAenC,OAZgBC,EAAAA,QAAQ,IAAM,CAC5B,MAAMC,EAAkB,IAAIC,IAAiB,CAC3CL,EAAS,QAAQ,KAAKK,CAAI,EACtBL,EAAS,QAAQ,QAAUD,EAAQ,SAASE,EAAA,CAAM,EAGxD,OAAAG,EAAgB,MAAQH,EACxBG,EAAgB,OAAS,IAAOJ,EAAS,QAAU,CAAA,EAE5CI,CAAA,EACN,EAAE,CAGP"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const c=require("react"),m=require("../useRefState/useRefState.cjs"),d=require("../../utils/helpers/isTarget.cjs"),D=((...n)=>{const o=d.isTarget(n[0])?n[0]:void 0,s=o?typeof n[1]=="object"?n[1]:{onDrop:n[1]}:typeof n[0]=="object"?n[0]:{onDrop:n[0]},i=m.useRefState(),u=c.useRef(0),[g,E]=c.useState(null),[p,l]=c.useState(!1),a=s.dataTypes,T=e=>{if(!e.dataTransfer)return null;const t=Array.from(e.dataTransfer.files);return s.multiple?t:t.length?[t[0]]:null},v=e=>a?typeof a=="function"?a(e):a.length?e.length?e.every(t=>a.some(r=>t.includes(r))):!1:!0:!0,L=e=>{const t=Array.from(e).map(f=>f.type),r=v(t),y=s.multiple||e.length<=1;return r&&y};return c.useEffect(()=>{if(!o&&!i.state)return;const e=o?d.isTarget.getElement(o):i.current;if(!e)return;const t=r=>{if(!r.dataTransfer)return;if(!L(r.dataTransfer.items)){r.dataTransfer.dropEffect="none";return}r.preventDefault(),r.dataTransfer.dropEffect="copy";const f=T(r);if(r.type==="drop"){u.current=0,l(!1),E(f),s.onDrop?.(f,r);return}if(r.type==="dragenter"){u.current+=1,l(!0),s.onEnter?.(r);return}if(r.type==="dragleave"){if(u.current-=1,u.current!==0)return;l(!1),s.onLeave?.(r);return}r.type==="dragover"&&s.onOver?.(r)};return e.addEventListener("dragenter",t),e.addEventListener("dragover",t),e.addEventListener("dragleave",t),e.addEventListener("drop",t),()=>{e.removeEventListener("dragenter",t),e.removeEventListener("dragover",t),e.removeEventListener("dragleave",t),e.removeEventListener("drop",t)}},[o&&d.isTarget.getRawElement(o),i.state]),o?{overed:p,files:g}:{ref:i,overed:p,files:g}});exports.useDropZone=D;
|
|
2
2
|
//# sourceMappingURL=useDropZone.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useDropZone.cjs","sources":["../../../../src/hooks/useDropZone/useDropZone.ts"],"sourcesContent":["import { useEffect, useRef, useState } from 'react';\n\nimport type { HookTarget } from '@/utils/helpers';\n\nimport { isTarget } from '@/utils/helpers';\n\nimport type { StateRef } from '../useRefState/useRefState';\n\nimport { useRefState } from '../useRefState/useRefState';\n\nexport type DropZoneDataTypes = ((types: string[]) => boolean) | string[];\n\nexport interface UseDropZoneOptions {\n /** The data types for drop zone */\n dataTypes?: DropZoneDataTypes;\n /** The multiple mode for drop zone */\n multiple?: boolean;\n /** The on drop callback */\n onDrop?: (files: File[] | null, event: DragEvent) => void;\n /** The on enter callback */\n onEnter?: (event: DragEvent) => void;\n /** The on leave callback */\n onLeave?: (event: DragEvent) => void;\n /** The on over callback */\n onOver?: (event: DragEvent) => void;\n}\n\nexport interface UseDropZoneReturn {\n /** The files that was dropped in drop zone */\n files: File[] | null;\n /** The over drop zone status */\n overed: boolean;\n}\n\nexport interface UseDropZone {\n (\n target: HookTarget,\n callback?: (files: File[] | null, event: DragEvent) => void\n ): UseDropZoneReturn;\n\n <Target extends Element>(\n callback?: (files: File[] | null, event: DragEvent) => void,\n target?: never\n ): UseDropZoneReturn & {\n ref: StateRef<Target>;\n };\n\n (target: HookTarget, options?: UseDropZoneOptions): UseDropZoneReturn;\n\n <Target extends Element>(\n options?: UseDropZoneOptions,\n target?: never\n ): UseDropZoneReturn & {\n ref: StateRef<Target>;\n };\n}\n\n/**\n * @name useDropZone\n * @description - Hook that provides drop zone functionality\n * @category Elements\n * @usage medium\n\n * @overload\n * @template Target The target element\n * @param {Target} target The target element drop zone's\n * @param {DataTypes} [options.dataTypes] The data types\n * @param {boolean} [options.multiple] The multiple mode\n * @param {(files: File[] | null, event: DragEvent) => void} [options.onDrop] The on drop callback function\n * @param {(event: DragEvent) => void} [options.onEnter] The on enter callback function\n * @param {(event: DragEvent) => void} [options.onLeave] The on leave callback function\n * @param {(event: DragEvent) => void} [options.onOver] The on over callback function\n * @returns {UseDropZoneReturn} The object with drop zone states\n *\n * @example\n * const { overed, files } = useDropZone(ref, options);\n *\n * @overload\n * @param {Target} target The target element drop zone's\n * @param {(files: File[] | null, event: DragEvent) => void} [callback] The callback function to be invoked on drop\n * @returns {UseDropZoneReturn} The object with drop zone states\n *\n * @example\n * const { overed, files } = useDropZone(ref, () => console.log('callback'));\n *\n * @overload\n * @param {DataTypes} [options.dataTypes] The data types\n * @param {boolean} [options.multiple] The multiple mode\n * @param {(files: File[] | null, event: DragEvent) => void} [options.onDrop] The on drop callback function\n * @param {(event: DragEvent) => void} [options.onEnter] The on enter callback function\n * @param {(event: DragEvent) => void} [options.onLeave] The on leave callback function\n * @param {(event: DragEvent) => void} [options.onOver] The on over callback function\n * @returns {UseDropZoneReturn & { ref: StateRef<Target> }} The object with drop zone states and ref\n *\n * @example\n * const { ref, overed, files } = useDropZone(options);\n *\n * @overload\n * @param {(files: File[] | null, event: DragEvent) => void} [callback] The callback function to be invoked on drop\n * @returns {UseDropZoneReturn & { ref: StateRef<Target> }} The object with drop zone states and ref\n *\n * @example\n * const { ref, overed, files } = useDropZone(() => console.log('callback'));\n */\nexport const useDropZone = ((...params: any[]) => {\n const target = (isTarget(params[0]) ? params[0] : undefined) as HookTarget | undefined;\n\n const options = (\n target\n ? typeof params[1] === 'object'\n ? params[1]\n : { onDrop: params[1] }\n : typeof params[0] === 'object'\n ? params[0]\n : { onDrop: params[0] }\n ) as UseDropZoneOptions;\n\n const internalRef = useRefState<Element>();\n\n const counterRef = useRef(0);\n const [files, setFiles] = useState<File[] | null>(null);\n const [overed, setOvered] = useState(false);\n\n const dataTypes = options.dataTypes;\n\n const getFiles = (event: DragEvent) => {\n if (!event.dataTransfer) return null;\n const list = Array.from(event.dataTransfer.files);\n if (options.multiple) return list;\n if (!list.length) return null;\n return [list[0]];\n };\n\n const checkDataTypes = (types: string[]) => {\n if (!dataTypes) return true;\n if (typeof dataTypes === 'function') return dataTypes(types);\n if (!dataTypes.length) return true;\n if (!types.length) return false;\n\n return types.every((type) => dataTypes.some((dataType) => type.includes(dataType)));\n };\n\n const checkValidity = (items: DataTransferItemList) => {\n const types = Array.from(items).map((item) => item.type);\n const dataTypesValid = checkDataTypes(types);\n const multipleFilesValid = options.multiple || items.length <= 1;\n\n return dataTypesValid && multipleFilesValid;\n };\n\n useEffect(() => {\n if (!target && !internalRef.state) return;\n\n const element = target ? isTarget.getElement(target) : internalRef.current;\n\n if (!element) return;\n\n const onEvent = (event: DragEvent, type: 'drop' | 'enter' | 'leave' | 'over') => {\n if (!event.dataTransfer) return;\n\n const isValid = checkValidity(event.dataTransfer.items);\n if (!isValid) {\n event.dataTransfer.dropEffect = 'none';\n return;\n }\n\n event.preventDefault();\n event.dataTransfer.dropEffect = 'copy';\n\n const currentFiles = getFiles(event);\n\n if (type === 'drop') {\n counterRef.current = 0;\n setOvered(false);\n setFiles(currentFiles);\n options.onDrop?.(currentFiles, event);\n return;\n }\n\n if (type === 'enter') {\n counterRef.current += 1;\n setOvered(true);\n options.onEnter?.(event);\n return;\n }\n\n if (type === 'leave') {\n counterRef.current -= 1;\n if (counterRef.current !== 0) return;\n setOvered(false);\n options.onLeave?.(event);\n return;\n }\n\n if (type === 'over') options.onOver?.(event);\n };\n\n const onDrop = ((event: DragEvent) => onEvent(event, 'drop')) as EventListener;\n const onDragOver = ((event: DragEvent) => onEvent(event, 'over')) as EventListener;\n const onDragEnter = ((event: DragEvent) => onEvent(event, 'enter')) as EventListener;\n const onDragLeave = ((event: DragEvent) => onEvent(event, 'leave')) as EventListener;\n\n element.addEventListener('dragenter', onDragEnter);\n element.addEventListener('dragover', onDragOver);\n element.addEventListener('dragleave', onDragLeave);\n element.addEventListener('drop', onDrop);\n\n return () => {\n element.removeEventListener('dragenter', onDragEnter);\n element.removeEventListener('dragover', onDragOver);\n element.removeEventListener('dragleave', onDragLeave);\n element.removeEventListener('drop', onDrop);\n };\n }, [target && isTarget.getRawElement(target), internalRef.state]);\n\n if (target) return { overed, files };\n return { ref: internalRef, overed, files };\n}) as UseDropZone;\n"],"names":["useDropZone","params","target","isTarget","options","internalRef","useRefState","counterRef","useRef","files","setFiles","useState","overed","setOvered","dataTypes","getFiles","event","list","checkDataTypes","types","type","dataType","checkValidity","items","item","dataTypesValid","multipleFilesValid","useEffect","element","onEvent","currentFiles","onDrop","onDragOver","onDragEnter","onDragLeave"],"mappings":"mMAwGaA,GAAe,IAAIC,IAAkB,CAChD,MAAMC,EAAUC,EAAAA,SAASF,EAAO,CAAC,CAAC,EAAIA,EAAO,CAAC,EAAI,OAE5CG,EACJF,EACI,OAAOD,EAAO,CAAC,GAAM,SACnBA,EAAO,CAAC,EACR,CAAE,OAAQA,EAAO,CAAC,CAAA,EACpB,OAAOA,EAAO,CAAC,GAAM,SACnBA,EAAO,CAAC,EACR,CAAE,OAAQA,EAAO,CAAC,CAAA,EAGpBI,EAAcC,EAAAA,YAAA,EAEdC,EAAaC,EAAAA,OAAO,CAAC,EACrB,CAACC,EAAOC,CAAQ,EAAIC,EAAAA,SAAwB,IAAI,EAChD,CAACC,EAAQC,CAAS,EAAIF,EAAAA,SAAS,EAAK,EAEpCG,EAAYV,EAAQ,UAEpBW,EAAYC,GAAqB,CACrC,GAAI,CAACA,EAAM,aAAc,OAAO,KAChC,MAAMC,EAAO,MAAM,KAAKD,EAAM,aAAa,KAAK,EAChD,OAAIZ,EAAQ,SAAiBa,EACxBA,EAAK,OACH,CAACA,EAAK,CAAC,CAAC,EADU,IACV,EAGXC,EAAkBC,GACjBL,EACD,OAAOA,GAAc,WAAmBA,EAAUK,CAAK,EACtDL,EAAU,OACVK,EAAM,OAEJA,EAAM,MAAOC,GAASN,EAAU,KAAMO,GAAaD,EAAK,SAASC,CAAQ,CAAC,CAAC,EAFxD,GADI,GAFP,GAQnBC,EAAiBC,GAAgC,CACrD,MAAMJ,EAAQ,MAAM,KAAKI,CAAK,EAAE,IAAKC,GAASA,EAAK,IAAI,EACjDC,EAAiBP,EAAeC,CAAK,EACrCO,EAAqBtB,EAAQ,UAAYmB,EAAM,QAAU,EAE/D,OAAOE,GAAkBC,CAAA,EAoE3B,OAjEAC,EAAAA,UAAU,IAAM,CACd,GAAI,CAACzB,GAAU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Q,oBAAoB,OAAQG,CAAM,CAAA,CAC5C,EACC,CAAC7B,GAAUC,WAAS,cAAcD,CAAM,EAAGG,EAAY,KAAK,CAAC,EAE5DH,EAAe,CAAE,OAAAU,EAAQ,MAAAH,CAAA,EACtB,CAAE,IAAKJ,EAAa,OAAAO,EAAQ,MAAAH,CAAA,CACrC"}
|
|
1
|
+
{"version":3,"file":"useDropZone.cjs","sources":["../../../../src/hooks/useDropZone/useDropZone.ts"],"sourcesContent":["import { useEffect, useRef, useState } from 'react';\n\nimport type { HookTarget } from '@/utils/helpers';\n\nimport { isTarget } from '@/utils/helpers';\n\nimport type { StateRef } from '../useRefState/useRefState';\n\nimport { useRefState } from '../useRefState/useRefState';\n\nexport type DropZoneDataTypes = ((types: string[]) => boolean) | string[];\n\nexport interface UseDropZoneOptions {\n /** The data types for drop zone */\n dataTypes?: DropZoneDataTypes;\n /** The multiple mode for drop zone */\n multiple?: boolean;\n /** The on drop callback */\n onDrop?: (files: File[] | null, event: DragEvent) => void;\n /** The on enter callback */\n onEnter?: (event: DragEvent) => void;\n /** The on leave callback */\n onLeave?: (event: DragEvent) => void;\n /** The on over callback */\n onOver?: (event: DragEvent) => void;\n}\n\nexport interface UseDropZoneReturn {\n /** The files that was dropped in drop zone */\n files: File[] | null;\n /** The over drop zone status */\n overed: boolean;\n}\n\nexport interface UseDropZone {\n (\n target: HookTarget,\n callback?: (files: File[] | null, event: DragEvent) => void\n ): UseDropZoneReturn;\n\n <Target extends Element>(\n callback?: (files: File[] | null, event: DragEvent) => void,\n target?: never\n ): UseDropZoneReturn & {\n ref: StateRef<Target>;\n };\n\n (target: HookTarget, options?: UseDropZoneOptions): UseDropZoneReturn;\n\n <Target extends Element>(\n options?: UseDropZoneOptions,\n target?: never\n ): UseDropZoneReturn & {\n ref: StateRef<Target>;\n };\n}\n\n/**\n * @name useDropZone\n * @description - Hook that provides drop zone functionality\n * @category Elements\n * @usage medium\n\n * @overload\n * @template Target The target element\n * @param {Target} target The target element drop zone's\n * @param {DataTypes} [options.dataTypes] The data types\n * @param {boolean} [options.multiple] The multiple mode\n * @param {(files: File[] | null, event: DragEvent) => void} [options.onDrop] The on drop callback function\n * @param {(event: DragEvent) => void} [options.onEnter] The on enter callback function\n * @param {(event: DragEvent) => void} [options.onLeave] The on leave callback function\n * @param {(event: DragEvent) => void} [options.onOver] The on over callback function\n * @returns {UseDropZoneReturn} The object with drop zone states\n *\n * @example\n * const { overed, files } = useDropZone(ref, options);\n *\n * @overload\n * @param {Target} target The target element drop zone's\n * @param {(files: File[] | null, event: DragEvent) => void} [callback] The callback function to be invoked on drop\n * @returns {UseDropZoneReturn} The object with drop zone states\n *\n * @example\n * const { overed, files } = useDropZone(ref, () => console.log('callback'));\n *\n * @overload\n * @param {DataTypes} [options.dataTypes] The data types\n * @param {boolean} [options.multiple] The multiple mode\n * @param {(files: File[] | null, event: DragEvent) => void} [options.onDrop] The on drop callback function\n * @param {(event: DragEvent) => void} [options.onEnter] The on enter callback function\n * @param {(event: DragEvent) => void} [options.onLeave] The on leave callback function\n * @param {(event: DragEvent) => void} [options.onOver] The on over callback function\n * @returns {UseDropZoneReturn & { ref: StateRef<Target> }} The object with drop zone states and ref\n *\n * @example\n * const { ref, overed, files } = useDropZone(options);\n *\n * @overload\n * @param {(files: File[] | null, event: DragEvent) => void} [callback] The callback function to be invoked on drop\n * @returns {UseDropZoneReturn & { ref: StateRef<Target> }} The object with drop zone states and ref\n *\n * @example\n * const { ref, overed, files } = useDropZone(() => console.log('callback'));\n */\nexport const useDropZone = ((...params: any[]) => {\n const target = (isTarget(params[0]) ? params[0] : undefined) as HookTarget | undefined;\n\n const options = (\n target\n ? typeof params[1] === 'object'\n ? params[1]\n : { onDrop: params[1] }\n : typeof params[0] === 'object'\n ? params[0]\n : { onDrop: params[0] }\n ) as UseDropZoneOptions;\n\n const internalRef = useRefState<Element>();\n\n const counterRef = useRef(0);\n const [files, setFiles] = useState<File[] | null>(null);\n const [overed, setOvered] = useState(false);\n\n const dataTypes = options.dataTypes;\n\n const getFiles = (event: DragEvent) => {\n if (!event.dataTransfer) return null;\n const list = Array.from(event.dataTransfer.files);\n if (options.multiple) return list;\n if (!list.length) return null;\n return [list[0]];\n };\n\n const checkDataTypes = (types: string[]) => {\n if (!dataTypes) return true;\n if (typeof dataTypes === 'function') return dataTypes(types);\n if (!dataTypes.length) return true;\n if (!types.length) return false;\n\n return types.every((type) => dataTypes.some((dataType) => type.includes(dataType)));\n };\n\n const checkValidity = (items: DataTransferItemList) => {\n const types = Array.from(items).map((item) => item.type);\n const dataTypesValid = checkDataTypes(types);\n const multipleFilesValid = options.multiple || items.length <= 1;\n\n return dataTypesValid && multipleFilesValid;\n };\n\n useEffect(() => {\n if (!target && !internalRef.state) return;\n\n const element = target ? isTarget.getElement(target) : internalRef.current;\n\n if (!element) return;\n\n const onEvent = (event: DragEvent) => {\n if (!event.dataTransfer) return;\n\n const isValid = checkValidity(event.dataTransfer.items);\n if (!isValid) {\n event.dataTransfer.dropEffect = 'none';\n return;\n }\n\n event.preventDefault();\n event.dataTransfer.dropEffect = 'copy';\n\n const currentFiles = getFiles(event);\n\n if (event.type === 'drop') {\n counterRef.current = 0;\n setOvered(false);\n setFiles(currentFiles);\n options.onDrop?.(currentFiles, event);\n return;\n }\n\n if (event.type === 'dragenter') {\n counterRef.current += 1;\n setOvered(true);\n options.onEnter?.(event);\n return;\n }\n\n if (event.type === 'dragleave') {\n counterRef.current -= 1;\n if (counterRef.current !== 0) return;\n setOvered(false);\n options.onLeave?.(event);\n return;\n }\n\n if (event.type === 'dragover') options.onOver?.(event);\n };\n\n element.addEventListener('dragenter', onEvent as EventListener);\n element.addEventListener('dragover', onEvent as EventListener);\n element.addEventListener('dragleave', onEvent as EventListener);\n element.addEventListener('drop', onEvent as EventListener);\n\n return () => {\n element.removeEventListener('dragenter', onEvent as EventListener);\n element.removeEventListener('dragover', onEvent as EventListener);\n element.removeEventListener('dragleave', onEvent as EventListener);\n element.removeEventListener('drop', onEvent as EventListener);\n };\n }, [target && isTarget.getRawElement(target), internalRef.state]);\n\n if (target) return { overed, files };\n return { ref: internalRef, overed, files };\n}) as UseDropZone;\n"],"names":["useDropZone","params","target","isTarget","options","internalRef","useRefState","counterRef","useRef","files","setFiles","useState","overed","setOvered","dataTypes","getFiles","event","list","checkDataTypes","types","type","dataType","checkValidity","items","item","dataTypesValid","multipleFilesValid","useEffect","element","onEvent","currentFiles"],"mappings":"mMAwGaA,GAAe,IAAIC,IAAkB,CAChD,MAAMC,EAAUC,EAAAA,SAASF,EAAO,CAAC,CAAC,EAAIA,EAAO,CAAC,EAAI,OAE5CG,EACJF,EACI,OAAOD,EAAO,CAAC,GAAM,SACnBA,EAAO,CAAC,EACR,CAAE,OAAQA,EAAO,CAAC,CAAA,EACpB,OAAOA,EAAO,CAAC,GAAM,SACnBA,EAAO,CAAC,EACR,CAAE,OAAQA,EAAO,CAAC,CAAA,EAGpBI,EAAcC,EAAAA,YAAA,EAEdC,EAAaC,EAAAA,OAAO,CAAC,EACrB,CAACC,EAAOC,CAAQ,EAAIC,EAAAA,SAAwB,IAAI,EAChD,CAACC,EAAQC,CAAS,EAAIF,EAAAA,SAAS,EAAK,EAEpCG,EAAYV,EAAQ,UAEpBW,EAAYC,GAAqB,CACrC,GAAI,CAACA,EAAM,aAAc,OAAO,KAChC,MAAMC,EAAO,MAAM,KAAKD,EAAM,aAAa,KAAK,EAChD,OAAIZ,EAAQ,SAAiBa,EACxBA,EAAK,OACH,CAACA,EAAK,CAAC,CAAC,EADU,IACV,EAGXC,EAAkBC,GACjBL,EACD,OAAOA,GAAc,WAAmBA,EAAUK,CAAK,EACtDL,EAAU,OACVK,EAAM,OAEJA,EAAM,MAAOC,GAASN,EAAU,KAAMO,GAAaD,EAAK,SAASC,CAAQ,CAAC,CAAC,EAFxD,GADI,GAFP,GAQnBC,EAAiBC,GAAgC,CACrD,MAAMJ,EAAQ,MAAM,KAAKI,CAAK,EAAE,IAAKC,GAASA,EAAK,IAAI,EACjDC,EAAi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AAQC,CAAwB,CAAA,CAC9D,EACC,CAAC3B,GAAUC,WAAS,cAAcD,CAAM,EAAGG,EAAY,KAAK,CAAC,EAE5DH,EAAe,CAAE,OAAAU,EAAQ,MAAAH,CAAA,EACtB,CAAE,IAAKJ,EAAa,OAAAO,EAAQ,MAAAH,CAAA,CACrC"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const f=require("react"),k=require("../useRerender/useRerender.cjs"),L=(u="",c)=>{const r=f.useRef(null),l=f.useRef(!1),i=k.useRerender(),[v,o]=f.useState(!1),[g,s]=f.useState(c?.initialTouched??!1),[y,t]=f.useState(void 0),h=()=>r.current?.type==="radio"||r.current?.type==="checkbox"?r.current.checked:r.current?.value??u,a=e=>{if(r.current?.type==="radio"||r.current?.type==="checkbox")return r.current.checked=e,l.current?i():void 0;if(r.current.value=e,l.current)return i()},x=()=>{a(u),o(!1),s(!1),t(void 0)},b=()=>r.current.focus(),d=e=>{if(e.required&&!r.current.value)return t(e.required);if(e.minLength&&r.current.value.length<e.minLength.value)return t(e.minLength.message);if(e.maxLength&&r.current.value.length>e.maxLength.value)return t(e.maxLength.message);if(e.min&&Number(r.current.value)<e.min.value)return t(e.min.message);if(e.max&&Number(r.current.value)>e.max.value)return t(e.max.message);if(e.pattern&&!e.pattern.value.test(r.current.value))return t(e.pattern.message);if(e.validate){const n=e.validate(r.current.value);if(typeof n=="string")return t(n)}t(void 0)};return{register:e=>({ref:n=>{if(!r.current&&n){if(c?.autoFocus&&n.focus(),r.current=n,r.current.type==="radio"){r.current.defaultChecked=u===n.value;return}if(r.current.type==="checkbox"){r.current.defaultChecked=!!u;return}r.current.defaultValue=String(u),e&&c?.validateOnMount&&d(e)}},onChange:async()=>{if(l.current)return i();r.current.value!==u&&o(!0),v&&r.current.value===u&&o(!1),e&&c?.validateOnChange&&await d(e),e&&c?.validateOnBlur&&t(void 0)},onBlur:async()=>{e&&c?.validateOnBlur&&await d(e),s(!0)}}),dirty:v,touched:g,error:y,setError:t,clearError:()=>t(void 0),getValue:h,setValue:a,reset:x,watch:()=>(l.current=!0,h()),focus:b,ref:r}};exports.useField=L;
|
|
2
2
|
//# sourceMappingURL=useField.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useField.cjs","sources":["../../../../src/hooks/useField/useField.ts"],"sourcesContent":["import type { RefObject } from 'react';\n\nimport { useRef, useState } from 'react';\n\nimport { useRerender } from '../useRerender/useRerender';\n\n/** The use field params type */\nexport interface
|
|
1
|
+
{"version":3,"file":"useField.cjs","sources":["../../../../src/hooks/useField/useField.ts"],"sourcesContent":["import type { RefObject } from 'react';\n\nimport { useRef, useState } from 'react';\n\nimport { useRerender } from '../useRerender/useRerender';\n\n/** The use field params type */\nexport interface UseFieldOptions {\n /** The auto focus */\n autoFocus?: boolean;\n /** The initial touched */\n initialTouched?: boolean;\n /** The validate on blur */\n validateOnBlur?: boolean;\n /** The validate on mount */\n validateOnChange?: boolean;\n /** The validate on mount */\n validateOnMount?: boolean;\n}\n\n/** The use field register params type */\nexport interface UseFieldRegisterParams {\n /** The min value validation */\n max?: {\n value: number;\n message: string;\n };\n /** The max length validation */\n maxLength?: {\n value: number;\n message: string;\n };\n /** The max value validation */\n min?: {\n value: number;\n message: string;\n };\n /** The min length validation */\n minLength?: {\n value: number;\n message: string;\n };\n /** The pattern validation */\n pattern?: {\n value: RegExp;\n message: string;\n };\n /** The required validation */\n required?: string;\n /** The custom validation */\n validate?: (value: string) => Promise<string | true>;\n}\n\n/** The use field return type */\nexport interface UseFieldReturn<Value> {\n /** The dirty state */\n dirty: boolean;\n /** The error state */\n error?: string;\n /** The input ref */\n ref: RefObject<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement | null>;\n /** The set error function */\n touched: boolean;\n /** The set error function */\n clearError: () => void;\n /** The focus function */\n focus: () => void;\n /** The get value function */\n getValue: () => Value;\n /** The register function */\n register: (params?: UseFieldRegisterParams) => {\n onBlur: () => void;\n onChange: () => void;\n ref: (\n node: HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement | null | undefined\n ) => void;\n };\n /** The reset function */\n reset: () => void;\n /** The set error function */\n setError: (error: string) => void;\n /** The set value function */\n setValue: (value: Value) => void;\n /** The watch function */\n watch: () => Value;\n}\n\n/**\n * @name useField\n * @description - Hook to manage a form field\n * @category State\n * @usage medium\n *\n * @template Value The input value\n * @template Type The input value type\n * @param {Value} [params.initialValue = \"\"] Initial value\n * @param {boolean} [params.initialTouched=false] Initial touched state\n * @param {boolean} [params.autoFocus=false] Auto focus\n * @param {boolean} [params.validateOnChange=false] Validate on change\n * @param {boolean} [params.validateOnBlur=false] Validate on blur\n * @param {boolean} [params.validateOnMount=false] Validate on mount\n * @returns {UseFieldReturn<Value>} An object containing input information\n *\n * @example\n * const { register, getValue, setValue, reset, dirty, error, setError, clearError, touched, focus, watch } = useField();\n */\nexport const useField = <\n Value extends boolean | number | string = string,\n Type = Value extends string ? string : Value extends boolean ? boolean : number\n>(\n initialValue: Value = '' as Value,\n options?: UseFieldOptions\n): UseFieldReturn<Type> => {\n const inputRef = useRef<HTMLInputElement | null>(null);\n const watchingRef = useRef(false);\n const rerender = useRerender();\n\n const [dirty, setDirty] = useState(false);\n const [touched, setTouched] = useState(options?.initialTouched ?? false);\n const [error, setError] = useState<string | undefined>(undefined);\n\n const getValue = () => {\n if (inputRef.current?.type === 'radio' || inputRef.current?.type === 'checkbox')\n return inputRef.current.checked as Type;\n return (inputRef.current?.value ?? initialValue) as Type;\n };\n\n const setValue = (value: Type) => {\n if (inputRef.current?.type === 'radio' || inputRef.current?.type === 'checkbox') {\n inputRef.current.checked = value as boolean;\n if (watchingRef.current) return rerender();\n return;\n }\n\n inputRef.current!.value = value as string;\n if (watchingRef.current) return rerender();\n };\n\n const reset = () => {\n setValue(initialValue as unknown as Type);\n setDirty(false);\n setTouched(false);\n setError(undefined);\n };\n\n const focus = () => inputRef.current!.focus();\n\n const validate = (params: UseFieldRegisterParams) => {\n if (params.required && !inputRef.current!.value) {\n return setError(params.required);\n }\n\n if (params.minLength && inputRef.current!.value.length < params.minLength.value) {\n return setError(params.minLength.message);\n }\n\n if (params.maxLength && inputRef.current!.value.length > params.maxLength.value) {\n return setError(params.maxLength.message);\n }\n\n if (params.min && Number(inputRef.current!.value) < params.min.value) {\n return setError(params.min.message);\n }\n\n if (params.max && Number(inputRef.current!.value) > params.max.value) {\n return setError(params.max.message);\n }\n\n if (params.pattern && !params.pattern.value.test(inputRef.current!.value)) {\n return setError(params.pattern.message);\n }\n\n if (params.validate) {\n const error = params.validate(inputRef.current!.value);\n if (typeof error === 'string') return setError(error);\n }\n\n setError(undefined);\n };\n\n const register = (registerParams?: UseFieldRegisterParams) => ({\n ref: (node: HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement | null | undefined) => {\n if (!inputRef.current && node) {\n if (options?.autoFocus) node.focus();\n inputRef.current = node as HTMLInputElement;\n if (inputRef.current.type === 'radio') {\n inputRef.current.defaultChecked = initialValue === node.value;\n return;\n }\n if (inputRef.current.type === 'checkbox') {\n inputRef.current.defaultChecked = !!initialValue;\n return;\n }\n inputRef.current.defaultValue = String(initialValue);\n\n if (registerParams && options?.validateOnMount) validate(registerParams);\n }\n },\n onChange: async () => {\n if (watchingRef.current) return rerender();\n if (inputRef.current!.value !== initialValue) setDirty(true);\n if (dirty && inputRef.current!.value === initialValue) setDirty(false);\n if (registerParams && options?.validateOnChange) await validate(registerParams);\n if (registerParams && options?.validateOnBlur) setError(undefined);\n },\n onBlur: async () => {\n if (registerParams && options?.validateOnBlur) await validate(registerParams);\n setTouched(true);\n }\n });\n\n const watch = () => {\n watchingRef.current = true;\n return getValue();\n };\n\n const clearError = () => setError(undefined);\n\n return {\n register,\n dirty,\n touched,\n error,\n setError,\n clearError,\n getValue,\n setValue,\n reset,\n watch,\n focus,\n ref: inputRef\n };\n};\n"],"names":["useField","initialValue","options","inputRef","useRef","watchingRef","rerender","useRerender","dirty","setDirty","useState","touched","setTouched","error","setError","getValue","setValue","value","reset","focus","validate","params","registerParams","node"],"mappings":"qJA0GaA,EAAW,CAItBC,EAAsB,GACtBC,IACyB,CACzB,MAAMC,EAAWC,EAAAA,OAAgC,IAAI,EAC/CC,EAAcD,EAAAA,OAAO,EAAK,EAC1BE,EAAWC,EAAAA,YAAA,EAEX,CAACC,EAAOC,CAAQ,EAAIC,EAAAA,SAAS,EAAK,EAClC,CAACC,EAASC,CAAU,EAAIF,EAAAA,SAASR,GAAS,gBAAkB,EAAK,EACjE,CAACW,EAAOC,CAAQ,EAAIJ,EAAAA,SAA6B,MAAS,EAE1DK,EAAW,IACXZ,EAAS,SAAS,OAAS,SAAWA,EAAS,SAAS,OAAS,WAC5DA,EAAS,QAAQ,QAClBA,EAAS,SAAS,OAASF,EAG/Be,EAAYC,GAAgB,CAChC,GAAId,EAAS,SAAS,OAAS,SAAWA,EAAS,SAAS,OAAS,WAEnE,OADAA,EAAS,QAAQ,QAAUc,EACvBZ,EAAY,QAAgBC,EAAA,EAChC,OAIF,GADAH,EAAS,QAAS,MAAQc,EACtBZ,EAAY,QAAS,OAAOC,EAAA,CAAS,EAGrCY,EAAQ,IAAM,CAClBF,EAASf,CAA+B,EACxCQ,EAAS,EAAK,EACdG,EAAW,EAAK,EAChBE,EAAS,MAAS,CAAA,EAGdK,EAAQ,IAAMhB,EAAS,QAAS,MAAA,EAEhCiB,EAAYC,GAAmC,CACnD,GAAIA,EAAO,UAAY,CAAClB,EAAS,QAAS,MACxC,OAAOW,EAASO,EAAO,QAAQ,EAGjC,GAAIA,EAAO,WAAalB,EAAS,QAAS,MAAM,OAASkB,EAAO,UAAU,MACxE,OAAOP,EAASO,EAAO,UAAU,OAAO,EAG1C,GAAIA,EAAO,WAAalB,EAAS,QAAS,MAAM,OAASkB,EAAO,UAAU,MACxE,OAAOP,EAASO,EAAO,UAAU,OAAO,EAG1C,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S,gBAAgB,MAAMkB,EAASE,CAAc,EAC5EV,EAAW,EAAI,CAAA,CACjB,GAYA,MAAAJ,EACA,QAAAG,EACA,MAAAE,EACA,SAAAC,EACA,WARiB,IAAMA,EAAS,MAAS,EASzC,SAAAC,EACA,SAAAC,EACA,MAAAE,EACA,MAjBY,KACZb,EAAY,QAAU,GACfU,EAAA,GAgBP,MAAAI,EACA,IAAKhB,CAAA,CAET"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useHotkeys.cjs","sources":["../../../../src/hooks/useHotkeys/useHotkeys.ts"],"sourcesContent":["import { useEffect, useRef } from 'react';\n\nimport type { HookTarget } from '@/utils/helpers';\n\nimport { isTarget } from '@/utils/helpers';\n\nimport type { StateRef } from '../useRefState/useRefState';\n\nimport { useEvent } from '../useEvent/useEvent';\nimport { useRefState } from '../useRefState/useRefState';\n\n/** The use hotkeys params type */\nexport interface UseHotkeysOptions {\n /** Alias map for hotkeys */\n alias?: Record<string, string>;\n /** Enable or disable the event listeners */\n enabled?: boolean;\n}\n\nexport const isHotkeyMatch = (hotkey: string, keys: UseHotkeysKey[]) =>\n hotkey\n .toLowerCase()\n .split(/[+_,\\-]/g)\n .map((key) => key.trim())\n .every((key) =>\n keys.find(\n (updatedKey) =>\n key === updatedKey.code.toLocaleLowerCase() ||\n key === updatedKey.key.toLocaleLowerCase() ||\n key === updatedKey.alias.toLocaleLowerCase()\n )\n );\n\n/** The hotkeys string type */\nexport type UseHotkeysHotkeys = string;\n\n/** The hotkey key information */\nexport interface UseHotkeysKey {\n /** The alias for the key */\n alias: string;\n /** The key code */\n code: string;\n /** The key value */\n key: string;\n}\n\n/** The use hotkeys target type */\nexport type UseHotkeysTarget = Element | React.RefObject<Element | null | undefined>;\n\nexport interface UseHotkeys {\n (\n target: UseHotkeysTarget,\n hotkeys: UseHotkeysHotkeys,\n callback: (event: KeyboardEvent) => void,\n options?: UseHotkeysOptions\n ): void;\n\n <Target extends Element>(\n hotkeys: UseHotkeysHotkeys,\n callback: (event: KeyboardEvent) => void,\n options?: UseHotkeysOptions,\n target?: never\n ): StateRef<Target>;\n}\n\n/**\n * @name useHotkeys\n * @description - Hook that listens for hotkeys\n * @category Sensors\n * @usage medium\n *\n * @overload\n * @param {HookTarget} [target=window] The target element to attach the event listener to\n * @param {string} hotkeys The hotkey to listen for\n * @param {(event: KeyboardEvent) => void} callback The callback function to execute when hotkey is pressed\n * @param {Record<string, string>} [options.alias] Alias map for hotkeys\n * @param {boolean} [options.enabled=true] Enable or disable the event listeners\n * @returns {void}\n *\n * @example\n * useHotkeys(ref, 'ctrl+a', () => console.log('hotkey pressed'));\n * @example\n * useHotkeys(ref, 'ctrl+a, ctrl+b', () => console.log('hotkey pressed'));\n *\n * @overload\n * @template Target The target element\n * @param {string} hotkeys The hotkey to listen for\n * @param {(event: KeyboardEvent) => void} callback The callback function to execute when hotkey is pressed\n * @param {Record<string, string>} [options.alias] Alias map for hotkeys\n * @param {boolean} [options.enabled=true] Enable or disable the event listeners\n * @returns {StateRef<Target>} A reference to the target element\n *\n * @example\n * const ref = useHotkeys('ctrl+a', () => console.log('hotkey pressed'));\n * @example\n * const ref = useHotkeys('ctrl+a, ctrl+b', () => console.log('hotkey pressed'));\n */\nexport const useHotkeys = ((...params: any[]) => {\n const target = (isTarget(params[0]) ? params[0] : undefined) as HookTarget | undefined;\n const hotkeys = (target ? params[1] : params[0]) as UseHotkeysHotkeys;\n const callback = (target ? params[2] : params[1]) as (event: KeyboardEvent) => void;\n const options = (target ? params[3] : params[2]) as UseHotkeysOptions | undefined;\n\n const internalRef = useRefState(window);\n const keysRef = useRef<UseHotkeysKey[]>([]);\n const enabled = options?.enabled ?? true;\n\n const onKeyDown = useEvent((event: KeyboardEvent) => {\n if (!enabled) return;\n\n if (keysRef.current.some(({ code }) => code === event.code)) return;\n\n const alias = options?.alias?.[event.key] ?? event.code;\n const updatedKeys = [...keysRef.current, { key: event.key, code: event.code, alias }];\n keysRef.current = updatedKeys;\n\n const hotkeysList = hotkeys.split(',').map((h) => h.trim());\n const isMatch = hotkeysList.some((hotkey) => isHotkeyMatch(hotkey, updatedKeys));\n if (!isMatch) return;\n event.preventDefault();\n callback(event);\n });\n\n const onKeyUp = useEvent((event: KeyboardEvent) => {\n if (!enabled) return;\n keysRef.current = keysRef.current.filter(({ code }) => code !== event.code);\n });\n\n useEffect(() => {\n keysRef.current = [];\n if (!target && !internalRef.state && !enabled) return;\n\n const element = (target ? isTarget.getElement(target) : internalRef.current) as Element;\n if (!element) return;\n\n element.addEventListener('keydown', onKeyDown as EventListener);\n element.addEventListener('keyup', onKeyUp as EventListener);\n\n return () => {\n element.removeEventListener('keydown', onKeyDown as EventListener);\n element.removeEventListener('keyup', onKeyUp as EventListener);\n };\n }, [\n target && isTarget.getRawElement(target),\n internalRef.state,\n enabled,\n hotkeys,\n onKeyDown,\n onKeyUp\n ]);\n\n if (target) return;\n return internalRef;\n}) as UseHotkeys;\n"],"names":["isHotkeyMatch","hotkey","keys","key","updatedKey","useHotkeys","params","target","isTarget","hotkeys","callback","options","internalRef","useRefState","keysRef","useRef","enabled","onKeyDown","useEvent","event","code","alias","updatedKeys","h","onKeyUp","useEffect","element"],"mappings":"yOAmBaA,EAAgB,CAACC,EAAgBC,IAC5CD,EACG,cACA,MAAM,UAAU,EAChB,IAAKE,GAAQA,EAAI,KAAA,CAAM,EACvB,MAAOA,GACND,EAAK,KACFE,GACCD,IAAQC,EAAW,KAAK,kBAAA,GACxBD,IAAQC,EAAW,IAAI,kBAAA,GACvBD,IAAQC,EAAW,MAAM,kBAAA,CAAkB,CAEjD,EAkESC,GAAc,IAAIC,IAAkB,CAC/C,MAAMC,EAAUC,EAAAA,SAASF,EAAO,CAAC,CAAC,EAAIA,EAAO,CAAC,EAAI,OAC5CG,EAAWF,EAASD,EAAO,CAAC,EAAIA,EAAO,CAAC,EACxCI,EAAYH,EAASD,EAAO,CAAC,EAAIA,EAAO,CAAC,EACzCK,EAAWJ,EAASD,EAAO,CAAC,EA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"version":3,"file":"useHotkeys.cjs","sources":["../../../../src/hooks/useHotkeys/useHotkeys.ts"],"sourcesContent":["import { useEffect, useRef } from 'react';\r\n\r\nimport type { HookTarget } from '@/utils/helpers';\r\n\r\nimport { isTarget } from '@/utils/helpers';\r\n\r\nimport type { StateRef } from '../useRefState/useRefState';\r\n\r\nimport { useEvent } from '../useEvent/useEvent';\r\nimport { useRefState } from '../useRefState/useRefState';\r\n\r\n/** The use hotkeys params type */\r\nexport interface UseHotkeysOptions {\r\n /** Alias map for hotkeys */\r\n alias?: Record<string, string>;\r\n /** Enable or disable the event listeners */\r\n enabled?: boolean;\r\n}\r\n\r\nexport const isHotkeyMatch = (hotkey: string, keys: UseHotkeysKey[]) =>\r\n hotkey\r\n .toLowerCase()\r\n .split(/[+_,\\-]/g)\r\n .map((key) => key.trim())\r\n .every((key) =>\r\n keys.find(\r\n (updatedKey) =>\r\n key === updatedKey.code.toLocaleLowerCase() ||\r\n key === updatedKey.key.toLocaleLowerCase() ||\r\n key === updatedKey.alias.toLocaleLowerCase()\r\n )\r\n );\r\n\r\n/** The hotkeys string type */\r\nexport type UseHotkeysHotkeys = string;\r\n\r\n/** The hotkey key information */\r\nexport interface UseHotkeysKey {\r\n /** The alias for the key */\r\n alias: string;\r\n /** The key code */\r\n code: string;\r\n /** The key value */\r\n key: string;\r\n}\r\n\r\n/** The use hotkeys target type */\r\nexport type UseHotkeysTarget = Element | React.RefObject<Element | null | undefined>;\r\n\r\nexport interface UseHotkeys {\r\n (\r\n target: UseHotkeysTarget,\r\n hotkeys: UseHotkeysHotkeys,\r\n callback: (event: KeyboardEvent) => void,\r\n options?: UseHotkeysOptions\r\n ): void;\r\n\r\n <Target extends Element>(\r\n hotkeys: UseHotkeysHotkeys,\r\n callback: (event: KeyboardEvent) => void,\r\n options?: UseHotkeysOptions,\r\n target?: never\r\n ): StateRef<Target>;\r\n}\r\n\r\n/**\r\n * @name useHotkeys\r\n * @description - Hook that listens for hotkeys\r\n * @category Sensors\r\n * @usage medium\r\n *\r\n * @overload\r\n * @param {HookTarget} [target=window] The target element to attach the event listener to\r\n * @param {string} hotkeys The hotkey to listen for\r\n * @param {(event: KeyboardEvent) => void} callback The callback function to execute when hotkey is pressed\r\n * @param {Record<string, string>} [options.alias] Alias map for hotkeys\r\n * @param {boolean} [options.enabled=true] Enable or disable the event listeners\r\n * @returns {void}\r\n *\r\n * @example\r\n * useHotkeys(ref, 'ctrl+a', () => console.log('hotkey pressed'));\r\n * @example\r\n * useHotkeys(ref, 'ctrl+a, ctrl+b', () => console.log('hotkey pressed'));\r\n *\r\n * @overload\r\n * @template Target The target element\r\n * @param {string} hotkeys The hotkey to listen for\r\n * @param {(event: KeyboardEvent) => void} callback The callback function to execute when hotkey is pressed\r\n * @param {Record<string, string>} [options.alias] Alias map for hotkeys\r\n * @param {boolean} [options.enabled=true] Enable or disable the event listeners\r\n * @returns {StateRef<Target>} A reference to the target element\r\n *\r\n * @example\r\n * const ref = useHotkeys('ctrl+a', () => console.log('hotkey pressed'));\r\n * @example\r\n * const ref = useHotkeys('ctrl+a, ctrl+b', () => console.log('hotkey pressed'));\r\n */\r\nexport const useHotkeys = ((...params: any[]) => {\r\n const target = (isTarget(params[0]) ? params[0] : undefined) as HookTarget | undefined;\r\n const hotkeys = (target ? params[1] : params[0]) as UseHotkeysHotkeys;\r\n const callback = (target ? params[2] : params[1]) as (event: KeyboardEvent) => void;\r\n const options = (target ? params[3] : params[2]) as UseHotkeysOptions | undefined;\r\n\r\n const internalRef = useRefState(window);\r\n const keysRef = useRef<UseHotkeysKey[]>([]);\r\n const enabled = options?.enabled ?? true;\r\n\r\n const onKeyDown = useEvent((event: KeyboardEvent) => {\r\n if (!enabled) return;\r\n\r\n if (keysRef.current.some(({ code }) => code === event.code)) return;\r\n\r\n const alias = options?.alias?.[event.key] ?? event.code;\r\n const updatedKeys = [...keysRef.current, { key: event.key, code: event.code, alias }];\r\n keysRef.current = updatedKeys;\r\n\r\n const hotkeysList = hotkeys.split(',').map((h) => h.trim());\r\n const isMatch = hotkeysList.some((hotkey) => isHotkeyMatch(hotkey, updatedKeys));\r\n if (!isMatch) return;\r\n event.preventDefault();\r\n callback(event);\r\n });\r\n\r\n const onKeyUp = useEvent((event: KeyboardEvent) => {\r\n if (!enabled) return;\r\n keysRef.current = keysRef.current.filter(({ code }) => code !== event.code);\r\n });\r\n\r\n useEffect(() => {\r\n keysRef.current = [];\r\n if (!target && !internalRef.state && !enabled) return;\r\n\r\n const element = (target ? isTarget.getElement(target) : internalRef.current) as Element;\r\n if (!element) return;\r\n\r\n element.addEventListener('keydown', onKeyDown as EventListener);\r\n element.addEventListener('keyup', onKeyUp as EventListener);\r\n\r\n return () => {\r\n element.removeEventListener('keydown', onKeyDown as EventListener);\r\n element.removeEventListener('keyup', onKeyUp as EventListener);\r\n };\r\n }, [\r\n target && isTarget.getRawElement(target),\r\n internalRef.state,\r\n enabled,\r\n hotkeys,\r\n onKeyDown,\r\n onKeyUp\r\n ]);\r\n\r\n if (target) return;\r\n return internalRef;\r\n}) as UseHotkeys;\r\n"],"names":["isHotkeyMatch","hotkey","keys","key","updatedKey","useHotkeys","params","target","isTarget","hotkeys","callback","options","internalRef","useRefState","keysRef","useRef","enabled","onKeyDown","useEvent","event","code","alias","updatedKeys","h","onKeyUp","useEffect","element"],"mappings":"yOAmBaA,EAAgB,CAACC,EAAgBC,IAC5CD,EACG,cACA,MAAM,UAAU,EAChB,IAAKE,GAAQA,EAAI,KAAA,CAAM,EACvB,MAAOA,GACND,EAAK,KACFE,GACCD,IAAQC,EAAW,KAAK,kBAAA,GACxBD,IAAQC,EAAW,IAAI,kBAAA,GACvBD,IAAQC,EAAW,MAAM,kBAAA,CAAkB,CAEjD,EAkESC,GAAc,IAAIC,IAAkB,CAC/C,MAAMC,EAAUC,EAAAA,SAASF,EAAO,CAAC,CAAC,EAAIA,EAAO,CAAC,EAAI,OAC5CG,EAAWF,EAASD,EAAO,CAAC,EAAIA,EAAO,CAAC,EACxCI,EAAYH,EA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ACAQ,EACAO,CAAA,CACD,EAEG,CAAAjB,EACJ,OAAOK,CACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useImage.cjs","sources":["../../../../src/hooks/useImage/useImage.ts"],"sourcesContent":["import type { UseQueryOptions, UseQueryReturn } from '../useQuery/useQuery';\n\nimport { useQuery } from '../useQuery/useQuery';\n\n/** The use image options */\nexport interface UseImageOptions {\n /** The alt of the image */\n alt?: string;\n /** The class of the image */\n class?: string;\n /** The crossorigin of the image */\n crossorigin?: string;\n /** The loading of the image */\n loading?: HTMLImageElement['loading'];\n /** The referrer policy of the image */\n referrerPolicy?: HTMLImageElement['referrerPolicy'];\n /** The sizes of the image */\n sizes?: string;\n /** The srcset of the image */\n srcset?: string;\n}\n\n/** The use image return type */\nexport type UseImageReturn = UseQueryReturn<HTMLImageElement>;\n\nconst loadImage = async (src: string, options: UseImageOptions = {}): Promise<HTMLImageElement> =>\n new Promise((resolve, reject) => {\n const img = new Image();\n const { srcset, sizes, class: className, loading, crossorigin, referrerPolicy } = options;\n\n img.src = src;\n if (srcset) img.srcset = srcset;\n if (sizes) img.sizes = sizes;\n if (className) img.className = className;\n if (loading) img.loading = loading;\n if (crossorigin) img.crossOrigin = crossorigin;\n\n if (referrerPolicy) img.referrerPolicy = referrerPolicy;\n\n img.onload = () => resolve(img);\n img.onerror = reject;\n });\n\n/**\n * @name useImage\n * @description - Hook that load an image in the browser\n * @category Elements\n * @usage low\n *\n * @param {string} src The source of the image\n * @param {string} [options.srcset] The srcset of the image\n * @param {string} [options.sizes] The sizes of the image\n * @param {string} [options.alt] The alt of the image\n * @param {string} [options.class] The class of the image\n * @param {HTMLImageElement['loading']} [options.loading] The loading of the image\n * @param {string} [options.crossorigin] The crossorigin of the image\n * @param {HTMLImageElement['referrerPolicy']} [options.referrerPolicy] The referrerPolicy of the image\n * @param {DependencyList} [options.keys] The dependencies for the hook\n * @param {(data: Data) => void} [options.onSuccess] The callback function to be invoked on success\n * @param {(error: Error) => void} [options.onError] The callback function to be invoked on error\n * @param {number} [options.refetchInterval] The refetch interval\n * @param {boolean | number} [options.retry] The retry count of requests\n * @returns {UseImageReturn} An object with the state of the image\n *\n * @example\n * const { data, isLoading, isError, isSuccess, error, refetch, isRefetching } = useImage('https://example.com/image.png');\n */\nexport const useImage = (\n src: string,\n options?: UseImageOptions &\n Omit<\n UseQueryOptions<HTMLImageElement, HTMLImageElement>,\n 'initialData' | 'placeholderData' | 'select'\n >\n) =>\n useQuery(\n () =>\n loadImage(src, {\n alt: options?.alt,\n class: options?.class,\n crossorigin: options?.crossorigin,\n loading: options?.loading,\n referrerPolicy: options?.referrerPolicy,\n sizes: options?.sizes,\n srcset: options?.srcset\n }),\n {\n keys: [src, ...(options?.keys ?? [])],\n onSuccess: options?.onSuccess,\n onError: options?.onError,\n refetchInterval: options?.refetchInterval,\n retry: options?.retry\n }\n );\n"],"names":["loadImage","src","options","resolve","reject","img","srcset","sizes","className","loading","crossorigin","referrerPolicy","useImage","useQuery"],"mappings":"4HAyBMA,EAAY,MAAOC,EAAaC,EAA2B,CAAA,IAC/D,IAAI,QAAQ,CAACC,EAASC,IAAW,CAC/B,MAAMC,EAAM,IAAI,MACV,CAAE,OAAAC,EAAQ,MAAAC,EAAO,MAAOC,EAAW,QAAAC,EAAS,YAAAC,EAAa,eAAAC,GAAmBT,EAElFG,EAAI,IAAMJ,EACNK,MAAY,OAASA,GACrBC,MAAW,MAAQA,GACnBC,MAAe,UAAYA,GAC3BC,MAAa,QAAUA,GACvBC,MAAiB,YAAcA,GAE/BC,MAAoB,eAAiBA,GAEzCN,EAAI,OAAS,IAAMF,EAAQE,CAAG,EAC9BA,EAAI,QAAUD,CAChB,CAAC,EA0BUQ,EAAW,CACtBX,EACAC,IAMAW,EAAAA,SACE,IACEb,EAAUC,EAAK,CACb,IAAKC,GAAS,IACd,MAAOA,GAAS,MAChB,YAAaA,GAAS,YACtB,QAASA,GAAS,QAClB,eAAgBA,GAAS,eACzB,MAAOA,GAAS,MAChB,OAAQA,GAAS,MAAA,CAClB,EACH,CACE,KAAM,CAACD,EAAK,GAAIC,GAAS,MAAQ,CAAA,CAAG,EACpC,UAAWA,GAAS,UACpB,QAASA,GAAS,QAClB,gBAAiBA,GAAS,gBAC1B,MAAOA,GAAS,KAAA,CAEpB"}
|
|
1
|
+
{"version":3,"file":"useImage.cjs","sources":["../../../../src/hooks/useImage/useImage.ts"],"sourcesContent":["import type { UseQueryOptions, UseQueryReturn } from '../useQuery/useQuery';\r\n\r\nimport { useQuery } from '../useQuery/useQuery';\r\n\r\n/** The use image options */\r\nexport interface UseImageOptions {\r\n /** The alt of the image */\r\n alt?: string;\r\n /** The class of the image */\r\n class?: string;\r\n /** The crossorigin of the image */\r\n crossorigin?: string;\r\n /** The loading of the image */\r\n loading?: HTMLImageElement['loading'];\r\n /** The referrer policy of the image */\r\n referrerPolicy?: HTMLImageElement['referrerPolicy'];\r\n /** The sizes of the image */\r\n sizes?: string;\r\n /** The srcset of the image */\r\n srcset?: string;\r\n}\r\n\r\n/** The use image return type */\r\nexport type UseImageReturn = UseQueryReturn<HTMLImageElement>;\r\n\r\nconst loadImage = async (src: string, options: UseImageOptions = {}): Promise<HTMLImageElement> =>\r\n new Promise((resolve, reject) => {\r\n const img = new Image();\r\n const { srcset, sizes, class: className, loading, crossorigin, referrerPolicy } = options;\r\n\r\n img.src = src;\r\n if (srcset) img.srcset = srcset;\r\n if (sizes) img.sizes = sizes;\r\n if (className) img.className = className;\r\n if (loading) img.loading = loading;\r\n if (crossorigin) img.crossOrigin = crossorigin;\r\n\r\n if (referrerPolicy) img.referrerPolicy = referrerPolicy;\r\n\r\n img.onload = () => resolve(img);\r\n img.onerror = reject;\r\n });\r\n\r\n/**\r\n * @name useImage\r\n * @description - Hook that load an image in the browser\r\n * @category Elements\r\n * @usage low\r\n *\r\n * @param {string} src The source of the image\r\n * @param {string} [options.srcset] The srcset of the image\r\n * @param {string} [options.sizes] The sizes of the image\r\n * @param {string} [options.alt] The alt of the image\r\n * @param {string} [options.class] The class of the image\r\n * @param {HTMLImageElement['loading']} [options.loading] The loading of the image\r\n * @param {string} [options.crossorigin] The crossorigin of the image\r\n * @param {HTMLImageElement['referrerPolicy']} [options.referrerPolicy] The referrerPolicy of the image\r\n * @param {DependencyList} [options.keys] The dependencies for the hook\r\n * @param {(data: Data) => void} [options.onSuccess] The callback function to be invoked on success\r\n * @param {(error: Error) => void} [options.onError] The callback function to be invoked on error\r\n * @param {number} [options.refetchInterval] The refetch interval\r\n * @param {boolean | number} [options.retry] The retry count of requests\r\n * @returns {UseImageReturn} An object with the state of the image\r\n *\r\n * @example\r\n * const { data, isLoading, isError, isSuccess, error, refetch, isRefetching } = useImage('https://example.com/image.png');\r\n */\r\nexport const useImage = (\r\n src: string,\r\n options?: UseImageOptions &\r\n Omit<\r\n UseQueryOptions<HTMLImageElement, HTMLImageElement>,\r\n 'initialData' | 'placeholderData' | 'select'\r\n >\r\n) =>\r\n useQuery(\r\n () =>\r\n loadImage(src, {\r\n alt: options?.alt,\r\n class: options?.class,\r\n crossorigin: options?.crossorigin,\r\n loading: options?.loading,\r\n referrerPolicy: options?.referrerPolicy,\r\n sizes: options?.sizes,\r\n srcset: options?.srcset\r\n }),\r\n {\r\n keys: [src, ...(options?.keys ?? [])],\r\n onSuccess: options?.onSuccess,\r\n onError: options?.onError,\r\n refetchInterval: options?.refetchInterval,\r\n retry: options?.retry\r\n }\r\n );\r\n"],"names":["loadImage","src","options","resolve","reject","img","srcset","sizes","className","loading","crossorigin","referrerPolicy","useImage","useQuery"],"mappings":"4HAyBMA,EAAY,MAAOC,EAAaC,EAA2B,CAAA,IAC/D,IAAI,QAAQ,CAACC,EAASC,IAAW,CAC/B,MAAMC,EAAM,IAAI,MACV,CAAE,OAAAC,EAAQ,MAAAC,EAAO,MAAOC,EAAW,QAAAC,EAAS,YAAAC,EAAa,eAAAC,GAAmBT,EAElFG,EAAI,IAAMJ,EACNK,MAAY,OAASA,GACrBC,MAAW,MAAQA,GACnBC,MAAe,UAAYA,GAC3BC,MAAa,QAAUA,GACvBC,MAAiB,YAAcA,GAE/BC,MAAoB,eAAiBA,GAEzCN,EAAI,OAAS,IAAMF,EAAQE,CAAG,EAC9BA,EAAI,QAAUD,CAChB,CAAC,EA0BUQ,EAAW,CACtBX,EACAC,IAMAW,EAAAA,SACE,IACEb,EAAUC,EAAK,CACb,IAAKC,GAAS,IACd,MAAOA,GAAS,MAChB,YAAaA,GAAS,YACtB,QAASA,GAAS,QAClB,eAAgBA,GAAS,eACzB,MAAOA,GAAS,MAChB,OAAQA,GAAS,MAAA,CAClB,EACH,CACE,KAAM,CAACD,EAAK,GAAIC,GAAS,MAAQ,CAAA,CAAG,EACpC,UAAWA,GAAS,UACpB,QAASA,GAAS,QAClB,gBAAiBA,GAAS,gBAC1B,MAAOA,GAAS,KAAA,CAEpB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useMediaQuery.cjs","sources":["../../../../src/hooks/useMediaQuery/useMediaQuery.ts"],"sourcesContent":["import { useCallback, useSyncExternalStore } from 'react';\n\nconst getServerSnapshot = () => false;\n\n/**\n * @name useMediaQuery\n * @description - Hook that manages a media query\n * @category Browser\n * @usage medium\n *\n * @browserapi window.matchMedia https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia\n *\n * @param {string} query The media query string\n * @returns {boolean} A boolean indicating if the media query matches\n *\n * @example\n * const matches = useMediaQuery('(max-width: 768px)');\n */\nexport const useMediaQuery = (query: string) => {\n const subscribe = useCallback(\n (callback: () => void) => {\n const matchMedia = window.matchMedia(query);\n\n matchMedia.addEventListener('change', callback);\n return () => {\n matchMedia.removeEventListener('change', callback);\n };\n },\n [query]\n );\n\n const getSnapshot = () => window.matchMedia(query).matches;\n\n return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);\n};\n"],"names":["getServerSnapshot","useMediaQuery","query","subscribe","useCallback","callback","matchMedia","getSnapshot","useSyncExternalStore"],"mappings":"yGAEMA,EAAoB,IAAM,GAgBnBC,EAAiBC,GAAkB,CAC9C,MAAMC,EAAYC,EAAAA,YACfC,GAAyB,CACxB,MAAMC,EAAa,OAAO,WAAWJ,CAAK,EAE1C,OAAAI,EAAW,iBAAiB,SAAUD,CAAQ,EACvC,IAAM,CACXC,EAAW,oBAAoB,SAAUD,CAAQ,CAAA,CACnD,EAEF,CAACH,CAAK,CAAA,EAGFK,EAAc,IAAM,OAAO,WAAWL,CAAK,EAAE,QAEnD,OAAOM,uBAAqBL,EAAWI,EAAaP,CAAiB,CACvE"}
|
|
1
|
+
{"version":3,"file":"useMediaQuery.cjs","sources":["../../../../src/hooks/useMediaQuery/useMediaQuery.ts"],"sourcesContent":["import { useCallback, useSyncExternalStore } from 'react';\r\n\r\nconst getServerSnapshot = () => false;\r\n\r\n/**\r\n * @name useMediaQuery\r\n * @description - Hook that manages a media query\r\n * @category Browser\r\n * @usage medium\r\n *\r\n * @browserapi window.matchMedia https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia\r\n *\r\n * @param {string} query The media query string\r\n * @returns {boolean} A boolean indicating if the media query matches\r\n *\r\n * @example\r\n * const matches = useMediaQuery('(max-width: 768px)');\r\n */\r\nexport const useMediaQuery = (query: string) => {\r\n const subscribe = useCallback(\r\n (callback: () => void) => {\r\n const matchMedia = window.matchMedia(query);\r\n\r\n matchMedia.addEventListener('change', callback);\r\n return () => {\r\n matchMedia.removeEventListener('change', callback);\r\n };\r\n },\r\n [query]\r\n );\r\n\r\n const getSnapshot = () => window.matchMedia(query).matches;\r\n\r\n return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);\r\n};\r\n"],"names":["getServerSnapshot","useMediaQuery","query","subscribe","useCallback","callback","matchMedia","getSnapshot","useSyncExternalStore"],"mappings":"yGAEMA,EAAoB,IAAM,GAgBnBC,EAAiBC,GAAkB,CAC9C,MAAMC,EAAYC,EAAAA,YACfC,GAAyB,CACxB,MAAMC,EAAa,OAAO,WAAWJ,CAAK,EAE1C,OAAAI,EAAW,iBAAiB,SAAUD,CAAQ,EACvC,IAAM,CACXC,EAAW,oBAAoB,SAAUD,CAAQ,CAAA,CACnD,EAEF,CAACH,CAAK,CAAA,EAGFK,EAAc,IAAM,OAAO,WAAWL,CAAK,EAAE,QAEnD,OAAOM,uBAAqBL,EAAWI,EAAaP,CAAiB,CACvE"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const l=require("react"),h=require("../useRefState/useRefState.cjs"),M=require("../useRerender/useRerender.cjs"),a=require("../../utils/helpers/isTarget.cjs"),S=((...s)=>{const n=a.isTarget(s[0])?s[0]:void 0,m=n?s[1]:s[0],t=l.useRef({x:0,y:0,elementX:0,elementY:0,elementPositionX:0,elementPositionY:0,clientX:0,clientY:0}),d=l.useRef(m);d.current=m;const X=l.useRef(!1),P=M.useRerender(),u=h.useRefState(),Y=(o,c)=>{t.current=o,d.current?.(o,c),X.current&&P()},f=()=>(X.current=!0,t.current);return l.useEffect(()=>{const o=e=>{const i=n?a.isTarget.getElement(n):u.current,r={x:e.pageX,y:e.pageY,clientX:e.clientX,clientY:e.clientY,elementX:e.pageX,elementY:e.pageY,elementPositionX:0,elementPositionY:0};if(i){const{left:R,top:p}=i.getBoundingClientRect(),g=R+window.scrollX,w=p+window.scrollY,E=e.pageX-g,y=e.pageY-w;r.elementX=E,r.elementY=y,r.elementPositionX=g,r.elementPositionY=w}Y(r,e)},c=e=>{const i={...t.current,x:t.current.x+window.scrollX-t.current.elementPositionX,y:t.current.y+window.scrollY-t.current.elementPositionY,elementPositionX:window.scrollX,elementPositionY:window.scrollY};Y(i,e)};return document.addEventListener("scroll",c,{passive:!0}),document.addEventListener("mousemove",o),()=>{document.removeEventListener("scroll",c),document.removeEventListener("mousemove",o)}},[u.state,n&&a.isTarget.getRawElement(n)]),n?{snapshot:t.current,watch:f}:{ref:u,snapshot:t.current,watch:f}});exports.useMouse=S;
|
|
2
2
|
//# sourceMappingURL=useMouse.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useMouse.cjs","sources":["../../../../src/hooks/useMouse/useMouse.ts"],"sourcesContent":["import { useEffect,
|
|
1
|
+
{"version":3,"file":"useMouse.cjs","sources":["../../../../src/hooks/useMouse/useMouse.ts"],"sourcesContent":["import { useEffect, useRef } from 'react';\n\nimport type { HookTarget } from '@/utils/helpers';\n\nimport { isTarget } from '@/utils/helpers';\n\nimport type { StateRef } from '../useRefState/useRefState';\n\nimport { useRefState } from '../useRefState/useRefState';\nimport { useRerender } from '../useRerender/useRerender';\n\n/** The use mouse return type */\nexport interface UseMouseReturn {\n /** The latest mouse value snapshot */\n snapshot: UseMouseValue;\n /** Function to enable subscriptions and rerender on next updates */\n watch: () => UseMouseValue;\n}\n\n/** The use mouse value type */\nexport interface UseMouseValue {\n /** The current mouse client x position */\n clientX: number;\n /** The current mouse client y position */\n clientY: number;\n /** The current element position x */\n elementPositionX: number;\n /** The current element position y */\n elementPositionY: number;\n /** The current element x position */\n elementX: number;\n /** The current element y position */\n elementY: number;\n /** The current mouse x position */\n x: number;\n /** The current mouse y position */\n y: number;\n}\n\nexport type UseMouseCallback = (value: UseMouseValue, event: Event) => void;\n\nexport interface UseMouse {\n (target: HookTarget, callback?: UseMouseCallback): UseMouseReturn;\n\n <Target extends Element>(\n callback?: UseMouseCallback,\n target?: never\n ): UseMouseReturn & {\n ref: StateRef<Target>;\n };\n\n (target?: Window, callback?: UseMouseCallback): UseMouseReturn;\n}\n\n/**\n * @name useMouse\n * @description - Hook that manages a mouse position\n * @category Sensors\n * @usage low\n *\n * @overload\n * @param {HookTarget} [target=window] The target element to manage the mouse position for\n * @param {(value: UseMouseValue, event: Event) => void} [callback] The callback to invoke on mouse updates\n * @returns {UseMouseReturn} An object with mouse value controls\n *\n * @example\n * const mouse = useMouse(ref);\n *\n * @overload\n * @template Target The target element\n * @param {(value: UseMouseValue, event: Event) => void} [callback] The callback to invoke on mouse updates\n * @returns {UseMouseReturn & { ref: StateRef<Target> }} An object with mouse value controls and a ref\n *\n * @example\n * const mouse = useMouse<HTMLDivElement>();\n */\nexport const useMouse = ((...params: any[]) => {\n const target = isTarget(params[0]) ? params[0] : undefined;\n const callback = (target ? params[1] : params[0]) as UseMouseCallback | undefined;\n\n const snapshotRef = useRef<UseMouseValue>({\n x: 0,\n y: 0,\n elementX: 0,\n elementY: 0,\n elementPositionX: 0,\n elementPositionY: 0,\n clientX: 0,\n clientY: 0\n });\n const internalCallbackRef = useRef(callback);\n internalCallbackRef.current = callback;\n const watchingRef = useRef(false);\n const rerender = useRerender();\n\n const internalRef = useRefState<Element>();\n\n const updateValue = (nextValue: UseMouseValue, event: Event) => {\n snapshotRef.current = nextValue;\n internalCallbackRef.current?.(nextValue, event);\n if (watchingRef.current) rerender();\n };\n\n const watch = () => {\n watchingRef.current = true;\n return snapshotRef.current;\n };\n\n useEffect(() => {\n const onMouseMove = (event: MouseEvent) => {\n const element = (target ? isTarget.getElement(target) : internalRef.current) as\n | Element\n | undefined;\n\n const updatedValue: UseMouseValue = {\n x: event.pageX,\n y: event.pageY,\n clientX: event.clientX,\n clientY: event.clientY,\n elementX: event.pageX,\n elementY: event.pageY,\n elementPositionX: 0,\n elementPositionY: 0\n };\n\n if (element) {\n const { left, top } = element.getBoundingClientRect();\n const elementPositionX = left + window.scrollX;\n const elementPositionY = top + window.scrollY;\n const elementX = event.pageX - elementPositionX;\n const elementY = event.pageY - elementPositionY;\n\n updatedValue.elementX = elementX;\n updatedValue.elementY = elementY;\n updatedValue.elementPositionX = elementPositionX;\n updatedValue.elementPositionY = elementPositionY;\n }\n\n updateValue(updatedValue, event);\n };\n\n const onScroll = (event: Event) => {\n const updatedValue: UseMouseValue = {\n ...snapshotRef.current,\n x: snapshotRef.current.x + window.scrollX - snapshotRef.current.elementPositionX,\n y: snapshotRef.current.y + window.scrollY - snapshotRef.current.elementPositionY,\n elementPositionX: window.scrollX,\n elementPositionY: window.scrollY\n };\n updateValue(updatedValue, event);\n };\n\n document.addEventListener('scroll', onScroll, { passive: true });\n document.addEventListener('mousemove', onMouseMove);\n return () => {\n document.removeEventListener('scroll', onScroll);\n document.removeEventListener('mousemove', onMouseMove);\n };\n }, [internalRef.state, target && isTarget.getRawElement(target)]);\n\n if (target) return { snapshot: snapshotRef.current, watch };\n return {\n ref: internalRef,\n snapshot: snapshotRef.current,\n watch\n };\n}) as UseMouse;\n"],"names":["useMouse","params","target","isTarget","callback","snapshotRef","useRef","internalCallbackRef","watchingRef","rerender","useRerender","internalRef","useRefState","updateValue","nextValue","event","watch","useEffect","onMouseMove","element","updatedValue","left","top","elementPositionX","elementPositionY","elementX","elementY","onScroll"],"mappings":"+OA4EaA,GAAY,IAAIC,IAAkB,CAC7C,MAAMC,EAASC,EAAAA,SAASF,EAAO,CAAC,CAAC,EAAIA,EAAO,CAAC,EAAI,OAC3CG,EAAYF,EAASD,EAAO,CAAC,EAAIA,EAAO,CAAC,EAEzCI,EAAcC,EAAAA,OAAsB,CACxC,EAAG,EACH,EAAG,EACH,SAAU,EACV,SAAU,EACV,iBAAkB,EAClB,iBAAkB,EAClB,QAAS,EACT,QAAS,CAAA,CACV,EACKC,EAAsBD,EAAAA,OAAOF,CAAQ,EAC3CG,EAAoB,QAAUH,EAC9B,MAAMI,EAAcF,EAAAA,OAAO,EAAK,EAC1BG,EAAWC,EAAAA,YAAA,EAEXC,EAAcC,EAAAA,YAAA,EAEdC,EAAc,CAACC,EAA0BC,IAAiB,CAC9DV,EAAY,QAAUS,EACtBP,EAAoB,UAAUO,EAAWC,CAAK,EAC1CP,EAAY,SAASC,EAAA,CAAS,EAG9BO,EAAQ,KACZR,EAAY,QAAU,GACfH,EAAY,SAuDrB,OApDAY,EAAAA,UAAU,IAAM,CACd,MAAMC,EAAeH,GAAsB,CACzC,MAAMI,EAAWjB,EAASC,EAAAA,SAAS,WAAWD,CAAM,EAAIS,EA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object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("react"),T=(E,a)=>{const[m,s]=n.useState(!1),[g,o]=n.useState(!1),[h,f]=n.useState(!1),[I,S]=n.useState(null),[M,D]=n.useState(null),y=(t,r)=>{s(!0);const e=r?.attempt??0;return E(t).then(c=>(r?.onSuccess?.(c),D(c),f(!0),s(!1),S(null),o(!1),c)).catch(c=>{const l=typeof r?.retry=="function"?r?.retry(e,c):r?.retry,u=typeof r?.retryDelay=="function"?r?.retryDelay(e,c):r?.retryDelay;if(typeof l=="boolean"&&l){if(u){setTimeout(()=>y(t,{...r,attempt:e+1}),u);return}return y(t,{...r,attempt:e+1})}if(l&&l>e){if(u){setTimeout(()=>y(t,{...r,attempt:e+1}),u);return}return y(t,{...r,attempt:e+1})}if(D(null),f(!1),s(!1),S(c),o(!0),!r?.onError)throw c;r?.onError?.(c)})};return{data:M,error:I,mutate:(t,r)=>{const e={retry:r?.retry??a?.retry,retryDelay:r?.retryDelay??a?.retryDelay,onSuccess:r?.onSuccess??a?.onSuccess,onError:r?.onError??a?.onError};y(t,e)},mutateAsync:async(t,r)=>{const e={retry:r?.retry??a?.retry,retryDelay:r?.retryDelay??a?.retryDelay,onSuccess:r?.onSuccess??a?.onSuccess,onError:r?.onError??a?.onError};return y(t,e)},isLoading:m,isError:g,isSuccess:h}};exports.useMutation=T;
|
|
2
2
|
//# sourceMappingURL=useMutation.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useMutation.cjs","sources":["../../../../src/hooks/useMutation/useMutation.ts"],"sourcesContent":["import { useState } from
|
|
1
|
+
{"version":3,"file":"useMutation.cjs","sources":["../../../../src/hooks/useMutation/useMutation.ts"],"sourcesContent":["import { useState } from \"react\";\r\n\r\n/* The type of the options */\r\ninterface UseMutationOptions<Data> {\r\n /* The retry count of requests */\r\n retry?: ((failureCount: number, error: Error) => boolean) | boolean | number;\r\n /* The retry delay of requests */\r\n retryDelay?: ((retry: number, error: Error) => number) | number;\r\n /* The callback function to be invoked on error */\r\n onError?: (error: Error) => void;\r\n /* The callback function to be invoked on success */\r\n onSuccess?: (data: Data) => void;\r\n}\r\n\r\n/* The use mutation return type */\r\ninterface UseMutationReturn<Body, Data> {\r\n /* The data of the mutation */\r\n data: Data | null;\r\n /* The error of the mutation */\r\n error: Error | null;\r\n /* The error state of the mutation */\r\n isError: boolean;\r\n /* The loading state of the mutation */\r\n isLoading: boolean;\r\n /* The success state of the mutation */\r\n isSuccess: boolean;\r\n /* The mutate function */\r\n mutate: (body?: Body, options?: UseMutationOptions<Data>) => void;\r\n /* The mutate async function */\r\n mutateAsync: (\r\n body?: Body,\r\n options?: UseMutationOptions<Data>\r\n ) => Promise<Data>;\r\n}\r\n\r\nexport interface RequestOptions<Data> extends UseMutationOptions<Data> {\r\n /* The attempt count */\r\n attempt?: number;\r\n}\r\n\r\n/**\r\n * @name useMutation\r\n * @description - Hook that defines the logic when mutate data\r\n * @category Async\r\n * @usage high\r\n *\r\n * @template Body The type of the body\r\n * @template Data The type of the data\r\n * @param {(body: Body) => Promise<Data>} callback The callback function to be invoked\r\n * @param {boolean | number} [options.retry] The retry count of requests\r\n * @param {(data: Data) => void} [options.onSuccess] The callback function to be invoked on success\r\n * @param {(error: Error) => void} [options.onError] The callback function to be invoked on error\r\n * @returns {UseMutationReturn<Data>} An object with the state of the mutation\r\n *\r\n * @example\r\n * const { mutate, mutateAsync, isLoading, isError, isSuccess, error, data } = useMutation((name) => Promise.resolve(name));\r\n */\r\nexport const useMutation = <Body, Data>(\r\n callback: (body: Body) => Promise<Data>,\r\n options?: UseMutationOptions<Data>\r\n) => {\r\n const [isLoading, setIsLoading] = useState(false);\r\n const [isError, setIsError] = useState(false);\r\n const [isSuccess, setIsSuccess] = useState(false);\r\n\r\n const [error, setError] = useState<Error | null>(null);\r\n const [data, setData] = useState<Data | null>(null);\r\n\r\n const request = (\r\n body: Body,\r\n requestOptions?: RequestOptions<Data>\r\n ): Promise<Data | undefined> => {\r\n setIsLoading(true);\r\n const attempt = requestOptions?.attempt ?? 0;\r\n\r\n return callback(body)\r\n .then((response) => {\r\n requestOptions?.onSuccess?.(response);\r\n\r\n setData(response);\r\n setIsSuccess(true);\r\n setIsLoading(false);\r\n setError(null);\r\n setIsError(false);\r\n return response;\r\n })\r\n .catch((error: Error) => {\r\n const retry =\r\n typeof requestOptions?.retry === \"function\"\r\n ? requestOptions?.retry(attempt, error)\r\n : requestOptions?.retry;\r\n\r\n const retryDelay =\r\n typeof requestOptions?.retryDelay === \"function\"\r\n ? requestOptions?.retryDelay(attempt, error)\r\n : requestOptions?.retryDelay;\r\n\r\n if (typeof retry === \"boolean\" && retry) {\r\n if (retryDelay) {\r\n setTimeout(\r\n () => request(body, { ...requestOptions, attempt: attempt + 1 }),\r\n retryDelay\r\n );\r\n return;\r\n }\r\n return request(body, { ...requestOptions, attempt: attempt + 1 });\r\n }\r\n\r\n if (retry && retry > attempt) {\r\n if (retryDelay) {\r\n setTimeout(\r\n () => request(body, { ...requestOptions, attempt: attempt + 1 }),\r\n retryDelay\r\n );\r\n return;\r\n }\r\n return request(body, { ...requestOptions, attempt: attempt + 1 });\r\n }\r\n\r\n setData(null);\r\n setIsSuccess(false);\r\n setIsLoading(false);\r\n setError(error);\r\n setIsError(true);\r\n if (!requestOptions?.onError) throw error;\r\n requestOptions?.onError?.(error);\r\n });\r\n };\r\n const mutate = (body: Body, mutateOptions?: UseMutationOptions<Data>) => {\r\n const requestOptions = {\r\n retry: mutateOptions?.retry ?? options?.retry,\r\n retryDelay: mutateOptions?.retryDelay ?? options?.retryDelay,\r\n onSuccess: mutateOptions?.onSuccess ?? options?.onSuccess,\r\n onError: mutateOptions?.onError ?? options?.onError,\r\n };\r\n\r\n request(body, requestOptions);\r\n };\r\n\r\n const mutateAsync = async (\r\n body: Body,\r\n mutateOptions?: UseMutationOptions<Data>\r\n ) => {\r\n const requestOptions = {\r\n retry: mutateOptions?.retry ?? options?.retry,\r\n retryDelay: mutateOptions?.retryDelay ?? options?.retryDelay,\r\n onSuccess: mutateOptions?.onSuccess ?? options?.onSuccess,\r\n onError: mutateOptions?.onError ?? options?.onError,\r\n };\r\n\r\n return request(body, requestOptions) as Promise<Data>;\r\n };\r\n\r\n return {\r\n data,\r\n error,\r\n mutate,\r\n mutateAsync,\r\n isLoading,\r\n isError,\r\n isSuccess,\r\n } as UseMutationReturn<Body, Data>;\r\n};\r\n"],"names":["useMutation","callback","options","isLoading","setIsLoading","useState","isError","setIsError","isSuccess","setIsSuccess","error","setError","data","setData","request","body","requestOptions","attempt","response","retry","retryDelay","mutateOptions"],"mappings":"yGAyDaA,EAAc,CACzBC,EACAC,IACG,CACH,KAAM,CAACC,EAAWC,CAAY,EAAIC,EAAAA,SAAS,EAAK,EAC1C,CAACC,EAASC,CAAU,EAAIF,EAAAA,SAAS,EAAK,EACtC,CAACG,EAAWC,CAAY,EAAIJ,EAAAA,SAAS,EAAK,EAE1C,CAACK,EAAOC,CAAQ,EAAIN,EAAAA,SAAuB,IAAI,EAC/C,CAACO,EAAMC,CAAO,EAAIR,EAAAA,SAAsB,IAAI,EAE5CS,EAAU,CACdC,EACAC,IAC8B,CAC9BZ,EAAa,EAAI,EACjB,MAAMa,EAAUD,GAAgB,SAAW,EAE3C,OAAOf,EAASc,CAAI,EACjB,KAAMG,IACLF,GAAgB,YAAYE,CAAQ,EAEpCL,EAAQK,CAAQ,EAChBT,EAAa,EAAI,EACjBL,EAAa,EAAK,EAClBO,EAAS,IAAI,EACbJ,EAAW,EAAK,EACTW,EACR,EACA,MAAOR,GAAiB,CACvB,MAAMS,EACJ,OAAOH,GAAgB,OAAU,WAC7BA,GAAgB,MAAMC,EAASP,CAAK,EACpCM,GAAgB,MAEhBI,EACJ,OAAOJ,GAAgB,YAAe,WAClCA,GAAgB,WAAWC,EAASP,CAAK,EACzCM,GAAgB,WAEtB,GAAI,OAAOG,GAAU,WAAaA,EAAO,CACvC,GAAIC,EAAY,CACd,WACE,IAAMN,EAAQC,EAAM,CAAE,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