@siberiacancode/reactuse 0.3.4 → 0.3.6
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/dist/cjs/helpers/createStore/createStore.cjs +1 -1
- package/dist/cjs/helpers/createStore/createStore.cjs.map +1 -1
- package/dist/cjs/hooks/useBatchedCallback/useBatchedCallback.cjs +2 -0
- package/dist/cjs/hooks/useBatchedCallback/useBatchedCallback.cjs.map +1 -0
- package/dist/cjs/hooks/useDropZone/useDropZone.cjs.map +1 -1
- package/dist/cjs/hooks/useEventListener/useEventListener.cjs +1 -1
- package/dist/cjs/hooks/useEventListener/useEventListener.cjs.map +1 -1
- package/dist/cjs/hooks/useEventSource/useEventSource.cjs +1 -1
- package/dist/cjs/hooks/useEventSource/useEventSource.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/useLongPress/useLongPress.cjs +1 -1
- package/dist/cjs/hooks/useLongPress/useLongPress.cjs.map +1 -1
- package/dist/cjs/hooks/useOtpCredential/useOtpCredential.cjs +1 -1
- package/dist/cjs/hooks/useOtpCredential/useOtpCredential.cjs.map +1 -1
- package/dist/cjs/hooks/useSpeechRecognition/useSpeechRecognition.cjs +1 -1
- package/dist/cjs/hooks/useSpeechRecognition/useSpeechRecognition.cjs.map +1 -1
- package/dist/cjs/hooks/useSpeechSynthesis/useSpeechSynthesis.cjs +1 -1
- package/dist/cjs/hooks/useSpeechSynthesis/useSpeechSynthesis.cjs.map +1 -1
- package/dist/cjs/hooks/useStorage/useStorage.cjs +1 -1
- package/dist/cjs/hooks/useStorage/useStorage.cjs.map +1 -1
- package/dist/cjs/hooks/useTextareaAutosize/useTextareaAutosize.cjs +1 -1
- package/dist/cjs/hooks/useTextareaAutosize/useTextareaAutosize.cjs.map +1 -1
- package/dist/cjs/hooks/useWindowFocus/useWindowFocus.cjs +1 -1
- package/dist/cjs/hooks/useWindowFocus/useWindowFocus.cjs.map +1 -1
- package/dist/cjs/index.cjs +1 -1
- package/dist/esm/helpers/createStore/createStore.mjs +10 -9
- package/dist/esm/helpers/createStore/createStore.mjs.map +1 -1
- package/dist/esm/hooks/useBatchedCallback/useBatchedCallback.mjs +20 -0
- package/dist/esm/hooks/useBatchedCallback/useBatchedCallback.mjs.map +1 -0
- package/dist/esm/hooks/useDropZone/useDropZone.mjs.map +1 -1
- package/dist/esm/hooks/useEventListener/useEventListener.mjs +8 -8
- package/dist/esm/hooks/useEventListener/useEventListener.mjs.map +1 -1
- package/dist/esm/hooks/useEventSource/useEventSource.mjs +33 -34
- package/dist/esm/hooks/useEventSource/useEventSource.mjs.map +1 -1
- package/dist/esm/hooks/useField/useField.mjs +2 -1
- package/dist/esm/hooks/useField/useField.mjs.map +1 -1
- package/dist/esm/hooks/useLongPress/useLongPress.mjs +19 -19
- package/dist/esm/hooks/useLongPress/useLongPress.mjs.map +1 -1
- package/dist/esm/hooks/useOtpCredential/useOtpCredential.mjs +14 -12
- package/dist/esm/hooks/useOtpCredential/useOtpCredential.mjs.map +1 -1
- package/dist/esm/hooks/useSpeechRecognition/useSpeechRecognition.mjs +19 -22
- package/dist/esm/hooks/useSpeechRecognition/useSpeechRecognition.mjs.map +1 -1
- package/dist/esm/hooks/useSpeechSynthesis/useSpeechSynthesis.mjs +51 -36
- package/dist/esm/hooks/useSpeechSynthesis/useSpeechSynthesis.mjs.map +1 -1
- package/dist/esm/hooks/useStorage/useStorage.mjs +39 -36
- package/dist/esm/hooks/useStorage/useStorage.mjs.map +1 -1
- package/dist/esm/hooks/useTextareaAutosize/useTextareaAutosize.mjs +36 -41
- package/dist/esm/hooks/useTextareaAutosize/useTextareaAutosize.mjs.map +1 -1
- package/dist/esm/hooks/useWindowFocus/useWindowFocus.mjs +1 -1
- package/dist/esm/hooks/useWindowFocus/useWindowFocus.mjs.map +1 -1
- package/dist/esm/index.mjs +53 -51
- package/dist/esm/index.mjs.map +1 -1
- package/dist/types/helpers/createStore/createStore.d.ts +5 -12
- package/dist/types/hooks/useBatchedCallback/useBatchedCallback.d.ts +19 -0
- package/dist/types/hooks/useEventSource/useEventSource.d.ts +2 -2
- package/dist/types/hooks/useField/useField.d.ts +3 -0
- package/dist/types/hooks/useOtpCredential/useOtpCredential.d.ts +2 -3
- package/dist/types/hooks/useSpeechRecognition/useSpeechRecognition.d.ts +1 -1
- package/dist/types/hooks/useSpeechSynthesis/useSpeechSynthesis.d.ts +1 -1
- package/dist/types/hooks/useTextareaAutosize/useTextareaAutosize.d.ts +10 -1
- package/dist/types/hooks/utilities.d.ts +1 -0
- package/package.json +1 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const y=require("react"),b=s=>{let e;const
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const y=require("react"),b=s=>{let e,o;const i=new Set,a=t=>{const n=typeof t=="function"?t(e):t;if(!Object.is(n,e)){const f=e;e=typeof n!="object"||n===null||Array.isArray(n)?n:Object.assign({},e,n),i.forEach(l=>l(e,f))}},u=t=>(i.add(t),()=>i.delete(t)),r=()=>e,c=()=>o;typeof s=="function"?o=e=s(a,r):o=e=s;function S(t){return y.useSyncExternalStore(u,()=>t?t(r()):r(),()=>t?t(c()):c())}return{set:a,get:r,getInitial:c,use:S,subscribe:u}};exports.createStore=b;
|
|
2
2
|
//# sourceMappingURL=createStore.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createStore.cjs","sources":["../../../../src/helpers/createStore/createStore.ts"],"sourcesContent":["import { useSyncExternalStore } from 'react';\n\ntype StoreSetAction<Value> = ((prev: Value) => Partial<Value>) | Partial<Value>;\n\ntype StoreListener<Value> = (state: Value, prevState: Value) => void;\n\ntype StoreCreator<Value> = (\n set: (action: StoreSetAction<Value>) => void,\n get: () => Value\n) => Value;\n\nexport interface StoreApi<Value> {\n
|
|
1
|
+
{"version":3,"file":"createStore.cjs","sources":["../../../../src/helpers/createStore/createStore.ts"],"sourcesContent":["import { useSyncExternalStore } from 'react';\n\ntype StoreSetAction<Value> = ((prev: Value) => Partial<Value>) | Partial<Value>;\n\ntype StoreListener<Value> = (state: Value, prevState: Value) => void;\n\ntype StoreCreator<Value> = (\n set: (action: StoreSetAction<Value>) => void,\n get: () => Value\n) => Value;\n\nexport interface StoreApi<Value> {\n get: () => Value;\n getInitial: () => Value;\n set: (action: StoreSetAction<Value>) => void;\n subscribe: (listener: StoreListener<Value>) => () => void;\n\n use: (() => Value) &\n (<Selected>(selector: (state: Value) => Selected) => Selected) &\n (<Selected>(selector?: (state: Value) => Selected) => Selected | Value);\n}\n\n/**\n * @name createStore\n * @description - Creates a store with state management capabilities\n * @category Helpers\n * @usage medium\n *\n * @template Value - The type of the store state\n * @param {StateCreator<Value>} createState - Function that initializes the store state\n * @returns {StoreApi<Value>} - Object containing store methods and hook for accessing state\n *\n * @example\n * const { set, get, use, subscribe } = createStore((set) => ({\n * count: 0,\n * increment: () => set(state => ({ count: state.count + 1 }))\n * }));\n */\nexport const createStore = <Value>(createState: StoreCreator<Value> | Value): StoreApi<Value> => {\n let state: Value;\n let initialState: Value;\n const listeners: Set<StoreListener<Value>> = new Set();\n\n const setState: StoreApi<Value>['set'] = (action: StoreSetAction<Value>) => {\n const nextState = typeof action === 'function' ? action(state) : action;\n\n if (!Object.is(nextState, state)) {\n const prevState = state;\n state = (\n typeof nextState !== 'object' || nextState === null || Array.isArray(nextState)\n ? nextState\n : Object.assign({}, state, nextState)\n ) as Value;\n\n listeners.forEach((listener) => listener(state, prevState));\n }\n };\n\n const subscribe = (listener: StoreListener<Value>) => {\n listeners.add(listener);\n\n return () => listeners.delete(listener);\n };\n\n const getState = () => state;\n const getInitialState = () => initialState;\n\n if (typeof createState === 'function') {\n initialState = state = (createState as StoreCreator<Value>)(setState, getState);\n } else {\n initialState = state = createState;\n }\n\n function useStore(): Value;\n function useStore<Selected>(selector: (state: Value) => Selected): Selected;\n function useStore<Selected>(selector?: (state: Value) => Selected): Selected | Value {\n return useSyncExternalStore(\n subscribe,\n () => (selector ? selector(getState()) : getState()),\n () => (selector ? selector(getInitialState()) : getInitialState())\n );\n }\n\n return {\n set: setState,\n get: getState,\n getInitial: getInitialState,\n use: useStore,\n subscribe\n };\n};\n"],"names":["createStore","createState","state","initialState","listeners","setState","action","nextState","prevState","listener","subscribe","getState","getInitialState","useStore","selector","useSyncExternalStore"],"mappings":"yGAsCaA,EAAsBC,GAA8D,CAC/F,IAAIC,EACAC,EACJ,MAAMC,MAA2C,IAE3CC,EAAoCC,GAAkC,CAC1E,MAAMC,EAAY,OAAOD,GAAW,WAAaA,EAAOJ,CAAK,EAAII,EAEjE,GAAI,CAAC,OAAO,GAAGC,EAAWL,CAAK,EAAG,CAChC,MAAMM,EAAYN,EAClBA,EACE,OAAOK,GAAc,UAAYA,IAAc,MAAQ,MAAM,QAAQA,CAAS,EAC1EA,EACA,OAAO,OAAO,CAAA,EAAIL,EAAOK,CAAS,EAGxCH,EAAU,QAASK,GAAaA,EAASP,EAAOM,CAAS,CAAC,CAAA,CAC5D,EAGIE,EAAaD,IACjBL,EAAU,IAAIK,CAAQ,EAEf,IAAML,EAAU,OAAOK,CAAQ,GAGlCE,EAAW,IAAMT,EACjBU,EAAkB,IAAMT,EAE1B,OAAOF,GAAgB,WACzBE,EAAeD,EAASD,EAAoCI,EAAUM,CAAQ,EAE9ER,EAAeD,EAAQD,EAKzB,SAASY,EAAmBC,EAAyD,CACnF,OAAOC,EAAAA,qBACLL,EACA,IAAOI,EAAWA,EAASH,EAAA,CAAU,EAAIA,EAAA,EACzC,IAAOG,EAAWA,EAASF,EAAA,CAAiB,EAAIA,EAAA,CAAgB,CAClE,CAGF,MAAO,CACL,IAAKP,EACL,IAAKM,EACL,WAAYC,EACZ,IAAKC,EACL,UAAAH,CAAA,CAEJ"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const c=require("react"),o=(r,u)=>{const n=c.useRef(r),s=c.useRef(u),e=c.useRef([]);n.current=r,s.current=u;const a=()=>{if(!e.current.length)return;const t=e.current;e.current=[],n.current(t)};return c.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
|
+
//# sourceMappingURL=useBatchedCallback.cjs.map
|
|
@@ -0,0 +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 callbackRef = useRef(callback);\n const sizeRef = useRef(size);\n const queueRef = useRef<Params[]>([]);\n\n callbackRef.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 callbackRef.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","callbackRef","useRef","sizeRef","queueRef","flush","batch","useMemo","batchedCallback","args"],"mappings":"yGAqBaA,EAAqB,CAChCC,EACAC,IAC4B,CAC5B,MAAMC,EAAcC,EAAAA,OAAOH,CAAQ,EAC7BI,EAAUD,EAAAA,OAAOF,CAAI,EACrBI,EAAWF,EAAAA,OAAiB,EAAE,EAEpCD,EAAY,QAAUF,EACtBI,EAAQ,QAAUH,EAElB,MAAMK,EAAQ,IAAM,CAClB,GAAI,CAACD,EAAS,QAAQ,OAAQ,OAC9B,MAAME,EAAQF,EAAS,QACvBA,EAAS,QAAU,CAAA,EACnBH,EAAY,QAAQK,CAAK,CAAA,EAe3B,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 +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 */\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, internalRef.state, isTarget.getRefState(target)]);\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":"mMAyGaA,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,CA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EAAU,EAAK,EACfH,EAASoB,CAAY,EACrB1B,EAAQ,SAAS0B,EAAcd,CAAK,EACpC,MAAA,CAGF,GAAII,IAAS,QAAS,CACpBb,EAAW,SAAW,EACtBM,EAAU,EAAI,EACdT,EAAQ,UAAUY,CAAK,EACvB,MAAA,CAGF,GAAII,IAAS,QAAS,CAEpB,GADAb,EAAW,SAAW,EAClBA,EAAW,UAAY,EAAG,OAC9BM,EAAU,EAAK,EACfT,EAAQ,UAAUY,CAAK,EACvB,MAAA,CAGEI,IAAS,QAAQhB,EAAQ,SAASY,CAAK,CAAA,EAGvCe,GAAWf,GAAqBa,EAAQb,EAAO,MAAM,GACrDgB,GAAehB,GAAqBa,EAAQb,EAAO,MAAM,GACzDiB,GAAgBjB,GAAqBa,EAAQb,EAAO,OAAO,GAC3DkB,GAAgBlB,GAAqBa,EAAQb,EAAO,OAAO,GAEjE,OAAAY,EAAQ,iBAAiB,YAAaK,CAAW,EACjDL,EAAQ,iBAAiB,WAAYI,CAAU,EAC/CJ,EAAQ,iBAAiB,YAAaM,CAAW,EACjDN,EAAQ,iBAAiB,OAAQG,CAAM,EAEhC,IAAM,CACXH,EAAQ,oBAAoB,YAAaK,CAAW,EACpDL,EAAQ,oBAAoB,WAAYI,CAAU,EAClDJ,EAAQ,oBAAoB,YAAaM,CAAW,EACpDN,EAAQ,oBAAoB,OAAQG,CAAM,CAAA,CAC5C,EACC,CAAC7B,EAAQG,EAAY,MAAOF,EAAAA,SAAS,YAAYD,CAAM,CAAC,CAAC,EAExDA,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, 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, internalRef.state, isTarget.getRefState(target)]);\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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AAQG,EAAY,MAAOF,EAAAA,SAAS,YAAYD,CAAM,CAAC,CAAC,EAExDA,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 i=require("react"),R=require("../useRefState/useRefState.cjs"),o=require("../../utils/helpers/isTarget.cjs"),E=((...
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("react"),R=require("../useRefState/useRefState.cjs"),o=require("../../utils/helpers/isTarget.cjs"),E=((...e)=>{const t=o.isTarget(e[0])?e[0]:void 0,r=t?e[1]:e[0],c=t?e[2]:e[1],n=t?e[3]:e[2],u=n?.enabled??!0,s=R.useRefState(),f=i.useRef(c);f.current=c;const d=i.useRef(n);if(d.current=n,i.useEffect(()=>{if(!u)return;const l=(t?o.isTarget.getElement(t):s.current)??window,g=v=>f.current(v);return l.addEventListener(r,g,n),()=>{l.removeEventListener(r,g,n)}},[t,s.state,o.isTarget.getRefState(t),r,u]),!t)return s});exports.useEventListener=E;
|
|
2
2
|
//# sourceMappingURL=useEventListener.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useEventListener.cjs","sources":["../../../../src/hooks/useEventListener/useEventListener.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';\n\n/** The use event listener options */\nexport type UseEventListenerOptions = {\n enabled?: boolean;\n} & AddEventListenerOptions;\n\n/** The use event listener return type */\nexport type UseEventListenerReturn<Target extends Element> = StateRef<Target>;\n\nexport interface UseEventListener {\n <Event extends keyof WindowEventMap = keyof WindowEventMap>(\n target: HookTarget,\n event: Event,\n listener: (this: Window, event: WindowEventMap[Event]) => void,\n options?: UseEventListenerOptions\n ): void;\n\n <Event extends keyof DocumentEventMap = keyof DocumentEventMap>(\n target: HookTarget,\n event: Event,\n listener: (this: Document, event: DocumentEventMap[Event]) => void,\n options?: UseEventListenerOptions\n ): void;\n\n <Event extends keyof HTMLElementEventMap = keyof HTMLElementEventMap>(\n target: HookTarget,\n event: Event,\n listener: (this: Element, event: HTMLElementEventMap[Event]) => void,\n options?: UseEventListenerOptions\n ): void;\n\n <Target extends Element, Event extends keyof HTMLElementEventMap = keyof HTMLElementEventMap>(\n event: Event,\n listener: (this: Target, event: HTMLElementEventMap[Event]) => void,\n options?: UseEventListenerOptions,\n target?: never\n ): UseEventListenerReturn<Target>;\n\n <\n Target extends Element,\n Event extends keyof MediaQueryListEventMap = keyof MediaQueryListEventMap\n >(\n event: Event,\n listener: (this: Target, event: MediaQueryListEventMap[Event]) => void,\n options?: UseEventListenerOptions,\n target?: never\n ): UseEventListenerReturn<Target>;\n}\n\n/**\n * @name useEventListener\n * @description - Hook that attaches an event listener to the specified target\n * @category Browser\n * @usage necessary\n\n * @overload\n * @template Event Key of window event map\n * @param {Window} target The window object to attach the event listener to\n * @param {Event | Event[]} event An array of event types to listen for\n * @param {(this: Window, event: WindowEventMap[Event]) => void} handler The event handler function\n * @param {UseEventListenerOptions} [options] Options for the event listener\n * @returns {void}\n *\n * @example\n * useEventListener(window, 'click', () => console.log('click'));\n *\n * @overload\n * @template Event Key of window event map\n * @param {Document} target The window object to attach the event listener to\n * @param {Event | Event[]} event An array of event types to listen for\n * @param {(this: Document, event: DocumentEventMap[Event]) => void} handler The event handler function\n * @param {UseEventListenerOptions} [options] Options for the event listener\n * @returns {void}\n *\n * @example\n * useEventListener(document, 'click', () => console.log('click'));\n *\n * @overload\n * @template Event Key of window event map\n * @template Target The target element\n * @param {HookTarget} target The target element to attach the event listener to\n * @param {Event | Event[]} event An array of event types to listen for\n * @param {(this: Target, event: HTMLElementEventMap[Event]) => void} handler The event handler function\n * @param {UseEventListenerOptions} [options] Options for the event listener\n * @returns {void}\n *\n * @example\n * useEventListener(ref, 'click', () => console.log('click'));\n *\n * @overload\n * @template Event Key of window event map\n * @template Target The target element\n * @param {Event | Event[]} event An array of event types to listen for\n * @param {(this: Target, event: HTMLElementEventMap[Event] | MediaQueryListEventMap[Event]) => void} handler The event handler function\n * @param {UseEventListenerOptions} [options] Options for the event listener\n * @returns {UseEventListenerReturn<Target>} A reference to the target element\n *\n * @example\n * const ref = useEventListener('click', () => console.log('click'));\n */\nexport const useEventListener = ((...params: any[]) => {\n const target = (isTarget(params[0]) ? params[0] : undefined) as HookTarget | undefined;\n const event = (target ? params[1] : params[0]) as string;\n const listener = (target ? params[2] : params[1]) as (...arg: any[]) => undefined | void;\n const options = (target ? params[3] : params[2]) as UseEventListenerOptions | undefined;\n\n const enabled = options?.enabled ?? true;\n\n const internalRef = useRefState();\n const internalListenerRef = useRef(listener);\n internalListenerRef.current = listener;\n const internalOptionsRef = useRef(options);\n internalOptionsRef.current = options;\n\n useEffect(() => {\n if (!enabled
|
|
1
|
+
{"version":3,"file":"useEventListener.cjs","sources":["../../../../src/hooks/useEventListener/useEventListener.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';\n\n/** The use event listener options */\nexport type UseEventListenerOptions = {\n enabled?: boolean;\n} & AddEventListenerOptions;\n\n/** The use event listener return type */\nexport type UseEventListenerReturn<Target extends Element> = StateRef<Target>;\n\nexport interface UseEventListener {\n <Event extends keyof WindowEventMap = keyof WindowEventMap>(\n target: HookTarget,\n event: Event,\n listener: (this: Window, event: WindowEventMap[Event]) => void,\n options?: UseEventListenerOptions\n ): void;\n\n <Event extends keyof DocumentEventMap = keyof DocumentEventMap>(\n target: HookTarget,\n event: Event,\n listener: (this: Document, event: DocumentEventMap[Event]) => void,\n options?: UseEventListenerOptions\n ): void;\n\n <Event extends keyof HTMLElementEventMap = keyof HTMLElementEventMap>(\n target: HookTarget,\n event: Event,\n listener: (this: Element, event: HTMLElementEventMap[Event]) => void,\n options?: UseEventListenerOptions\n ): void;\n\n <Target extends Element, Event extends keyof HTMLElementEventMap = keyof HTMLElementEventMap>(\n event: Event,\n listener: (this: Target, event: HTMLElementEventMap[Event]) => void,\n options?: UseEventListenerOptions,\n target?: never\n ): UseEventListenerReturn<Target>;\n\n <\n Target extends Element,\n Event extends keyof MediaQueryListEventMap = keyof MediaQueryListEventMap\n >(\n event: Event,\n listener: (this: Target, event: MediaQueryListEventMap[Event]) => void,\n options?: UseEventListenerOptions,\n target?: never\n ): UseEventListenerReturn<Target>;\n}\n\n/**\n * @name useEventListener\n * @description - Hook that attaches an event listener to the specified target\n * @category Browser\n * @usage necessary\n\n * @overload\n * @template Event Key of window event map\n * @param {Window} target The window object to attach the event listener to\n * @param {Event | Event[]} event An array of event types to listen for\n * @param {(this: Window, event: WindowEventMap[Event]) => void} handler The event handler function\n * @param {UseEventListenerOptions} [options] Options for the event listener\n * @returns {void}\n *\n * @example\n * useEventListener(window, 'click', () => console.log('click'));\n *\n * @overload\n * @template Event Key of window event map\n * @param {Document} target The window object to attach the event listener to\n * @param {Event | Event[]} event An array of event types to listen for\n * @param {(this: Document, event: DocumentEventMap[Event]) => void} handler The event handler function\n * @param {UseEventListenerOptions} [options] Options for the event listener\n * @returns {void}\n *\n * @example\n * useEventListener(document, 'click', () => console.log('click'));\n *\n * @overload\n * @template Event Key of window event map\n * @template Target The target element\n * @param {HookTarget} target The target element to attach the event listener to\n * @param {Event | Event[]} event An array of event types to listen for\n * @param {(this: Target, event: HTMLElementEventMap[Event]) => void} handler The event handler function\n * @param {UseEventListenerOptions} [options] Options for the event listener\n * @returns {void}\n *\n * @example\n * useEventListener(ref, 'click', () => console.log('click'));\n *\n * @overload\n * @template Event Key of window event map\n * @template Target The target element\n * @param {Event | Event[]} event An array of event types to listen for\n * @param {(this: Target, event: HTMLElementEventMap[Event] | MediaQueryListEventMap[Event]) => void} handler The event handler function\n * @param {UseEventListenerOptions} [options] Options for the event listener\n * @returns {UseEventListenerReturn<Target>} A reference to the target element\n *\n * @example\n * const ref = useEventListener('click', () => console.log('click'));\n */\nexport const useEventListener = ((...params: any[]) => {\n const target = (isTarget(params[0]) ? params[0] : undefined) as HookTarget | undefined;\n const event = (target ? params[1] : params[0]) as string;\n const listener = (target ? params[2] : params[1]) as (...arg: any[]) => undefined | void;\n const options = (target ? params[3] : params[2]) as UseEventListenerOptions | undefined;\n\n const enabled = options?.enabled ?? true;\n\n const internalRef = useRefState();\n const internalListenerRef = useRef(listener);\n internalListenerRef.current = listener;\n const internalOptionsRef = useRef(options);\n internalOptionsRef.current = options;\n\n useEffect(() => {\n if (!enabled) return;\n\n const element =\n ((target ? isTarget.getElement(target) : internalRef.current) as Element) ?? window;\n\n const listener = (event: Event) => internalListenerRef.current(event);\n\n element.addEventListener(event, listener, options);\n return () => {\n element.removeEventListener(event, listener, options);\n };\n }, [target, internalRef.state, isTarget.getRefState(target), event, enabled]);\n\n if (target) return;\n return internalRef;\n}) as UseEventListener;\n"],"names":["useEventListener","params","target","isTarget","event","listener","options","enabled","internalRef","useRefState","internalListenerRef","useRef","internalOptionsRef","useEffect","element"],"mappings":"mMA6GaA,GAAoB,IAAIC,IAAkB,CACrD,MAAMC,EAAUC,EAAAA,SAASF,EAAO,CAAC,CAAC,EAAIA,EAAO,CAAC,EAAI,OAC5CG,EAASF,EAASD,EAAO,CAAC,EAAIA,EAAO,CAAC,EACtCI,EAAYH,EAASD,EAAO,CAAC,EAAIA,EAAO,CAAC,EACzCK,EAAWJ,EAASD,EAAO,CAAC,EAAIA,EAAO,CAAC,EAExCM,EAAUD,GAAS,SAAW,GAE9BE,EAAcC,EAAAA,YAAA,EACdC,EAAsBC,EAAAA,OAAON,CAAQ,EAC3CK,EAAoB,QAAUL,EAC9B,MAAMO,EAAqBD,EAAAA,OAAOL,CAAO,EAiBzC,GAhBAM,EAAmB,QAAUN,EAE7BO,EAAAA,UAAU,IAAM,CACd,GAAI,CAACN,EAAS,OAEd,MAAMO,GACFZ,EAASC,EAAAA,SAAS,WAAWD,CAAM,EAAIM,EAAY,UAAwB,OAEzEH,EAAYD,GAAiBM,EAAoB,QAAQN,CAAK,EAEpE,OAAAU,EAAQ,iBAAiBV,EAAOC,EAAUC,CAAO,EAC1C,IAAM,CACXQ,EAAQ,oBAAoBV,EAAOC,EAAUC,CAAO,CAAA,CACtD,EACC,CAACJ,EAAQM,EAAY,MAAOL,EAAAA,SAAS,YAAYD,CAAM,EAAGE,EAAOG,CAAO,CAAC,EAExE,CAAAL,EACJ,OAAOM,CACT"}
|
|
@@ -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 n=require("react"),v=require("../../utils/helpers/getRetry.cjs"),O=(R,y=[],e={})=>{const[m,s]=n.useState(!1),[D,f]=n.useState(!1),[h,d]=n.useState(!1),a=n.useRef(e?.retry?v.getRetry(e.retry):0),[C,i]=n.useState(void 0),[w,E]=n.useState(e?.placeholderData),c=n.useRef(void 0),S=e.immediately??!0,g=n.useRef(r=>E(r.data)),l=()=>{c.current&&(f(!1),s(!1),d(!1),y.forEach(r=>c.current.removeEventListener(r,g.current)),c.current.close(),c.current=void 0)},u=()=>{l();const r=new EventSource(R,{withCredentials:e.withCredentials??!1});c.current=r,s(!0),r.onopen=()=>{f(!0),s(!1),i(void 0),e?.onOpen?.()},r.onerror=t=>{if(f(!1),s(!1),d(!0),i(t),e?.onError?.(t),a.current>0){a.current-=1;const o=typeof e?.retryDelay=="function"?e?.retryDelay(a.current,t):e?.retryDelay;if(o){setTimeout(u,o);return}return u()}a.current=e?.retry?v.getRetry(e.retry):0},r.onmessage=t=>{const o=e?.select?e?.select(t.data):t.data;E(o),e?.onMessage?.(t)},y.forEach(t=>r.addEventListener(t,g.current))};return n.useEffect(()=>{if(S)return u(),()=>{l()}},[S]),{instance:c.current,data:w,error:C,isConnecting:m,opened:D,isError:h,close:l,open:u}};exports.useEventSource=O;
|
|
2
2
|
//# sourceMappingURL=useEventSource.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useEventSource.cjs","sources":["../../../../src/hooks/useEventSource/useEventSource.ts"],"sourcesContent":["import { useEffect, useRef, useState } from 'react';\n\nimport { getRetry } from '@/utils/helpers';\n\n/** The use event source options type */\nexport interface UseEventSourceOptions<QueryData, Data> extends EventSourceInit {\n /** Immediately open the connection when calling this hook */\n immediately?: boolean;\n /* The placeholder data for the hook */\n placeholderData?: (() => Data) | Data;\n /* The retry count of requests */\n retry?: boolean | number;\n /* The retry delay of requests */\n retryDelay?: ((retry: number, event: Event) => number) | number;\n /* The onError function to be invoked */\n onError?: (error: Event) => void;\n /* The onMessage function to be invoked */\n onMessage?: (event: Event & { data?: Data }) => void;\n /* The onOpen function to be invoked */\n onOpen?: () => void;\n /* The select function to be invoked */\n select?: (data: QueryData) => Data;\n}\n\n/** The use event source return type */\ninterface UseEventSourceReturn<Data = any> {\n /** The latest data received via the EventSource */\n data?: Data;\n /** The current error */\n error?: Event;\n /** The instance of the EventSource */\n instance?: EventSource;\n /* The connecting state of the query */\n isConnecting: boolean;\n /* The error state of the query */\n isError: boolean;\n /* The open state of the query */\n
|
|
1
|
+
{"version":3,"file":"useEventSource.cjs","sources":["../../../../src/hooks/useEventSource/useEventSource.ts"],"sourcesContent":["import { useEffect, useRef, useState } from 'react';\n\nimport { getRetry } from '@/utils/helpers';\n\n/** The use event source options type */\nexport interface UseEventSourceOptions<QueryData, Data> extends EventSourceInit {\n /** Immediately open the connection when calling this hook */\n immediately?: boolean;\n /* The placeholder data for the hook */\n placeholderData?: (() => Data) | Data;\n /* The retry count of requests */\n retry?: boolean | number;\n /* The retry delay of requests */\n retryDelay?: ((retry: number, event: Event) => number) | number;\n /* The onError function to be invoked */\n onError?: (error: Event) => void;\n /* The onMessage function to be invoked */\n onMessage?: (event: Event & { data?: Data }) => void;\n /* The onOpen function to be invoked */\n onOpen?: () => void;\n /* The select function to be invoked */\n select?: (data: QueryData) => Data;\n}\n\n/** The use event source return type */\ninterface UseEventSourceReturn<Data = any> {\n /** The latest data received via the EventSource */\n data?: Data;\n /** The current error */\n error?: Event;\n /** The instance of the EventSource */\n instance?: EventSource;\n /* The connecting state of the query */\n isConnecting: boolean;\n /* The error state of the query */\n isError: boolean;\n /* The open state of the query */\n opened: boolean;\n /** Closes the EventSource connection gracefully */\n close: () => void;\n /** Reopen the EventSource connection */\n open: () => void;\n}\n\n/**\n * @name useEventSource\n * @description - Hook that provides a reactive wrapper for event source\n * @category Browser\n * @usage low\n *\n * @browserapi EventSource https://developer.mozilla.org/en-US/docs/Web/API/EventSource\n *\n * @param {string | URL} url The URL of the EventSource\n * @param {string[]} [events=[]] List of events to listen to\n * @param {UseEventSourceOptions} [options={}] Configuration options\n * @returns {UseEventSourceReturn<Data>} The EventSource state and controls\n *\n * @example\n * const { instance, data, connecting, opened, isError, close, open } = useEventSource('url', ['message']);\n */\nexport const useEventSource = <QueryData = any, Data = QueryData>(\n url: string | URL,\n events: string[] = [],\n options: UseEventSourceOptions<QueryData, Data> = {}\n): UseEventSourceReturn<Data> => {\n const [isConnecting, setIsConnecting] = useState(false);\n const [opened, setOpened] = useState(false);\n const [isError, setIsError] = useState(false);\n\n const retryCountRef = useRef(options?.retry ? getRetry(options.retry) : 0);\n const [error, setError] = useState<Event | undefined>(undefined);\n const [data, setData] = useState<Data | undefined>(options?.placeholderData);\n\n const eventSourceRef = useRef<EventSource>(undefined);\n\n const immediately = options.immediately ?? true;\n\n const onEventRef = useRef((event: Event & { data?: Data }) => setData(event.data));\n\n const close = () => {\n if (!eventSourceRef.current) return;\n\n setOpened(false);\n setIsConnecting(false);\n setIsError(false);\n\n events.forEach((eventName) =>\n eventSourceRef.current!.removeEventListener(eventName, onEventRef.current)\n );\n\n eventSourceRef.current.close();\n eventSourceRef.current = undefined;\n };\n\n const open = () => {\n close();\n\n const eventSource = new EventSource(url, {\n withCredentials: options.withCredentials ?? false\n });\n eventSourceRef.current = eventSource;\n\n setIsConnecting(true);\n\n eventSource.onopen = () => {\n setOpened(true);\n setIsConnecting(false);\n setError(undefined);\n options?.onOpen?.();\n };\n\n eventSource.onerror = (event) => {\n setOpened(false);\n setIsConnecting(false);\n setIsError(true);\n setError(event);\n options?.onError?.(event);\n\n if (retryCountRef.current > 0) {\n retryCountRef.current -= 1;\n\n const retryDelay =\n typeof options?.retryDelay === 'function'\n ? options?.retryDelay(retryCountRef.current, event)\n : options?.retryDelay;\n\n if (retryDelay) {\n setTimeout(open, retryDelay);\n return;\n }\n\n return open();\n }\n\n retryCountRef.current = options?.retry ? getRetry(options.retry) : 0;\n };\n\n eventSource.onmessage = (event) => {\n const data = options?.select ? options?.select(event.data) : event.data;\n setData(data);\n options?.onMessage?.(event);\n };\n\n events.forEach((eventName) => eventSource.addEventListener(eventName, onEventRef.current));\n };\n\n useEffect(() => {\n if (!immediately) return;\n\n open();\n return () => {\n close();\n };\n }, [immediately]);\n\n return {\n instance: eventSourceRef.current,\n data,\n error,\n isConnecting,\n opened,\n isError,\n close,\n open\n };\n};\n"],"names":["useEventSource","url","events","options","isConnecting","setIsConnecting","useState","opened","setOpened","isError","setIsError","retryCountRef","useRef","getRetry","error","setError","data","setData","eventSourceRef","immediately","onEventRef","event","close","eventName","open","eventSource","retryDelay","useEffect"],"mappings":"uJA4DaA,EAAiB,CAC5BC,EACAC,EAAmB,CAAA,EACnBC,EAAkD,CAAA,IACnB,CAC/B,KAAM,CAACC,EAAcC,CAAe,EAAIC,EAAAA,SAAS,EAAK,EAChD,CAACC,EAAQC,CAAS,EAAIF,EAAAA,SAAS,EAAK,EACpC,CAACG,EAASC,CAAU,EAAIJ,EAAAA,SAAS,EAAK,EAEtCK,EAAgBC,E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AI,CAAA,EAGrEsB,EAAY,UAAaJ,GAAU,CACjC,MAAML,EAAOb,GAAS,OAASA,GAAS,OAAOkB,EAAM,IAAI,EAAIA,EAAM,KACnEJ,EAAQD,CAAI,EACZb,GAAS,YAAYkB,CAAK,CAAA,EAG5BnB,EAAO,QAASqB,GAAcE,EAAY,iBAAiBF,EAAWH,EAAW,OAAO,CAAC,CAAA,EAG3FO,OAAAA,EAAAA,UAAU,IAAM,CACd,GAAKR,EAEL,OAAAK,EAAA,EACO,IAAM,CACXF,EAAA,CAAM,CACR,EACC,CAACH,CAAW,CAAC,EAET,CACL,SAAUD,EAAe,QACzB,KAAAF,EACA,MAAAF,EACA,aAAAV,EACA,OAAAG,EACA,QAAAE,EACA,MAAAa,EACA,KAAAE,CAAA,CAEJ"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("react"),k=require("../useRerender/useRerender.cjs"),V=u=>{const c=u?.initialValue??"",t=i.useRef(null),l=i.useRef(!1),o=k.useRerender(),[v,f]=i.useState(!1),[g,a]=i.useState(u?.initialTouched??!1),[y,r]=i.useState(void 0),h=()=>t.current?.type==="radio"||t.current?.type==="checkbox"?t.current.checked:t.current?.value??c,s=e=>{if(t.current?.type==="radio"||t.current?.type==="checkbox")return t.current.checked=e,l.current?o():void 0;if(t.current.value=e,l.current)return o()},x=()=>{s(c),f(!1),a(!1),r(void 0)},b=()=>t.current.focus(),d=e=>{if(e.required&&!t.current.value)return r(e.required);if(e.minLength&&t.current.value.length<e.minLength.value)return r(e.minLength.message);if(e.maxLength&&t.current.value.length>e.maxLength.value)return r(e.maxLength.message);if(e.min&&Number(t.current.value)<e.min.value)return r(e.min.message);if(e.max&&Number(t.current.value)>e.max.value)return r(e.max.message);if(e.pattern&&!e.pattern.value.test(t.current.value))return r(e.pattern.message);if(e.validate){const n=e.validate(t.current.value);if(typeof n=="string")return r(n)}r(void 0)};return{register:e=>({ref:n=>{if(!t.current&&n){if(u?.autoFocus&&n.focus(),t.current=n,t.current.type==="radio"){t.current.defaultChecked=u?.initialValue===n.value;return}if(t.current.type==="checkbox"){t.current.defaultChecked=!!u?.initialValue;return}t.current.defaultValue=String(c),e&&u?.validateOnMount&&d(e)}},onChange:async()=>{if(l.current)return o();t.current.value!==c&&f(!0),v&&t.current.value===c&&f(!1),e&&u?.validateOnChange&&await d(e),e&&u?.validateOnBlur&&r(void 0)},onBlur:async()=>{e&&u?.validateOnBlur&&await d(e),a(!0)}}),dirty:v,touched:g,error:y,setError:r,clearError:()=>r(void 0),getValue:h,setValue:s,reset:x,watch:()=>(l.current=!0,h()),focus:b}};exports.useField=V;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("react"),k=require("../useRerender/useRerender.cjs"),V=u=>{const c=u?.initialValue??"",t=i.useRef(null),l=i.useRef(!1),o=k.useRerender(),[v,f]=i.useState(!1),[g,a]=i.useState(u?.initialTouched??!1),[y,r]=i.useState(void 0),h=()=>t.current?.type==="radio"||t.current?.type==="checkbox"?t.current.checked:t.current?.value??c,s=e=>{if(t.current?.type==="radio"||t.current?.type==="checkbox")return t.current.checked=e,l.current?o():void 0;if(t.current.value=e,l.current)return o()},x=()=>{s(c),f(!1),a(!1),r(void 0)},b=()=>t.current.focus(),d=e=>{if(e.required&&!t.current.value)return r(e.required);if(e.minLength&&t.current.value.length<e.minLength.value)return r(e.minLength.message);if(e.maxLength&&t.current.value.length>e.maxLength.value)return r(e.maxLength.message);if(e.min&&Number(t.current.value)<e.min.value)return r(e.min.message);if(e.max&&Number(t.current.value)>e.max.value)return r(e.max.message);if(e.pattern&&!e.pattern.value.test(t.current.value))return r(e.pattern.message);if(e.validate){const n=e.validate(t.current.value);if(typeof n=="string")return r(n)}r(void 0)};return{register:e=>({ref:n=>{if(!t.current&&n){if(u?.autoFocus&&n.focus(),t.current=n,t.current.type==="radio"){t.current.defaultChecked=u?.initialValue===n.value;return}if(t.current.type==="checkbox"){t.current.defaultChecked=!!u?.initialValue;return}t.current.defaultValue=String(c),e&&u?.validateOnMount&&d(e)}},onChange:async()=>{if(l.current)return o();t.current.value!==c&&f(!0),v&&t.current.value===c&&f(!1),e&&u?.validateOnChange&&await d(e),e&&u?.validateOnBlur&&r(void 0)},onBlur:async()=>{e&&u?.validateOnBlur&&await d(e),a(!0)}}),dirty:v,touched:g,error:y,setError:r,clearError:()=>r(void 0),getValue:h,setValue:s,reset:x,watch:()=>(l.current=!0,h()),focus:b,ref:t}};exports.useField=V;
|
|
2
2
|
//# sourceMappingURL=useField.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useField.cjs","sources":["../../../../src/hooks/useField/useField.ts"],"sourcesContent":["import { useRef, useState } from 'react';\n\nimport { useRerender } from '../useRerender/useRerender';\n\n/** The use field params type */\nexport interface UseFieldParams<Value> {\n /** The auto focus */\n autoFocus?: boolean;\n /** The initial touched */\n initialTouched?: boolean;\n /** The initial value */\n initialValue?: Value;\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 required validation */\n required?: string;\n /** The custom validation */\n validate?: (value: string) => Promise<string | true>;\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}\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 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 params?: UseFieldParams<Value>\n): UseFieldReturn<Type> => {\n const initialValue = (params?.initialValue ?? '') as Value;\n\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(params?.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 (params?.autoFocus) node.focus();\n inputRef.current = node as HTMLInputElement;\n if (inputRef.current.type === 'radio') {\n inputRef.current.defaultChecked = params?.initialValue === node.value;\n return;\n }\n if (inputRef.current.type === 'checkbox') {\n inputRef.current.defaultChecked = !!params?.initialValue;\n return;\n }\n inputRef.current.defaultValue = String(initialValue);\n\n if (registerParams && params?.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 && params?.validateOnChange) await validate(registerParams);\n if (registerParams && params?.validateOnBlur) setError(undefined);\n },\n onBlur: async () => {\n if (registerParams && params?.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 };\n};\n"],"names":["useField","params","initialValue","inputRef","useRef","watchingRef","rerender","useRerender","dirty","setDirty","useState","touched","setTouched","error","setError","getValue","setValue","value","reset","focus","validate","registerParams","node"],"mappings":"
|
|
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 UseFieldParams<Value> {\n /** The auto focus */\n autoFocus?: boolean;\n /** The initial touched */\n initialTouched?: boolean;\n /** The initial value */\n initialValue?: Value;\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 required validation */\n required?: string;\n /** The custom validation */\n validate?: (value: string) => Promise<string | true>;\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}\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 params?: UseFieldParams<Value>\n): UseFieldReturn<Type> => {\n const initialValue = (params?.initialValue ?? '') as Value;\n\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(params?.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 (params?.autoFocus) node.focus();\n inputRef.current = node as HTMLInputElement;\n if (inputRef.current.type === 'radio') {\n inputRef.current.defaultChecked = params?.initialValue === node.value;\n return;\n }\n if (inputRef.current.type === 'checkbox') {\n inputRef.current.defaultChecked = !!params?.initialValue;\n return;\n }\n inputRef.current.defaultValue = String(initialValue);\n\n if (registerParams && params?.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 && params?.validateOnChange) await validate(registerParams);\n if (registerParams && params?.validateOnBlur) setError(undefined);\n },\n onBlur: async () => {\n if (registerParams && params?.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","params","initialValue","inputRef","useRef","watchingRef","rerender","useRerender","dirty","setDirty","useState","touched","setTouched","error","setError","getValue","setValue","value","reset","focus","validate","registerParams","node"],"mappings":"qJA4GaA,EAIXC,GACyB,CACzB,MAAMC,EAAgBD,GAAQ,cAAgB,GAExCE,EAAWC,EAAAA,OAAgC,IAAI,EAC/CC,EAAcD,EAAAA,OAAO,EAAK,EAC1BE,EAAWC,EAAAA,YAAA,EAEX,CAACC,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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"),T=require("../useRefState/useRefState.cjs"),d=require("../../utils/helpers/isTarget.cjs"),m=400,w=((...t)=>{const e=d.isTarget(t[0])?t[0]:void 0,l=e?t[1]:t[0],v=e?t[2]:t[1],[E,R]=r.useState(!1),n=r.useRef(void 0),f=r.useRef(!1),c=T.useRefState(),L=r.useRef(l);L.current=l;const s=r.useRef(v);return s.current=v,r.useEffect(()=>{if(!e&&!c.state)return;const o=e?d.isTarget.getElement(e):c.current;if(!o)return;const i=u=>{s.current?.onStart?.(u),f.current=!0,n.current=setTimeout(()=>{L.current(u),R(!0)},s.current?.threshold??m)},a=u=>{R(g=>(g?s.current?.onFinish?.(u):f.current&&s.current?.onCancel?.(u),f.current=!1,n.current&&clearTimeout(n.current),!1))};return o.addEventListener("mousedown",i),window.addEventListener("mouseup",a),o.addEventListener("touchstart",i),window.addEventListener("touchend",a),()=>{o.removeEventListener("mousedown",i),window.removeEventListener("mouseup",a),o.removeEventListener("touchstart",i),window.removeEventListener("touchend",a),n.current&&clearTimeout(n.current)}},[e,c.state,d.isTarget.getRefState(e)]),e?E:{ref:c,pressed:E}});exports.useLongPress=w;
|
|
2
2
|
//# sourceMappingURL=useLongPress.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useLongPress.cjs","sources":["../../../../src/hooks/useLongPress/useLongPress.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 LongPressEvents = MouseEvent | TouchEvent;\n\n// * The use long press options type */\nexport interface UseLongPressOptions {\n // * The threshold time in milliseconds\n threshold?: number;\n // * The callback function to be invoked on long press cancel\n onCancel?: (event: LongPressEvents) => void;\n // * The callback function to be invoked on long press end\n onFinish?: (event: LongPressEvents) => void;\n // * The callback function to be invoked on long press start\n onStart?: (event: LongPressEvents) => void;\n}\n\nexport interface UseLongPress {\n (\n target: HookTarget,\n callback: (event: LongPressEvents) => void,\n options?: UseLongPressOptions\n ): boolean;\n\n <Target extends Element>(\n callback: (event: LongPressEvents) => void,\n options?: UseLongPressOptions,\n target?: never\n ): {\n ref: StateRef<Target>;\n pressed: boolean;\n };\n}\n\nconst DEFAULT_THRESHOLD_TIME = 400;\n\n/**\n * @name useLongPress\n * @description - Hook that defines the logic when long pressing an element\n * @category Elements\n * @usage medium\n *\n * @overload\n * @param {HookTarget} target The target element to be long pressed\n * @param {(event: LongPressEvents) => void} callback The callback function to be invoked on long press\n * @param {UseLongPressOptions} [options] The options for the long press\n * @returns {boolean} The long pressing state\n *\n * @example\n * const pressed = useLongPress(ref, () => console.log('callback'));\n *\n * @overload\n * @template Target The target element\n * @param {(event: LongPressEvents) => void} callback The callback function to be invoked on long press\n * @param {UseLongPressOptions} [options] The options for the long press\n * @returns {boolean} The long pressing state\n *\n * @example\n * const { ref, pressed } = useLongPress(() => console.log('callback'));\n */\nexport const useLongPress = ((...params: any[]): any => {\n const target = (isTarget(params[0]) ? params[0] : undefined) as HookTarget | undefined;\n const callback = (target ? params[1] : params[0]) as (event: LongPressEvents) => void;\n const options = (target ? params[2] : params[1]) as UseLongPressOptions | undefined;\n\n const [pressed, setPressed] = useState(false);\n const timeoutIdRef = useRef<ReturnType<typeof setTimeout>>(undefined);\n const isPressedRef = useRef(false);\n const internalRef = useRefState<Element>();\n\n const internalCallbackRef = useRef(callback);\n internalCallbackRef.current = callback;\n const internalOptionsRef = useRef(options);\n internalOptionsRef.current = options;\n\n useEffect(() => {\n if (!target && !internalRef.state) return;\n\n const element = target ? isTarget.getElement(target) : internalRef.current;\n if (!element) return;\n\n const onStart = (event: LongPressEvents) => {\n internalOptionsRef.current?.onStart?.(event);\n\n isPressedRef.current = true;\n timeoutIdRef.current = setTimeout(() => {\n internalCallbackRef.current(event);\n setPressed(true);\n }, internalOptionsRef.current?.threshold ?? DEFAULT_THRESHOLD_TIME);\n };\n\n const onCancel = (event: LongPressEvents) => {\n setPressed((prevPressed) => {\n if (prevPressed) {\n internalOptionsRef.current?.onFinish?.(event);\n } else if (isPressedRef.current) {\n internalOptionsRef.current?.onCancel?.(event);\n }\n\n
|
|
1
|
+
{"version":3,"file":"useLongPress.cjs","sources":["../../../../src/hooks/useLongPress/useLongPress.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 LongPressEvents = MouseEvent | TouchEvent;\n\n// * The use long press options type */\nexport interface UseLongPressOptions {\n // * The threshold time in milliseconds\n threshold?: number;\n // * The callback function to be invoked on long press cancel\n onCancel?: (event: LongPressEvents) => void;\n // * The callback function to be invoked on long press end\n onFinish?: (event: LongPressEvents) => void;\n // * The callback function to be invoked on long press start\n onStart?: (event: LongPressEvents) => void;\n}\n\nexport interface UseLongPress {\n (\n target: HookTarget,\n callback: (event: LongPressEvents) => void,\n options?: UseLongPressOptions\n ): boolean;\n\n <Target extends Element>(\n callback: (event: LongPressEvents) => void,\n options?: UseLongPressOptions,\n target?: never\n ): {\n ref: StateRef<Target>;\n pressed: boolean;\n };\n}\n\nconst DEFAULT_THRESHOLD_TIME = 400;\n\n/**\n * @name useLongPress\n * @description - Hook that defines the logic when long pressing an element\n * @category Elements\n * @usage medium\n *\n * @overload\n * @param {HookTarget} target The target element to be long pressed\n * @param {(event: LongPressEvents) => void} callback The callback function to be invoked on long press\n * @param {UseLongPressOptions} [options] The options for the long press\n * @returns {boolean} The long pressing state\n *\n * @example\n * const pressed = useLongPress(ref, () => console.log('callback'));\n *\n * @overload\n * @template Target The target element\n * @param {(event: LongPressEvents) => void} callback The callback function to be invoked on long press\n * @param {UseLongPressOptions} [options] The options for the long press\n * @returns {boolean} The long pressing state\n *\n * @example\n * const { ref, pressed } = useLongPress(() => console.log('callback'));\n */\nexport const useLongPress = ((...params: any[]): any => {\n const target = (isTarget(params[0]) ? params[0] : undefined) as HookTarget | undefined;\n const callback = (target ? params[1] : params[0]) as (event: LongPressEvents) => void;\n const options = (target ? params[2] : params[1]) as UseLongPressOptions | undefined;\n\n const [pressed, setPressed] = useState(false);\n const timeoutIdRef = useRef<ReturnType<typeof setTimeout>>(undefined);\n const isPressedRef = useRef(false);\n const internalRef = useRefState<Element>();\n\n const internalCallbackRef = useRef(callback);\n internalCallbackRef.current = callback;\n const internalOptionsRef = useRef(options);\n internalOptionsRef.current = options;\n\n useEffect(() => {\n if (!target && !internalRef.state) return;\n\n const element = target ? isTarget.getElement(target) : internalRef.current;\n if (!element) return;\n\n const onStart = (event: LongPressEvents) => {\n internalOptionsRef.current?.onStart?.(event);\n\n isPressedRef.current = true;\n timeoutIdRef.current = setTimeout(() => {\n internalCallbackRef.current(event);\n setPressed(true);\n }, internalOptionsRef.current?.threshold ?? DEFAULT_THRESHOLD_TIME);\n };\n\n const onCancel = (event: LongPressEvents) => {\n setPressed((prevPressed) => {\n if (prevPressed) {\n internalOptionsRef.current?.onFinish?.(event);\n } else if (isPressedRef.current) {\n internalOptionsRef.current?.onCancel?.(event);\n }\n\n isPressedRef.current = false;\n if (timeoutIdRef.current) clearTimeout(timeoutIdRef.current);\n\n return false;\n });\n };\n\n element.addEventListener('mousedown', onStart as EventListener);\n window.addEventListener('mouseup', onCancel as EventListener);\n\n element.addEventListener('touchstart', onStart as EventListener);\n window.addEventListener('touchend', onCancel as EventListener);\n\n return () => {\n element.removeEventListener('mousedown', onStart as EventListener);\n window.removeEventListener('mouseup', onCancel as EventListener);\n\n element.removeEventListener('touchstart', onStart as EventListener);\n window.removeEventListener('touchend', onCancel as EventListener);\n\n if (timeoutIdRef.current) clearTimeout(timeoutIdRef.current);\n };\n }, [target, internalRef.state, isTarget.getRefState(target)]);\n\n if (target) return pressed;\n return {\n ref: internalRef,\n pressed\n };\n}) as UseLongPress;\n"],"names":["DEFAULT_THRESHOLD_TIME","useLongPress","params","target","isTarget","callback","options","pressed","setPressed","useState","timeoutIdRef","useRef","isPressedRef","internalRef","useRefState","internalCallbackRef","internalOptionsRef","useEffect","element","onStart","event","onCancel","prevPressed"],"mappings":"mMAyCMA,EAAyB,IA0BlBC,GAAgB,IAAIC,IAAuB,CACtD,MAAMC,EAAUC,EAAAA,SAASF,EAAO,CAAC,CAAC,EAAIA,EAAO,CAAC,EAAI,OAC5CG,EAAYF,EAASD,EAAO,CAAC,EAAIA,EAAO,CAAC,EACzCI,EAAWH,EAASD,EAAO,CAAC,EAAIA,EAAO,CAAC,EAExC,CAACK,EAASC,CAAU,EAAIC,EAAAA,SAAS,EAAK,EACtCC,EAAeC,EAAAA,OAAsC,MAAS,EAC9DC,EAAeD,EAAAA,OAAO,EAAK,EAC3BE,EAAcC,EAAAA,YAAA,EAEdC,EAAsBJ,EAAAA,OAAON,CAAQ,EAC3CU,EAAoB,QAAUV,EAC9B,MAAMW,EAAqBL,EAAAA,OAAOL,CAAO,EAmDzC,OAlDAU,EAAmB,QAAUV,EAE7BW,EAAAA,UAAU,IAAM,CACd,GAAI,CAACd,GAAU,CAACU,EAAY,MAAO,OAEnC,MAAMK,EAAUf,EAASC,EAAAA,SAAS,WAAWD,CAAM,EAAIU,EAAY,QACnE,GAAI,CAACK,EAAS,OAEd,MAAMC,EAAWC,GAA2B,CAC1CJ,EAAmB,SAAS,UAAUI,CAAK,EAE3CR,EAAa,QAAU,GACvBF,EAAa,QAAU,WAAW,IAAM,CACtCK,EAAoB,QAAQK,CAAK,EACjCZ,EAAW,EAAI,CAAA,EACdQ,EAAmB,SAAS,WAAahB,CAAsB,CAAA,EAG9DqB,EAAYD,GAA2B,CAC3CZ,EAAYc,IACNA,EACFN,EAAmB,SAAS,WAAWI,CAAK,EACnCR,EAAa,SACtBI,EAAmB,SAAS,WAAWI,CAAK,EAG9CR,EAAa,QAAU,GACnBF,EAAa,SAAS,aAAaA,EAAa,OAAO,EAEpD,GACR,CAAA,EAGH,OAAAQ,EAAQ,iBAAiB,YAAaC,CAAwB,EAC9D,OAAO,iBAAiB,UAAWE,CAAyB,EAE5DH,EAAQ,iBAAiB,aAAcC,CAAwB,EAC/D,OAAO,iBAAiB,WAAYE,CAAyB,EAEtD,IAAM,CACXH,EAAQ,oBAAoB,YAAaC,CAAwB,EACjE,OAAO,oBAAoB,UAAWE,CAAyB,EAE/DH,EAAQ,oBAAoB,aAAcC,CAAwB,EAClE,OAAO,oBAAoB,WAAYE,CAAyB,EAE5DX,EAAa,SAAS,aAAaA,EAAa,OAAO,CAAA,CAC7D,EACC,CAACP,EAAQU,EAAY,MAAOT,EAAAA,SAAS,YAAYD,CAAM,CAAC,CAAC,EAExDA,EAAeI,EACZ,CACL,IAAKM,EACL,QAAAN,CAAA,CAEJ"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const c=require("react"),
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const c=require("react"),a=((...e)=>{const n=typeof navigator<"u"&&"OTPCredential"in navigator&&!!navigator.OTPCredential,o=typeof e[0]=="object"?e[0]:{onSuccess:e[0]},t=c.useRef(new AbortController);return{supported:n,abort:()=>{t.current.abort(),t.current=new AbortController},get:async()=>{if(n){t.current=new AbortController;try{const r=await navigator.credentials.get({otp:{transport:["sms"]},signal:t.current.signal});return o.onSuccess?.(r),r}catch(r){o.onError?.(r)}}}}});exports.useOtpCredential=a;
|
|
2
2
|
//# sourceMappingURL=useOtpCredential.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useOtpCredential.cjs","sources":["../../../../src/hooks/useOtpCredential/useOtpCredential.ts"],"sourcesContent":["import { useRef
|
|
1
|
+
{"version":3,"file":"useOtpCredential.cjs","sources":["../../../../src/hooks/useOtpCredential/useOtpCredential.ts"],"sourcesContent":["import { useRef } from 'react';\n\ndeclare global {\n interface OTPOptions {\n readonly transport: string[];\n }\n\n interface CredentialRequestOptions {\n readonly otp: OTPOptions;\n }\n\n interface Credential {\n readonly code: string;\n }\n}\n\n/* The use otp credential callback type */\nexport type UseOtpCredentialCallback = (otp: Credential | null) => void;\n\n/* The use otp credential options type */\nexport interface UseOtpCredentialParams {\n /* The callback function to be invoked on error */\n onError?: (error: any) => void;\n /* The callback function to be invoked on success */\n onSuccess?: (credential: Credential | null) => void;\n}\n\n/* The use otp credential return type */\nexport interface UseOtpCredentialReturn {\n /* The abort function */\n abort: AbortController['abort'];\n /* The supported state of the otp credential */\n supported: boolean;\n /* The get otp credential function */\n get: () => Promise<Credential | null>;\n}\n\nexport interface UseOtpCredential {\n (callback?: UseOtpCredentialCallback): UseOtpCredentialReturn;\n\n (params?: UseOtpCredentialParams): UseOtpCredentialReturn;\n}\n\n/**\n * @name useOtpCredential\n * @description - Hook that creates an otp credential\n * @category Browser\n * @usage low\n *\n * @browserapi navigator.credentials https://developer.mozilla.org/en-US/docs/Web/API/Navigator/credentials\n *\n * @overload\n * @param {UseOtpCredentialCallback} callback The callback function to be invoked\n * @returns {UseOtpCredentialReturn}\n *\n * @example\n * useOtpCredential((credential) => console.log(credential));\n *\n * @overload\n * @param {UseOtpCredentialCallback} params.onSuccess The callback function to be invoked on success\n * @param {UseOtpCredentialCallback} params.onError The callback function to be invoked on error\n * @returns {UseOtpCredentialReturn}\n *\n * @example\n * useOtpCredential({ onSuccess: (credential) => console.log(credential), onError: (error) => console.log(error) });\n */\nexport const useOtpCredential = ((...params: any[]) => {\n const supported =\n typeof navigator !== 'undefined' && 'OTPCredential' in navigator && !!navigator.OTPCredential;\n\n const options =\n typeof params[0] === 'object'\n ? params[0]\n : {\n onSuccess: params[0]\n };\n\n const abortControllerRef = useRef<AbortController>(new AbortController());\n\n const get = async () => {\n if (!supported) return;\n\n abortControllerRef.current = new AbortController();\n try {\n const credential = await navigator.credentials.get({\n otp: { transport: ['sms'] },\n signal: abortControllerRef.current.signal\n });\n options.onSuccess?.(credential);\n\n return credential;\n } catch (error) {\n options.onError?.(error);\n }\n };\n\n const abort = () => {\n abortControllerRef.current.abort();\n abortControllerRef.current = new AbortController();\n };\n\n return { supported, abort, get };\n}) as UseOtpCredential;\n"],"names":["useOtpCredential","params","supported","options","abortControllerRef","useRef","credential","error"],"mappings":"yGAkEaA,GAAoB,IAAIC,IAAkB,CACrD,MAAMC,EACJ,OAAO,UAAc,KAAe,kBAAmB,WAAa,CAAC,CAAC,UAAU,cAE5EC,EACJ,OAAOF,EAAO,CAAC,GAAM,SACjBA,EAAO,CAAC,EACR,CACE,UAAWA,EAAO,CAAC,CAAA,EAGrBG,EAAqBC,EAAAA,OAAwB,IAAI,eAAiB,EAwBxE,MAAO,CAAE,UAAAH,EAAW,MALN,IAAM,CAClBE,EAAmB,QAAQ,MAAA,EAC3BA,EAAmB,QAAU,IAAI,eAAgB,EAGxB,IAtBf,SAAY,CACtB,GAAKF,EAEL,CAAAE,EAAmB,QAAU,IAAI,gBACjC,GAAI,CACF,MAAME,EAAa,MAAM,UAAU,YAAY,IAAI,CACjD,IAAK,CAAE,UAAW,CAAC,KAAK,CAAA,EACxB,OAAQF,EAAmB,QAAQ,MAAA,CACpC,EACD,OAAAD,EAAQ,YAAYG,CAAU,EAEvBA,CAAA,OACAC,EAAO,CACdJ,EAAQ,UAAUI,CAAK,CAAA,EACzB,CAQyB,CAC7B"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("react"),i=()=>window?.SpeechRecognition??window?.webkitSpeechRecognition,
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("react"),i=()=>window?.SpeechRecognition??window?.webkitSpeechRecognition,v=(S={})=>{const c=typeof window<"u"&&!!i(),{continuous:d=!1,interimResults:R=!1,language:a="en-US",grammars:u,maxAlternatives:m=1,onStart:h,onEnd:w,onError:E,onResult:b}=S,[l,s]=n.useState(!1),[x,y]=n.useState(""),[A,T]=n.useState(!1),[j,g]=n.useState(null),[o]=n.useState(()=>{if(!c)return;const r=i(),t=new r;return t.continuous=d,u&&(t.grammars=u),t.interimResults=R,t.lang=a,t.maxAlternatives=m,t.onstart=()=>{s(!0),T(!1),h?.()},t.onerror=e=>{g(e),s(!1),E?.(e)},t.onresult=e=>{const k=e.results[e.resultIndex],{transcript:q}=k[0];s(!1),y(q),g(null),b?.(e)},t.onend=()=>{s(!1),w?.(),t.lang=a},t});n.useEffect(()=>()=>o?.stop(),[]);const p=()=>o?.start(),f=()=>o?.stop();return{supported:c,transcript:x,recognition:o,final:A,listening:l,error:j,start:p,stop:f,toggle:(r=!l)=>{if(r)return p();f()}}};exports.getSpeechRecognition=i;exports.useSpeechRecognition=v;
|
|
2
2
|
//# sourceMappingURL=useSpeechRecognition.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useSpeechRecognition.cjs","sources":["../../../../src/hooks/useSpeechRecognition/useSpeechRecognition.ts"],"sourcesContent":["import { useEffect, useState } from 'react';\n\n/** The use speech recognition hook options type */\ninterface UseSpeechRecognitionOptions {\n /** If true, recognition continues even after pauses in speech. Default is false */\n continuous?: SpeechRecognition['continuous'];\n /** A list of grammar rules */\n grammars?: SpeechRecognition['grammars'];\n /** If true, interim (non-final) results are provided as the user speaks */\n interimResults?: SpeechRecognition['interimResults'];\n /** The language in which recognition should occur. Must be a valid BCP 47 language tag (e.g., \"en-US\", \"ru-RU\") */\n language?: SpeechRecognition['lang'];\n /** The maximum number of alternative transcripts returned for a given recognition result. Must be a positive integer */\n maxAlternatives?: SpeechRecognition['maxAlternatives'];\n /** Callback invoked when speech recognition ends */\n onEnd?: () => void;\n /** Callback invoked when an error occurs during recognition */\n onError?: (error: SpeechRecognitionErrorEvent) => void;\n /** Callback invoked when recognition produces a result */\n onResult?: (event: SpeechRecognitionEvent) => void;\n /** Callback invoked when speech recognition starts */\n onStart?: () => void;\n}\n\n/** The return type of the useSpeechRecognition hook. */\ninterface UseSpeechRecognitionReturn {\n /** The error state */\n error: SpeechRecognitionErrorEvent | null;\n /** The final transcript */\n final: boolean;\n /** Whether the hook is currently listening for speech */\n listening: boolean;\n /** The speech recognition instance */\n recognition
|
|
1
|
+
{"version":3,"file":"useSpeechRecognition.cjs","sources":["../../../../src/hooks/useSpeechRecognition/useSpeechRecognition.ts"],"sourcesContent":["import { useEffect, useState } from 'react';\n\n/** The use speech recognition hook options type */\ninterface UseSpeechRecognitionOptions {\n /** If true, recognition continues even after pauses in speech. Default is false */\n continuous?: SpeechRecognition['continuous'];\n /** A list of grammar rules */\n grammars?: SpeechRecognition['grammars'];\n /** If true, interim (non-final) results are provided as the user speaks */\n interimResults?: SpeechRecognition['interimResults'];\n /** The language in which recognition should occur. Must be a valid BCP 47 language tag (e.g., \"en-US\", \"ru-RU\") */\n language?: SpeechRecognition['lang'];\n /** The maximum number of alternative transcripts returned for a given recognition result. Must be a positive integer */\n maxAlternatives?: SpeechRecognition['maxAlternatives'];\n /** Callback invoked when speech recognition ends */\n onEnd?: () => void;\n /** Callback invoked when an error occurs during recognition */\n onError?: (error: SpeechRecognitionErrorEvent) => void;\n /** Callback invoked when recognition produces a result */\n onResult?: (event: SpeechRecognitionEvent) => void;\n /** Callback invoked when speech recognition starts */\n onStart?: () => void;\n}\n\n/** The return type of the useSpeechRecognition hook. */\ninterface UseSpeechRecognitionReturn {\n /** The error state */\n error: SpeechRecognitionErrorEvent | null;\n /** The final transcript */\n final: boolean;\n /** Whether the hook is currently listening for speech */\n listening: boolean;\n /** The speech recognition instance */\n recognition?: SpeechRecognition;\n /** Whether the current browser supports the Web Speech API */\n supported: boolean;\n /** The current transcript */\n transcript: string;\n /** Begins speech recognition */\n start: () => void;\n /** Ends speech recognition, finalizing results */\n stop: () => void;\n /** Toggles the listening state */\n toggle: (value?: boolean) => void;\n}\n\nexport const getSpeechRecognition = () =>\n window?.SpeechRecognition ?? window?.webkitSpeechRecognition;\n\n/**\n * @name useSpeechRecognition\n * @description - Hook that provides a streamlined interface for incorporating speech-to-text functionality\n * @category Browser\n * @usage low\n *\n * @browserapi window.SpeechRecognition https://developer.mozilla.org/en-US/docs/Web/API/SpeechRecognition\n *\n * @param {boolean} [options.continuous=false] Whether recognition should continue after pauses\n * @param {boolean} [options.interimResults=false] Whether interim results should be provided\n * @param {string} [options.language=\"en-US\"] The language for recognition, as a valid BCP 47 tag\n * @param {number} [options.maxAlternatives=1] The maximum number of alternative transcripts to return\n * @param {SpeechGrammarList} [options.grammars] A list of grammar rules\n * @param {() => void} [options.onStart] Callback invoked when speech recognition starts\n * @param {() => void} [options.onEnd] Callback invoked when speech recognition ends\n * @param {(error: SpeechRecognitionErrorEvent) => void} [options.onError] Callback invoked when an error occurs during recognition\n * @param {(event: SpeechRecognitionEvent) => void} [options.onResult] Callback invoked when recognition produces a result\n * @returns {UseSpeechRecognitionReturn} An object containing the speech recognition functionality\n *\n * @example\n * const { supported, value, recognition, listening, error, start, stop, toggle } = useSpeechRecognition();\n */\nexport const useSpeechRecognition = (\n options: UseSpeechRecognitionOptions = {}\n): UseSpeechRecognitionReturn => {\n const supported = typeof window !== 'undefined' && !!getSpeechRecognition();\n\n const {\n continuous = false,\n interimResults = false,\n language = 'en-US',\n grammars,\n maxAlternatives = 1,\n onStart,\n onEnd,\n onError,\n onResult\n } = options;\n\n const [listening, setListening] = useState(false);\n const [transcript, setTranscript] = useState('');\n const [final, setFinal] = useState(false);\n const [error, setError] = useState<SpeechRecognitionErrorEvent | null>(null);\n const [recognition] = useState<SpeechRecognition | undefined>(() => {\n if (!supported) return undefined;\n\n const SpeechRecognition = getSpeechRecognition();\n const speechRecognition = new SpeechRecognition();\n\n speechRecognition.continuous = continuous;\n if (grammars) speechRecognition.grammars = grammars;\n speechRecognition.interimResults = interimResults;\n speechRecognition.lang = language;\n speechRecognition.maxAlternatives = maxAlternatives;\n\n speechRecognition.onstart = () => {\n setListening(true);\n setFinal(false);\n onStart?.();\n };\n speechRecognition.onerror = (event) => {\n setError(event);\n setListening(false);\n onError?.(event);\n };\n speechRecognition.onresult = (event) => {\n const currentResult = event.results[event.resultIndex];\n const { transcript } = currentResult[0];\n\n setListening(false);\n setTranscript(transcript);\n setError(null);\n onResult?.(event);\n };\n speechRecognition.onend = () => {\n setListening(false);\n onEnd?.();\n speechRecognition.lang = language;\n };\n\n return speechRecognition;\n });\n\n useEffect(() => () => recognition?.stop(), []);\n\n const start = () => recognition?.start();\n const stop = () => recognition?.stop();\n\n const toggle = (value = !listening) => {\n if (value) return start();\n stop();\n };\n\n return {\n supported,\n transcript,\n recognition,\n final,\n listening,\n error,\n start,\n stop,\n toggle\n };\n};\n"],"names":["getSpeechRecognition","useSpeechRecognition","options","supported","continuous","interimResults","language","grammars","maxAlternatives","onStart","onEnd","onError","onResult","listening","setListening","useState","transcript","setTranscript","final","setFinal","error","setError","recognition","SpeechRecognition","speechRecognition","event","currentResult","useEffect","start","stop","value"],"mappings":"yGA8CaA,EAAuB,IAClC,QAAQ,mBAAqB,QAAQ,wBAwB1BC,EAAuB,CAClCC,EAAuC,KACR,CAC/B,MAAMC,EAAY,OAAO,OAAW,KAAe,CAAC,CAACH,EAAA,EAE/C,CACJ,WAAAI,EAAa,GACb,eAAAC,EAAiB,GACjB,SAAAC,EAAW,QACX,SAAAC,EACA,gBAAAC,EAAkB,EAClB,QAAAC,EACA,MAAAC,EACA,QAAAC,EACA,SAAAC,CAAA,EACEV,EAEE,CAACW,EAAWC,CAAY,EAAIC,EAAAA,SAAS,EAAK,EAC1C,CAACC,EAAYC,CAAa,EAAIF,EAAAA,SAAS,EAAE,EACzC,CAACG,EAAOC,CAAQ,EAAIJ,EAAAA,SAAS,EAAK,EAClC,CAACK,EAAOC,CAAQ,EAAIN,EAAAA,SAA6C,IAAI,EACrE,CAACO,CAAW,EAAIP,EAAAA,SAAwC,IAAM,CAClE,GAAI,CAACZ,EAAW,OAEhB,MAAMoB,EAAoBvB,EAAA,EACpBwB,EAAoB,IAAID,EAE9B,OAAAC,EAAkB,WAAapB,EAC3BG,MAA4B,SAAWA,GAC3CiB,EAAkB,eAAiBnB,EACnCmB,EAAkB,KAAOlB,EACzBkB,EAAkB,gBAAkBhB,EAEpCgB,EAAkB,QAAU,IAAM,CAChCV,EAAa,EAAI,EACjBK,EAAS,EAAK,EACdV,IAAA,CAAU,EAEZe,EAAkB,QAAWC,GAAU,CACrCJ,EAASI,CAAK,EACdX,EAAa,EAAK,EAClBH,IAAUc,CAAK,CAAA,EAEjBD,EAAkB,SAAYC,GAAU,CACtC,MAAMC,EAAgBD,EAAM,QAAQA,EAAM,WAAW,EAC/C,CAAE,WAAAT,GAAeU,EAAc,CAAC,EAEtCZ,EAAa,EAAK,EAClBG,EAAcD,CAAU,EACxBK,EAAS,IAAI,EACbT,IAAWa,CAAK,CAAA,EAElBD,EAAkB,MAAQ,IAAM,CAC9BV,EAAa,EAAK,EAClBJ,IAAA,EACAc,EAAkB,KAAOlB,CAAA,EAGpBkB,CAAA,CACR,EAEDG,EAAAA,UAAU,IAAM,IAAML,GAAa,KAAA,EAAQ,CAAA,CAAE,EAE7C,MAAMM,EAAQ,IAAMN,GAAa,MAAA,EAC3BO,EAAO,IAAMP,GAAa,KAAA,EAOhC,MAAO,CACL,UAAAnB,EACA,WAAAa,EACA,YAAAM,EACA,MAAAJ,EACA,UAAAL,EACA,MAAAO,EACA,MAAAQ,EACA,KAAAC,EACA,OAda,CAACC,EAAQ,CAACjB,IAAc,CACrC,GAAIiB,SAAcF,EAAA,EAClBC,EAAA,CAAK,CAYL,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 o=require("react"),v=(h={})=>{const n=typeof window<"u"&&"speechSynthesis"in window&&!!window.speechSynthesis,{text:c="",lang:a="en-US",pitch:l=1,rate:p=1,voice:t=null,volume:w=1}=h,[S,s]=o.useState(!1),[y,i]=o.useState("init"),[g,m]=o.useState(),[r,d]=o.useState(),f=e=>{e.lang=a,e.pitch=l,e.rate=p,e.volume=w,e.voice=t,e.onstart=()=>{s(!0),i("play")},e.onpause=()=>{s(!1),i("pause")},e.onresume=()=>{s(!0),i("play")},e.onend=()=>{s(!1),i("end")},e.onerror=u=>{s(!1),m(u)}};return o.useEffect(()=>{if(!n)return;const e=new SpeechSynthesisUtterance(c);return f(e),d(e),()=>{window.speechSynthesis?.cancel()}},[c,a,l,p,w,t?.default,t?.lang,t?.localService,t?.name,t?.voiceURI]),{supported:n,playing:S,status:y,utterance:r,error:g,stop:()=>{n&&(window.speechSynthesis?.cancel(),s(!1))},toggle:(e=!S)=>{n&&(e?window.speechSynthesis?.resume():window.speechSynthesis?.pause(),s(e))},speak:e=>{if(n){if(e){const u=new SpeechSynthesisUtterance(e);d(u),f(u)}window.speechSynthesis?.cancel(),r&&window.speechSynthesis?.speak(r),s(!0)}},resume:()=>{s(!0),window.speechSynthesis?.resume()},pause:()=>{s(!1),window.speechSynthesis?.pause()}}};exports.useSpeechSynthesis=v;
|
|
2
2
|
//# sourceMappingURL=useSpeechSynthesis.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useSpeechSynthesis.cjs","sources":["../../../../src/hooks/useSpeechSynthesis/useSpeechSynthesis.ts"],"sourcesContent":["import { useEffect,
|
|
1
|
+
{"version":3,"file":"useSpeechSynthesis.cjs","sources":["../../../../src/hooks/useSpeechSynthesis/useSpeechSynthesis.ts"],"sourcesContent":["import { useEffect, useState } from 'react';\n\n/** The use speech synthesis status type */\nexport type UseSpeechSynthesisStatus = 'end' | 'init' | 'pause' | 'play';\n\n/** The use speech synthesis options type */\nexport interface UseSpeechSynthesisOptions {\n /** Language for SpeechSynthesis */\n lang?: string;\n /** Gets and sets the pitch at which the utterance will be spoken at. */\n pitch?: number;\n /** Gets and sets the speed at which the utterance will be spoken at. */\n rate?: number;\n /** The text to be spoken */\n text?: string;\n /** Gets and sets the voice that will be used to speak the utterance. */\n voice?: SpeechSynthesisVoice | null;\n /** Gets and sets the volume that the utterance will be spoken at. */\n volume?: number;\n}\n\n/** The use speech synthesis return type */\nexport interface UseSpeechSynthesisReturn {\n /** Any error that occurred during speech synthesis. */\n error: SpeechSynthesisErrorEvent | undefined;\n /** Indicates if speech is currently playing. */\n playing: boolean;\n /** The current status of speech synthesis. */\n status: UseSpeechSynthesisStatus;\n /** Indicates if the SpeechSynthesis API is supported in the current environment. */\n supported: boolean;\n /** The SpeechSynthesisUtterance instance. */\n utterance: SpeechSynthesisUtterance | undefined;\n /** Function to pause speech synthesis. */\n pause: () => void;\n /** Function to resume speech synthesis. */\n resume: () => void;\n /** Function to start speech synthesis. */\n speak: () => void;\n /** Function to stop speech synthesis. */\n stop: () => void;\n /** Function to toggle between play and pause. */\n toggle: (value?: boolean) => void;\n}\n\n/**\n * @name useSpeechSynthesis\n * @description - Hook that provides speech synthesis functionality\n * @category Browser\n * @usage low\n *\n * @browserapi SpeechSynthesis https://developer.mozilla.org/en-US/docs/Web/API/SpeechSynthesis\n *\n * @params {string} [options.text] - The text to be spoken\n * @params {string} [options.lang] - The language to be spoken\n * @params {number} [options.pitch] - The pitch to be spoken\n * @params {number} [options.rate] - The rate to be spoken\n * @params {SpeechSynthesisVoice} [options.voice] - The voice to be spoken\n * @params {number} [options.volume] - The volume to be spoken\n * @returns {UseSpeechSynthesisReturn} An object containing the speech synthesis state and control methods\n *\n * @example\n * const { supported, playing, status, utterance, error, stop, toggle, speak, resume, pause } = useSpeechSynthesis();\n */\nexport const useSpeechSynthesis = (\n options: UseSpeechSynthesisOptions = {}\n): UseSpeechSynthesisReturn => {\n const supported =\n typeof window !== 'undefined' && 'speechSynthesis' in window && !!window.speechSynthesis;\n\n const { text = '', lang = 'en-US', pitch = 1, rate = 1, voice = null, volume = 1 } = options;\n\n const [playing, setPlaying] = useState(false);\n const [status, setStatus] = useState<UseSpeechSynthesisStatus>('init');\n const [error, setError] = useState<SpeechSynthesisErrorEvent>();\n\n const [utterance, setUtterance] = useState<SpeechSynthesisUtterance>();\n\n const bindSpeechSynthesisUtterance = (speechSynthesisUtterance: SpeechSynthesisUtterance) => {\n speechSynthesisUtterance.lang = lang;\n speechSynthesisUtterance.pitch = pitch;\n speechSynthesisUtterance.rate = rate;\n speechSynthesisUtterance.volume = volume;\n speechSynthesisUtterance.voice = voice;\n\n speechSynthesisUtterance.onstart = () => {\n setPlaying(true);\n setStatus('play');\n };\n\n speechSynthesisUtterance.onpause = () => {\n setPlaying(false);\n setStatus('pause');\n };\n\n speechSynthesisUtterance.onresume = () => {\n setPlaying(true);\n setStatus('play');\n };\n\n speechSynthesisUtterance.onend = () => {\n setPlaying(false);\n setStatus('end');\n };\n\n speechSynthesisUtterance.onerror = (event) => {\n setPlaying(false);\n setError(event);\n };\n };\n\n useEffect(() => {\n if (!supported) return;\n\n const speechSynthesisUtterance = new SpeechSynthesisUtterance(text);\n\n bindSpeechSynthesisUtterance(speechSynthesisUtterance);\n setUtterance(speechSynthesisUtterance);\n\n return () => {\n window.speechSynthesis?.cancel();\n };\n }, [\n text,\n lang,\n pitch,\n rate,\n volume,\n voice?.default,\n voice?.lang,\n voice?.localService,\n voice?.name,\n voice?.voiceURI\n ]);\n\n const speak = (text?: string) => {\n if (!supported) return;\n\n if (text) {\n const utterance = new SpeechSynthesisUtterance(text);\n setUtterance(utterance);\n bindSpeechSynthesisUtterance(utterance);\n }\n\n window.speechSynthesis?.cancel();\n if (utterance) window.speechSynthesis?.speak(utterance);\n setPlaying(true);\n };\n\n const stop = () => {\n if (!supported) return;\n\n window.speechSynthesis?.cancel();\n setPlaying(false);\n };\n\n const toggle = (value = !playing) => {\n if (!supported) return;\n\n if (value) {\n window.speechSynthesis?.resume();\n } else {\n window.speechSynthesis?.pause();\n }\n setPlaying(value);\n };\n\n const resume = () => {\n setPlaying(true);\n window.speechSynthesis?.resume();\n };\n\n const pause = () => {\n setPlaying(false);\n window.speechSynthesis?.pause();\n };\n\n return {\n supported,\n playing,\n status,\n utterance,\n error,\n stop,\n toggle,\n speak,\n resume,\n pause\n };\n};\n"],"names":["useSpeechSynthesis","options","supported","text","lang","pitch","rate","voice","volume","playing","setPlaying","useState","status","setStatus","error","setError","utterance","setUtterance","bindSpeechSynthesisUtterance","speechSynthesisUtterance","event","useEffect","value"],"mappings":"yGAgEaA,EAAqB,CAChCC,EAAqC,KACR,CAC7B,MAAMC,EACJ,OAAO,OAAW,KAAe,oBAAqB,QAAU,CAAC,CAAC,OAAO,gBAErE,CAAE,KAAAC,EAAO,GAAI,KAAAC,EAAO,QAAS,MAAAC,EAAQ,EAAG,KAAAC,EAAO,EAAG,MAAAC,EAAQ,KAAM,OAAAC,EAAS,GAAMP,EAE/E,CAACQ,EAASC,CAAU,EAAIC,EAAAA,SAAS,EAAK,EACtC,CAACC,EAAQC,CAAS,EAAIF,EAAAA,SAAmC,MAAM,EAC/D,CAACG,EAAOC,CAAQ,EAAIJ,WAAA,EAEpB,CAACK,EAAWC,CAAY,EAAIN,WAAA,EAE5BO,EAAgCC,GAAuD,CAC3FA,EAAyB,KAAOf,EAChCe,EAAyB,MAAQd,EACjCc,EAAyB,KAAOb,EAChCa,EAAyB,OAASX,EAClCW,EAAyB,MAAQZ,EAEjCY,EAAyB,QAAU,IAAM,CACvCT,EAAW,EAAI,EACfG,EAAU,MAAM,CAAA,EAGlBM,EAAyB,QAAU,IAAM,CACvCT,EAAW,EAAK,EAChBG,EAAU,OAAO,CAAA,EAGnBM,EAAyB,SAAW,IAAM,CACxCT,EAAW,EAAI,EACfG,EAAU,MAAM,CAAA,EAGlBM,EAAyB,MAAQ,IAAM,CACrCT,EAAW,EAAK,EAChBG,EAAU,KAAK,CAAA,EAGjBM,EAAyB,QAAWC,GAAU,CAC5CV,EAAW,EAAK,EAChBK,EAASK,CAAK,CAAA,CAChB,EAGFC,OAAAA,EAAAA,UAAU,IAAM,CACd,GAAI,CAACnB,EAAW,OAEhB,MAAMiB,EAA2B,IAAI,yBAAyBhB,CAAI,EAElE,OAAAe,EAA6BC,CAAwB,EACrDF,EAAaE,CAAwB,EAE9B,IAAM,CACX,OAAO,iBAAiB,OAAA,CAAO,CACjC,EACC,CACDhB,EACAC,EACAC,EACAC,EACAE,EACAD,GAAO,QACPA,GAAO,KACPA,GAAO,aACPA,GAAO,KACPA,GAAO,QAAA,CACR,EA4CM,CACL,UAAAL,EACA,QAAAO,EACA,OAAAG,EACA,UAAAI,EACA,MAAAF,EACA,KAlCW,IAAM,CACZZ,IAEL,OAAO,iBAAiB,OAAA,EACxBQ,EAAW,EAAK,EAAA,EA+BhB,OA5Ba,CAACY,EAAQ,CAACb,IAAY,CAC9BP,IAEDoB,EACF,OAAO,iBAAiB,OAAA,EAExB,OAAO,iBAAiB,MAAA,EAE1BZ,EAAWY,CAAK,EAAA,EAqBhB,MAlDanB,GAAkB,CAC/B,GAAKD,EAEL,IAAIC,EAAM,CACR,MAAMa,EAAY,IAAI,yBAAyBb,CAAI,EACnDc,EAAaD,CAAS,EACtBE,EAA6BF,CAAS,CAAA,CAGxC,OAAO,iBAAiB,OAAA,EACpBA,GAAW,OAAO,iBAAiB,MAAMA,CAAS,EACtDN,EAAW,EAAI,EAAA,EAwCf,OAnBa,IAAM,CACnBA,EAAW,EAAI,EACf,OAAO,iBAAiB,OAAA,CAAO,EAkB/B,MAfY,IAAM,CAClBA,EAAW,EAAK,EAChB,OAAO,iBAAiB,MAAA,CAAM,CAa9B,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 g=require("react"),a="reactuse-storage",u=t=>window.dispatchEvent(new StorageEvent(a,t)),f=(t,r,n)=>{const o=t.getItem(r);t.setItem(r,n),u({key:r,oldValue:o,newValue:n,storageArea:t})},m=(t,r)=>{const n=t.getItem(r);t.removeItem(r),u({key:r,oldValue:n,newValue:null,storageArea:t})},v=(t,r)=>{const n=t.getItem(r);if(n)return n},z=((t,r)=>{const n=typeof r=="object"&&r&&("serializer"in r||"deserializer"in r||"initialValue"in r||"storage"in r)?r:void 0,o=n?n?.initialValue:r;if(typeof window>"u")return{value:typeof o=="function"?o():o,set:()=>{},remove:()=>{}};const c=e=>n?.serializer?n.serializer(e):typeof e=="string"?e:JSON.stringify(e),i=n?.storage??window?.localStorage,w=e=>f(i,t,c(e)),S=()=>m(i,t),d=e=>{if(n?.deserializer)return n.deserializer(e);if(e!=="undefined")try{return JSON.parse(e)}catch{return e}},[E,V]=g.useState(()=>{const e=v(i,t);if(e===void 0&&o!==void 0){const s=typeof o=="function"?o():o;return f(i,t,c(s)),s}return e?d(e):void 0});return g.useEffect(()=>{const e=s=>{if(s&&s.storageArea!==i||s&&s.key!==t)return;const l=v(i,t);V(l?d(l):void 0)};return window.addEventListener(a,e),window.addEventListener("storage",e,{passive:!0}),()=>{window.removeEventListener(a,e),window.removeEventListener("storage",e)}},[t,i]),{value:E,set:w,remove:S}});exports.STORAGE_EVENT=a;exports.dispatchStorageEvent=u;exports.useStorage=z;
|
|
2
2
|
//# sourceMappingURL=useStorage.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useStorage.cjs","sources":["../../../../src/hooks/useStorage/useStorage.ts"],"sourcesContent":["import { useEffect, useState } from 'react';\n\n/* The use storage initial value type */\nexport type UseStorageInitialValue<Value> = (() => Value) | Value;\n\n/* The use storage options type */\nexport interface UseStorageOptions<Value> {\n /* The initial value of the storage */\n initialValue?: UseStorageInitialValue<Value>;\n /* The storage to be used */\n storage?: Storage;\n /* The deserializer function to be invoked */\n deserializer?: (value: string) => Value;\n /* The serializer function to be invoked */\n serializer?: (value: Value) => string;\n}\n\n/* The use storage return type */\nexport interface UseStorageReturn<Value> {\n /* The value of the storage */\n value: Value;\n /* The error state of the storage */\n remove: () => void;\n /* The loading state of the storage */\n set: (value: Value) => void;\n}\n\nexport interface UseStorage {\n <Value>(key: string, options?: UseStorageOptions<Value>): UseStorageReturn<Value | undefined>;\n\n <Value>(\n key: string,\n initialValue?: UseStorageInitialValue<Value>\n ): UseStorageReturn<Value | undefined>;\n}\n\nexport const STORAGE_EVENT = 'reactuse-storage';\n\nexport const dispatchStorageEvent = (params: Partial<StorageEvent>) =>\n window.dispatchEvent(new StorageEvent(STORAGE_EVENT, params));\n\nconst setStorageItem = (storage: Storage, key: string, value: string) => {\n const oldValue = storage.getItem(key);\n\n storage.setItem(key, value);\n dispatchStorageEvent({\n key,\n oldValue,\n newValue: value,\n storageArea: storage\n });\n};\n\nconst removeStorageItem = (storage: Storage, key: string) => {\n const oldValue = storage.getItem(key);\n\n storage.removeItem(key);\n dispatchStorageEvent({ key, oldValue, newValue: null, storageArea: storage });\n};\n\nconst getStorageItem = (storage: Storage, key: string) => {\n const value = storage.getItem(key);\n if (!value) return undefined;\n return value;\n};\n\n/**\n * @name useStorage\n * @description - Hook that manages storage value\n * @category State\n * @usage high\n *\n * @overload\n * @param {string} key The key of the storage\n * @param {UseStorageInitialValue<Value>} [initialValue] The initial value of the storage\n * @returns {UseStorageReturn<Value>} The value and the set function\n *\n * @overload\n * @param {string} key The key of the storage\n * @param {(value: Value) => string} [params.serializer] The serializer function\n * @param {(value: string) => Value} [params.deserializer] The deserializer function\n * @param {Storage} [params.storage] The storage\n * @param {UseStorageInitialValue<Value>} [params.initialValue] The initial value of the storage\n * @returns {UseStorageReturn<Value>} The value and the set function\n *\n * @example\n * const { value, set, remove } = useStorage('key', 'value');\n */\nexport const useStorage = (<Value>(key: string, params?: any): UseStorageReturn<Value> => {\n const options = (\n typeof params === 'object' &&\n params &&\n ('serializer' in params ||\n 'deserializer' in params ||\n 'initialValue' in params ||\n 'storage' in params)\n ? params\n : undefined\n ) as UseStorageOptions<Value>;\n\n const initialValue = (options ? options?.initialValue : params) as UseStorageInitialValue<Value>;\n\n if (typeof window === 'undefined') {\n const value = typeof initialValue === 'function' ? (initialValue as () => any)() : initialValue;\n return {\n value,\n set: () => {},\n remove: () => {}\n };\n }\n\n const serializer = (value: Value) => {\n if (options?.serializer) return options.serializer(value);\n if (typeof value === 'string') return value;\n return JSON.stringify(value);\n };\n\n const storage = options?.storage ?? window?.localStorage;\n\n const set = (value: Value) => setStorageItem(storage, key, serializer(value));\n const remove = () => removeStorageItem(storage, key);\n\n const deserializer = (value: string) => {\n if (options?.deserializer) return options.deserializer(value);\n if (value === 'undefined') return undefined as unknown as Value;\n\n try {\n return JSON.parse(value) as Value;\n } catch {\n return value as Value;\n }\n };\n\n const [value, setValue] = useState<Value | undefined>(() => {\n const storageValue = getStorageItem(storage, key);\n if (storageValue === undefined && initialValue !== undefined) {\n const value =\n typeof initialValue === 'function' ? (initialValue as () => Value)() : initialValue;\n setStorageItem(storage, key, serializer(value));\n return value;\n }\n return storageValue ? deserializer(storageValue) : undefined;\n });\n\n useEffect(() => {\n const onChange = () => {\n const storageValue = getStorageItem(storage, key);\n setValue(storageValue ? deserializer(storageValue) : undefined);\n };\n window.addEventListener(STORAGE_EVENT, onChange);\n return () => window.removeEventListener(STORAGE_EVENT, onChange);\n }, [key]);\n\n return {\n value: value as Value,\n set,\n remove\n };\n}) as UseStorage;\n"],"names":["STORAGE_EVENT","dispatchStorageEvent","params","setStorageItem","storage","key","value","oldValue","removeStorageItem","getStorageItem","useStorage","options","initialValue","serializer","set","remove","deserializer","setValue","useState","storageValue","useEffect","onChange"],"mappings":"yGAoCaA,EAAgB,mBAEhBC,EAAwBC,GACnC,OAAO,cAAc,IAAI,aAAaF,EAAeE,CAAM,CAAC,EAExDC,EAAiB,CAACC,EAAkBC,EAAaC,IAAkB,CACvE,MAAMC,EAAWH,EAAQ,QAAQC,CAAG,EAEpCD,EAAQ,QAAQC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D,GAAIc,IAAiB,QAAaP,IAAiB,OAAW,CAC5D,MAAMN,EACJ,OAAOM,GAAiB,WAAcA,IAAiCA,EACzE,OAAAT,EAAeC,EAASC,EAAKQ,EAAWP,CAAK,CAAC,EACvCA,CAAA,CAET,OAAOa,EAAeH,EAAaG,CAAY,EAAI,MAAA,CACpD,EAEDC,OAAAA,EAAAA,UAAU,IAAM,CACd,MAAMC,
|
|
1
|
+
{"version":3,"file":"useStorage.cjs","sources":["../../../../src/hooks/useStorage/useStorage.ts"],"sourcesContent":["import { useEffect, useState } from 'react';\n\n/* The use storage initial value type */\nexport type UseStorageInitialValue<Value> = (() => Value) | Value;\n\n/* The use storage options type */\nexport interface UseStorageOptions<Value> {\n /* The initial value of the storage */\n initialValue?: UseStorageInitialValue<Value>;\n /* The storage to be used */\n storage?: Storage;\n /* The deserializer function to be invoked */\n deserializer?: (value: string) => Value;\n /* The serializer function to be invoked */\n serializer?: (value: Value) => string;\n}\n\n/* The use storage return type */\nexport interface UseStorageReturn<Value> {\n /* The value of the storage */\n value: Value;\n /* The error state of the storage */\n remove: () => void;\n /* The loading state of the storage */\n set: (value: Value) => void;\n}\n\nexport interface UseStorage {\n <Value>(key: string, options?: UseStorageOptions<Value>): UseStorageReturn<Value | undefined>;\n\n <Value>(\n key: string,\n initialValue?: UseStorageInitialValue<Value>\n ): UseStorageReturn<Value | undefined>;\n}\n\nexport const STORAGE_EVENT = 'reactuse-storage';\n\nexport const dispatchStorageEvent = (params: Partial<StorageEvent>) =>\n window.dispatchEvent(new StorageEvent(STORAGE_EVENT, params));\n\nconst setStorageItem = (storage: Storage, key: string, value: string) => {\n const oldValue = storage.getItem(key);\n\n storage.setItem(key, value);\n dispatchStorageEvent({\n key,\n oldValue,\n newValue: value,\n storageArea: storage\n });\n};\n\nconst removeStorageItem = (storage: Storage, key: string) => {\n const oldValue = storage.getItem(key);\n\n storage.removeItem(key);\n dispatchStorageEvent({ key, oldValue, newValue: null, storageArea: storage });\n};\n\nconst getStorageItem = (storage: Storage, key: string) => {\n const value = storage.getItem(key);\n if (!value) return undefined;\n return value;\n};\n\n/**\n * @name useStorage\n * @description - Hook that manages storage value\n * @category State\n * @usage high\n *\n * @overload\n * @param {string} key The key of the storage\n * @param {UseStorageInitialValue<Value>} [initialValue] The initial value of the storage\n * @returns {UseStorageReturn<Value>} The value and the set function\n *\n * @overload\n * @param {string} key The key of the storage\n * @param {(value: Value) => string} [params.serializer] The serializer function\n * @param {(value: string) => Value} [params.deserializer] The deserializer function\n * @param {Storage} [params.storage] The storage\n * @param {UseStorageInitialValue<Value>} [params.initialValue] The initial value of the storage\n * @returns {UseStorageReturn<Value>} The value and the set function\n *\n * @example\n * const { value, set, remove } = useStorage('key', 'value');\n */\nexport const useStorage = (<Value>(key: string, params?: any): UseStorageReturn<Value> => {\n const options = (\n typeof params === 'object' &&\n params &&\n ('serializer' in params ||\n 'deserializer' in params ||\n 'initialValue' in params ||\n 'storage' in params)\n ? params\n : undefined\n ) as UseStorageOptions<Value>;\n\n const initialValue = (options ? options?.initialValue : params) as UseStorageInitialValue<Value>;\n\n if (typeof window === 'undefined') {\n const value = typeof initialValue === 'function' ? (initialValue as () => any)() : initialValue;\n return {\n value,\n set: () => {},\n remove: () => {}\n };\n }\n\n const serializer = (value: Value) => {\n if (options?.serializer) return options.serializer(value);\n if (typeof value === 'string') return value;\n return JSON.stringify(value);\n };\n\n const storage = options?.storage ?? window?.localStorage;\n\n const set = (value: Value) => setStorageItem(storage, key, serializer(value));\n const remove = () => removeStorageItem(storage, key);\n\n const deserializer = (value: string) => {\n if (options?.deserializer) return options.deserializer(value);\n if (value === 'undefined') return undefined as unknown as Value;\n\n try {\n return JSON.parse(value) as Value;\n } catch {\n return value as Value;\n }\n };\n\n const [value, setValue] = useState<Value | undefined>(() => {\n const storageValue = getStorageItem(storage, key);\n if (storageValue === undefined && initialValue !== undefined) {\n const value =\n typeof initialValue === 'function' ? (initialValue as () => Value)() : initialValue;\n setStorageItem(storage, key, serializer(value));\n return value;\n }\n return storageValue ? deserializer(storageValue) : undefined;\n });\n\n useEffect(() => {\n const onChange = (event?: StorageEvent) => {\n if (event && event.storageArea !== storage) return;\n if (event && event.key !== key) return;\n\n const storageValue = getStorageItem(storage, key);\n setValue(storageValue ? deserializer(storageValue) : undefined);\n };\n\n window.addEventListener(STORAGE_EVENT, onChange as EventListener);\n window.addEventListener('storage', onChange, { passive: true });\n\n return () => {\n window.removeEventListener(STORAGE_EVENT, onChange as EventListener);\n window.removeEventListener('storage', onChange);\n };\n }, [key, storage]);\n\n return {\n value: value as Value,\n set,\n remove\n };\n}) as UseStorage;\n"],"names":["STORAGE_EVENT","dispatchStorageEvent","params","setStorageItem","storage","key","value","oldValue","removeStorageItem","getStorageItem","useStorage","options","initialValue","serializer","set","remove","deserializer","setValue","useState","storageValue","useEffect","onChange","event"],"mappings":"yGAoCaA,EAAgB,mBAEhBC,EAAwBC,GACnC,OAAO,cAAc,IAAI,aAAaF,EAAeE,CAAM,CAAC,EAExDC,EAAiB,CAACC,EAAkBC,EAAaC,IAAkB,CACvE,MAAMC,EAAWH,EAAQ,QAAQC,CAAG,EAEpCD,EAAQ,QAAQC,EAAKC,CAAK,EAC1BL,EAAqB,CACnB,IAAAI,EACA,SAAAE,EACA,SAAUD,EACV,YAAaF,CAAA,CACd,CACH,EAEMI,EAAoB,CAACJ,EAAkBC,IAAgB,CAC3D,MAAME,EAAWH,EAAQ,QAAQC,CAAG,EAEpCD,EAAQ,WAAWC,CAAG,EACtBJ,EAAqB,CAAE,IAAAI,EAAK,SAAAE,EAAU,SAAU,KAAM,YAAaH,EAAS,CAC9E,EAEMK,EAAiB,CAACL,EAAkBC,IAAgB,CACxD,MAAMC,EAAQF,EAAQ,QAAQC,CAAG,EACjC,GAAKC,EACL,OAAOA,CACT,EAwBaI,GAAc,CAAQL,EAAaH,IAA0C,CACxF,MAAMS,EACJ,OAAOT,GAAW,UAClBA,IACC,eAAgBA,GACf,iBAAkBA,GAClB,iBAAkBA,GAClB,Y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AAM,EAEvD,IAAM,CACX,OAAO,oBAAoBrB,EAAeqB,CAAyB,EACnE,OAAO,oBAAoB,UAAWA,CAAQ,CAAA,CAChD,EACC,CAAChB,EAAKD,CAAO,CAAC,EAEV,CACL,MAAAE,EACA,IAAAQ,EACA,OAAAC,CAAA,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 l=require("react"),R=require("../useRefState/useRefState.cjs"),f=require("../../utils/helpers/isTarget.cjs"),m=((...t)=>{const n=f.isTarget(t[0])?t[0]:void 0,s=n?typeof t[1]=="object"?t[1]:{initialValue:t[1]}:typeof t[0]=="object"?t[0]:{initialValue:t[0]},[h,v]=l.useState(s?.initialValue??""),o=R.useRefState(),c=l.useRef(null),x=l.useRef(0),a=()=>{const e=c.current;if(!e)return;const i=e.style.minHeight,u=e.style.maxHeight;e.style.height="auto",e.style.minHeight="auto",e.style.maxHeight="none";const r=e.scrollHeight;e.style.height=`${r}px`,e.style.minHeight=i,e.style.maxHeight=u,r!==x.current&&s?.onResize?.(),x.current=r},g=e=>{v(e);const i=c.current;i&&(i.value=e,requestAnimationFrame(()=>{a()}))};l.useEffect(()=>{if(!n&&!o.state)return;const e=n?f.isTarget.getElement(n):o.current;if(!e)return;c.current=e,s?.initialValue&&(e.value=s.initialValue),a();const i=r=>{const H=r.target.value;g(H),requestAnimationFrame(()=>{a()})},u=()=>{requestAnimationFrame(()=>{a()})};return e.addEventListener("input",i),e.addEventListener("resize",u),()=>{e.removeEventListener("input",i),e.removeEventListener("resize",u)}},[n,o.state,f.isTarget.getRefState(n)]);const y=()=>v("");return n?{value:h,set:g,clear:y}:{ref:o,value:h,set:g,clear:y}});exports.useTextareaAutosize=m;
|
|
2
2
|
//# sourceMappingURL=useTextareaAutosize.cjs.map
|