@siberiacancode/reactuse 0.3.5 → 0.3.7

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.
Files changed (51) hide show
  1. package/dist/cjs/helpers/createStore/createStore.cjs +1 -1
  2. package/dist/cjs/helpers/createStore/createStore.cjs.map +1 -1
  3. package/dist/cjs/hooks/useBatchedCallback/useBatchedCallback.cjs +2 -0
  4. package/dist/cjs/hooks/useBatchedCallback/useBatchedCallback.cjs.map +1 -0
  5. package/dist/cjs/hooks/useDisclosure/useDisclosure.cjs +1 -1
  6. package/dist/cjs/hooks/useDisclosure/useDisclosure.cjs.map +1 -1
  7. package/dist/cjs/hooks/useEventListener/useEventListener.cjs +1 -1
  8. package/dist/cjs/hooks/useEventListener/useEventListener.cjs.map +1 -1
  9. package/dist/cjs/hooks/useInterval/useInterval.cjs +1 -1
  10. package/dist/cjs/hooks/useInterval/useInterval.cjs.map +1 -1
  11. package/dist/cjs/hooks/useLockScroll/useLockScroll.cjs +1 -1
  12. package/dist/cjs/hooks/useLockScroll/useLockScroll.cjs.map +1 -1
  13. package/dist/cjs/hooks/useMediaControls/useMediaControls.cjs +1 -1
  14. package/dist/cjs/hooks/useMediaControls/useMediaControls.cjs.map +1 -1
  15. package/dist/cjs/hooks/useOtpCredential/useOtpCredential.cjs +1 -1
  16. package/dist/cjs/hooks/useOtpCredential/useOtpCredential.cjs.map +1 -1
  17. package/dist/cjs/hooks/useSpeechRecognition/useSpeechRecognition.cjs +1 -1
  18. package/dist/cjs/hooks/useSpeechRecognition/useSpeechRecognition.cjs.map +1 -1
  19. package/dist/cjs/hooks/useTextareaAutosize/useTextareaAutosize.cjs +1 -1
  20. package/dist/cjs/hooks/useTextareaAutosize/useTextareaAutosize.cjs.map +1 -1
  21. package/dist/cjs/index.cjs +1 -1
  22. package/dist/esm/helpers/createStore/createStore.mjs +10 -9
  23. package/dist/esm/helpers/createStore/createStore.mjs.map +1 -1
  24. package/dist/esm/hooks/useBatchedCallback/useBatchedCallback.mjs +20 -0
  25. package/dist/esm/hooks/useBatchedCallback/useBatchedCallback.mjs.map +1 -0
  26. package/dist/esm/hooks/useDisclosure/useDisclosure.mjs +1 -1
  27. package/dist/esm/hooks/useDisclosure/useDisclosure.mjs.map +1 -1
  28. package/dist/esm/hooks/useEventListener/useEventListener.mjs +8 -8
  29. package/dist/esm/hooks/useEventListener/useEventListener.mjs.map +1 -1
  30. package/dist/esm/hooks/useInterval/useInterval.mjs +6 -6
  31. package/dist/esm/hooks/useInterval/useInterval.mjs.map +1 -1
  32. package/dist/esm/hooks/useLockScroll/useLockScroll.mjs +10 -13
  33. package/dist/esm/hooks/useLockScroll/useLockScroll.mjs.map +1 -1
  34. package/dist/esm/hooks/useMediaControls/useMediaControls.mjs +1 -1
  35. package/dist/esm/hooks/useMediaControls/useMediaControls.mjs.map +1 -1
  36. package/dist/esm/hooks/useOtpCredential/useOtpCredential.mjs +14 -12
  37. package/dist/esm/hooks/useOtpCredential/useOtpCredential.mjs.map +1 -1
  38. package/dist/esm/hooks/useSpeechRecognition/useSpeechRecognition.mjs +6 -11
  39. package/dist/esm/hooks/useSpeechRecognition/useSpeechRecognition.mjs.map +1 -1
  40. package/dist/esm/hooks/useTextareaAutosize/useTextareaAutosize.mjs +36 -41
  41. package/dist/esm/hooks/useTextareaAutosize/useTextareaAutosize.mjs.map +1 -1
  42. package/dist/esm/index.mjs +53 -51
  43. package/dist/esm/index.mjs.map +1 -1
  44. package/dist/types/helpers/createStore/createStore.d.ts +5 -12
  45. package/dist/types/hooks/useBatchedCallback/useBatchedCallback.d.ts +19 -0
  46. package/dist/types/hooks/useLockScroll/useLockScroll.d.ts +1 -1
  47. package/dist/types/hooks/useOtpCredential/useOtpCredential.d.ts +2 -3
  48. package/dist/types/hooks/useSpeechRecognition/useSpeechRecognition.d.ts +1 -1
  49. package/dist/types/hooks/useTextareaAutosize/useTextareaAutosize.d.ts +10 -1
  50. package/dist/types/hooks/utilities.d.ts +1 -0
  51. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"createStore.mjs","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 getInitialState: () => Value;\n getState: () => Value;\n setState: (action: StoreSetAction<Value>) => void;\n subscribe: (listener: StoreListener<Value>) => () => void;\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) => {\n let state: Value;\n const listeners: Set<StoreListener<Value>> = new Set();\n\n const setState: StoreApi<Value>['setState'] = (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 = () => state;\n\n if (typeof createState === 'function') {\n state = (createState as StoreCreator<Value>)(setState, getState);\n } else {\n 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 use: useStore,\n subscribe\n };\n};\n"],"names":["createStore","createState","state","listeners","setState","action","nextState","prevState","listener","subscribe","getState","getInitialState","useStore","selector","useSyncExternalStore"],"mappings":";AAkCO,MAAMA,IAAc,CAAQC,MAA6C;AAC9E,MAAIC;AACJ,QAAMC,wBAA2C,IAAA,GAE3CC,IAAwC,CAACC,MAAkC;AAC/E,UAAMC,IAAY,OAAOD,KAAW,aAAaA,EAAOH,CAAK,IAAIG;AAEjE,QAAI,CAAC,OAAO,GAAGC,GAAWJ,CAAK,GAAG;AAChC,YAAMK,IAAYL;AAClB,MAAAA,IACE,OAAOI,KAAc,YAAYA,MAAc,QAAQ,MAAM,QAAQA,CAAS,IAC1EA,IACA,OAAO,OAAO,CAAA,GAAIJ,GAAOI,CAAS,GAGxCH,EAAU,QAAQ,CAACK,MAAaA,EAASN,GAAOK,CAAS,CAAC;AAAA,IAAA;AAAA,EAC5D,GAGIE,IAAY,CAACD,OACjBL,EAAU,IAAIK,CAAQ,GAEf,MAAML,EAAU,OAAOK,CAAQ,IAGlCE,IAAW,MAAMR,GACjBS,IAAkB,MAAMT;AAE9B,EAAI,OAAOD,KAAgB,aACzBC,IAASD,EAAoCG,GAAUM,CAAQ,IAE/DR,IAAQD;AAKV,WAASW,EAAmBC,GAAyD;AACnF,WAAOC;AAAA,MACLL;AAAA,MACA,MAAOI,IAAWA,EAASH,EAAA,CAAU,IAAIA,EAAA;AAAA,MACzC,MAAOG,IAAWA,EAASF,EAAA,CAAiB,IAAIA,EAAA;AAAA,IAAgB;AAAA,EAClE;AAGF,SAAO;AAAA,IACL,KAAKP;AAAA,IACL,KAAKM;AAAA,IACL,KAAKE;AAAA,IACL,WAAAH;AAAA,EAAA;AAEJ;"}
1
+ {"version":3,"file":"createStore.mjs","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":";AAsCO,MAAMA,IAAc,CAAQC,MAA8D;AAC/F,MAAIC,GACAC;AACJ,QAAMC,wBAA2C,IAAA,GAE3CC,IAAmC,CAACC,MAAkC;AAC1E,UAAMC,IAAY,OAAOD,KAAW,aAAaA,EAAOJ,CAAK,IAAII;AAEjE,QAAI,CAAC,OAAO,GAAGC,GAAWL,CAAK,GAAG;AAChC,YAAMM,IAAYN;AAClB,MAAAA,IACE,OAAOK,KAAc,YAAYA,MAAc,QAAQ,MAAM,QAAQA,CAAS,IAC1EA,IACA,OAAO,OAAO,CAAA,GAAIL,GAAOK,CAAS,GAGxCH,EAAU,QAAQ,CAACK,MAAaA,EAASP,GAAOM,CAAS,CAAC;AAAA,IAAA;AAAA,EAC5D,GAGIE,IAAY,CAACD,OACjBL,EAAU,IAAIK,CAAQ,GAEf,MAAML,EAAU,OAAOK,CAAQ,IAGlCE,IAAW,MAAMT,GACjBU,IAAkB,MAAMT;AAE9B,EAAI,OAAOF,KAAgB,aACzBE,IAAeD,IAASD,EAAoCI,GAAUM,CAAQ,IAE9ER,IAAeD,IAAQD;AAKzB,WAASY,EAAmBC,GAAyD;AACnF,WAAOC;AAAA,MACLL;AAAA,MACA,MAAOI,IAAWA,EAASH,EAAA,CAAU,IAAIA,EAAA;AAAA,MACzC,MAAOG,IAAWA,EAASF,EAAA,CAAiB,IAAIA,EAAA;AAAA,IAAgB;AAAA,EAClE;AAGF,SAAO;AAAA,IACL,KAAKP;AAAA,IACL,KAAKM;AAAA,IACL,YAAYC;AAAA,IACZ,KAAKC;AAAA,IACL,WAAAH;AAAA,EAAA;AAEJ;"}
@@ -0,0 +1,20 @@
1
+ import { useRef as r, useMemo as h } from "react";
2
+ const b = (c, n) => {
3
+ const u = r(c), s = r(n), e = r([]);
4
+ u.current = c, s.current = n;
5
+ const o = () => {
6
+ if (!e.current.length) return;
7
+ const t = e.current;
8
+ e.current = [], u.current(t);
9
+ };
10
+ return h(() => {
11
+ const t = (...a) => {
12
+ e.current.push(a), e.current.length >= s.current && o();
13
+ };
14
+ return t.flush = o, t.cancel = () => e.current = [], t;
15
+ }, []);
16
+ };
17
+ export {
18
+ b as useBatchedCallback
19
+ };
20
+ //# sourceMappingURL=useBatchedCallback.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useBatchedCallback.mjs","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":";AAqBO,MAAMA,IAAqB,CAChCC,GACAC,MAC4B;AAC5B,QAAMC,IAAcC,EAAOH,CAAQ,GAC7BI,IAAUD,EAAOF,CAAI,GACrBI,IAAWF,EAAiB,EAAE;AAEpC,EAAAD,EAAY,UAAUF,GACtBI,EAAQ,UAAUH;AAElB,QAAMK,IAAQ,MAAM;AAClB,QAAI,CAACD,EAAS,QAAQ,OAAQ;AAC9B,UAAME,IAAQF,EAAS;AACvB,IAAAA,EAAS,UAAU,CAAA,GACnBH,EAAY,QAAQK,CAAK;AAAA,EAAA;AAe3B,SAZgBC,EAAQ,MAAM;AAC5B,UAAMC,IAAkB,IAAIC,MAAiB;AAC3C,MAAAL,EAAS,QAAQ,KAAKK,CAAI,GACtBL,EAAS,QAAQ,UAAUD,EAAQ,WAASE,EAAA;AAAA,IAAM;AAGxD,WAAAG,EAAgB,QAAQH,GACxBG,EAAgB,SAAS,MAAOJ,EAAS,UAAU,CAAA,GAE5CI;AAAA,EAAA,GACN,EAAE;AAGP;"}
@@ -1,7 +1,7 @@
1
1
  import { useState as c } from "react";
2
2
  const g = (u = !1, t) => {
3
3
  const [r, n] = c(u), o = () => n((e) => e || (t?.onOpen?.(), !0)), s = () => n((e) => e && (t?.onClose?.(), !1));
4
- return { opened: r, open: o, close: s, toggle: () => r ? s() : o() };
4
+ return { opened: r, open: o, close: s, toggle: (e = !r) => e ? o() : s() };
5
5
  };
6
6
  export {
7
7
  g as useDisclosure
@@ -1 +1 @@
1
- {"version":3,"file":"useDisclosure.mjs","sources":["../../../../src/hooks/useDisclosure/useDisclosure.ts"],"sourcesContent":["import { useState } from 'react';\n\n/** The use disclosure options type */\nexport interface UseDisclosureOptions {\n /** The callback function to be invoked on close */\n onClose?: () => void;\n /** The callback function to be invoked on open */\n onOpen?: () => void;\n}\n\n/** The use disclosure return type */\nexport interface UseDisclosureReturn {\n /** The opened value */\n opened: boolean;\n /** Function to close the modal */\n close: () => void;\n /** Function to open the modal */\n open: () => void;\n /** Function to toggle the modal */\n toggle: () => void;\n}\n\n/**\n * @name useDisclosure\n * @description - Hook that allows you to open and close a modal\n * @category State\n * @usage necessary\n\n * @param {boolean} [initialValue=false] The initial value of the component\n * @param {() => void} [options.onOpen] The callback function to be invoked on open\n * @param {() => void} [options.onClose] The callback function to be invoked on close\n * @returns {UseDisclosureReturn} An object with the opened, open, close, and toggle properties\n *\n * @example\n * const { opened, open, close, toggle } = useDisclosure();\n */\nexport const useDisclosure = (\n initialValue = false,\n options?: UseDisclosureOptions\n): UseDisclosureReturn => {\n const [opened, setOpened] = useState(initialValue);\n\n const open = () =>\n setOpened((opened) => {\n if (!opened) {\n options?.onOpen?.();\n return true;\n }\n return opened;\n });\n\n const close = () =>\n setOpened((opened) => {\n if (opened) {\n options?.onClose?.();\n return false;\n }\n return opened;\n });\n\n const toggle = () => (opened ? close() : open());\n\n return { opened, open, close, toggle };\n};\n"],"names":["useDisclosure","initialValue","options","opened","setOpened","useState","open","close"],"mappings":";AAoCO,MAAMA,IAAgB,CAC3BC,IAAe,IACfC,MACwB;AACxB,QAAM,CAACC,GAAQC,CAAS,IAAIC,EAASJ,CAAY,GAE3CK,IAAO,MACXF,EAAU,CAACD,MACJA,MACHD,GAAS,SAAA,GACF,GAGV,GAEGK,IAAQ,MACZH,EAAU,CAACD,MACLA,MACFD,GAAS,UAAA,GACF,GAGV;AAIH,SAAO,EAAE,QAAAC,GAAQ,MAAAG,GAAM,OAAAC,GAAO,QAFf,MAAOJ,IAASI,EAAA,IAAUD,EAAA,EAEX;AAChC;"}
1
+ {"version":3,"file":"useDisclosure.mjs","sources":["../../../../src/hooks/useDisclosure/useDisclosure.ts"],"sourcesContent":["import { useState } from 'react';\n\n/** The use disclosure options type */\nexport interface UseDisclosureOptions {\n /** The callback function to be invoked on close */\n onClose?: () => void;\n /** The callback function to be invoked on open */\n onOpen?: () => void;\n}\n\n/** The use disclosure return type */\nexport interface UseDisclosureReturn {\n /** The opened value */\n opened: boolean;\n /** Function to close the modal */\n close: () => void;\n /** Function to open the modal */\n open: () => void;\n /** Function to toggle the modal */\n toggle: () => void;\n}\n\n/**\n * @name useDisclosure\n * @description - Hook that allows you to open and close a modal\n * @category State\n * @usage necessary\n\n * @param {boolean} [initialValue=false] The initial value of the component\n * @param {() => void} [options.onOpen] The callback function to be invoked on open\n * @param {() => void} [options.onClose] The callback function to be invoked on close\n * @returns {UseDisclosureReturn} An object with the opened, open, close, and toggle properties\n *\n * @example\n * const { opened, open, close, toggle } = useDisclosure();\n */\nexport const useDisclosure = (\n initialValue = false,\n options?: UseDisclosureOptions\n): UseDisclosureReturn => {\n const [opened, setOpened] = useState(initialValue);\n\n const open = () =>\n setOpened((opened) => {\n if (!opened) {\n options?.onOpen?.();\n return true;\n }\n return opened;\n });\n\n const close = () =>\n setOpened((opened) => {\n if (opened) {\n options?.onClose?.();\n return false;\n }\n return opened;\n });\n\n const toggle = (value = !opened) => (value ? open() : close());\n\n return { opened, open, close, toggle };\n};\n"],"names":["useDisclosure","initialValue","options","opened","setOpened","useState","open","close","value"],"mappings":";AAoCO,MAAMA,IAAgB,CAC3BC,IAAe,IACfC,MACwB;AACxB,QAAM,CAACC,GAAQC,CAAS,IAAIC,EAASJ,CAAY,GAE3CK,IAAO,MACXF,EAAU,CAACD,MACJA,MACHD,GAAS,SAAA,GACF,GAGV,GAEGK,IAAQ,MACZH,EAAU,CAACD,MACLA,MACFD,GAAS,UAAA,GACF,GAGV;AAIH,SAAO,EAAE,QAAAC,GAAQ,MAAAG,GAAM,OAAAC,GAAO,QAFf,CAACC,IAAQ,CAACL,MAAYK,IAAQF,EAAA,IAASC,EAAA,EAExB;AAChC;"}
@@ -1,18 +1,18 @@
1
1
  import { useRef as d, useEffect as E } from "react";
2
2
  import { useRefState as g } from "../useRefState/useRefState.mjs";
3
3
  import { isTarget as i } from "../../utils/helpers/isTarget.mjs";
4
- const w = ((...t) => {
5
- const e = i(t[0]) ? t[0] : void 0, o = e ? t[1] : t[0], s = e ? t[2] : t[1], n = e ? t[3] : t[2], c = n?.enabled ?? !0, r = g(), f = d(s);
4
+ const w = ((...e) => {
5
+ const t = i(e[0]) ? e[0] : void 0, r = t ? e[1] : e[0], s = t ? e[2] : e[1], n = t ? e[3] : e[2], c = n?.enabled ?? !0, o = g(), f = d(s);
6
6
  f.current = s;
7
7
  const v = d(n);
8
8
  if (v.current = n, E(() => {
9
- if (!c || !e && !r.state) return;
10
- const u = (e ? i.getElement(e) : r.current) ?? window, l = (R) => f.current(R);
11
- return u.addEventListener(o, l, n), () => {
12
- u.removeEventListener(o, l, n);
9
+ if (!c) return;
10
+ const u = (t ? i.getElement(t) : o.current) ?? window, l = (R) => f.current(R);
11
+ return u.addEventListener(r, l, n), () => {
12
+ u.removeEventListener(r, l, n);
13
13
  };
14
- }, [e, r.state, i.getRefState(e), o, c]), !e)
15
- return r;
14
+ }, [t, o.state, i.getRefState(t), r, c]), !t)
15
+ return o;
16
16
  });
17
17
  export {
18
18
  w as useEventListener
@@ -1 +1 @@
1
- {"version":3,"file":"useEventListener.mjs","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 || (!target && !internalRef.state)) 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":";;;AA6GO,MAAMA,KAAoB,IAAIC,MAAkB;AACrD,QAAMC,IAAUC,EAASF,EAAO,CAAC,CAAC,IAAIA,EAAO,CAAC,IAAI,QAC5CG,IAASF,IAASD,EAAO,CAAC,IAAIA,EAAO,CAAC,GACtCI,IAAYH,IAASD,EAAO,CAAC,IAAIA,EAAO,CAAC,GACzCK,IAAWJ,IAASD,EAAO,CAAC,IAAIA,EAAO,CAAC,GAExCM,IAAUD,GAAS,WAAW,IAE9BE,IAAcC,EAAA,GACdC,IAAsBC,EAAON,CAAQ;AAC3C,EAAAK,EAAoB,UAAUL;AAC9B,QAAMO,IAAqBD,EAAOL,CAAO;AAiBzC,MAhBAM,EAAmB,UAAUN,GAE7BO,EAAU,MAAM;AACd,QAAI,CAACN,KAAY,CAACL,KAAU,CAACM,EAAY,MAAQ;AAEjD,UAAMM,KACFZ,IAASC,EAAS,WAAWD,CAAM,IAAIM,EAAY,YAAwB,QAEzEH,IAAW,CAACD,MAAiBM,EAAoB,QAAQN,CAAK;AAEpE,WAAAU,EAAQ,iBAAiBV,GAAOC,GAAUC,CAAO,GAC1C,MAAM;AACX,MAAAQ,EAAQ,oBAAoBV,GAAOC,GAAUC,CAAO;AAAA,IAAA;AAAA,EACtD,GACC,CAACJ,GAAQM,EAAY,OAAOL,EAAS,YAAYD,CAAM,GAAGE,GAAOG,CAAO,CAAC,GAExE,CAAAL;AACJ,WAAOM;AACT;"}
1
+ {"version":3,"file":"useEventListener.mjs","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":";;;AA6GO,MAAMA,KAAoB,IAAIC,MAAkB;AACrD,QAAMC,IAAUC,EAASF,EAAO,CAAC,CAAC,IAAIA,EAAO,CAAC,IAAI,QAC5CG,IAASF,IAASD,EAAO,CAAC,IAAIA,EAAO,CAAC,GACtCI,IAAYH,IAASD,EAAO,CAAC,IAAIA,EAAO,CAAC,GACzCK,IAAWJ,IAASD,EAAO,CAAC,IAAIA,EAAO,CAAC,GAExCM,IAAUD,GAAS,WAAW,IAE9BE,IAAcC,EAAA,GACdC,IAAsBC,EAAON,CAAQ;AAC3C,EAAAK,EAAoB,UAAUL;AAC9B,QAAMO,IAAqBD,EAAOL,CAAO;AAiBzC,MAhBAM,EAAmB,UAAUN,GAE7BO,EAAU,MAAM;AACd,QAAI,CAACN,EAAS;AAEd,UAAMO,KACFZ,IAASC,EAAS,WAAWD,CAAM,IAAIM,EAAY,YAAwB,QAEzEH,IAAW,CAACD,MAAiBM,EAAoB,QAAQN,CAAK;AAEpE,WAAAU,EAAQ,iBAAiBV,GAAOC,GAAUC,CAAO,GAC1C,MAAM;AACX,MAAAQ,EAAQ,oBAAoBV,GAAOC,GAAUC,CAAO;AAAA,IAAA;AAAA,EACtD,GACC,CAACJ,GAAQM,EAAY,OAAOL,EAAS,YAAYD,CAAM,GAAGE,GAAOG,CAAO,CAAC,GAExE,CAAAL;AACJ,WAAOM;AACT;"}
@@ -1,7 +1,7 @@
1
- import { useState as i, useRef as s, useEffect as f } from "react";
2
- const y = ((...e) => {
3
- const o = e[0], n = (typeof e[1] == "number" ? e[1] : e[1].interval) ?? 1e3, l = (typeof e[1] == "object" ? e[1] : e[2])?.immediately ?? !0, [t, r] = i(l ?? !0), c = s(void 0), u = s(o);
4
- return u.current = o, f(() => {
1
+ import { useState as f, useRef as s, useEffect as v } from "react";
2
+ const I = ((...e) => {
3
+ const o = e[0], n = (typeof e[1] == "number" ? e[1] : e[1].interval) ?? 1e3, l = (typeof e[1] == "object" ? e[1] : e[2])?.immediately ?? !0, [t, r] = f(l ?? !0), c = s(void 0), u = s(o);
4
+ return u.current = o, v(() => {
5
5
  if (t)
6
6
  return c.current = setInterval(() => u.current(), n), () => {
7
7
  clearInterval(c.current);
@@ -12,10 +12,10 @@ const y = ((...e) => {
12
12
  resume: () => {
13
13
  n <= 0 || r(!0);
14
14
  },
15
- toggle: () => r(!t)
15
+ toggle: (i = !t) => r(i)
16
16
  };
17
17
  });
18
18
  export {
19
- y as useInterval
19
+ I as useInterval
20
20
  };
21
21
  //# sourceMappingURL=useInterval.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"useInterval.mjs","sources":["../../../../src/hooks/useInterval/useInterval.ts"],"sourcesContent":["import { useEffect, useRef, useState } from 'react';\n\n/** The use interval options */\nexport interface UseIntervalOptions {\n /** Start the interval immediately */\n immediately?: boolean;\n}\n\n/** The use interval return type */\nexport interface UseIntervalReturn {\n /** Is the interval active */\n active: boolean;\n /** Pause the interval */\n pause: () => void;\n /** Resume the interval */\n resume: () => void;\n /** Toggle the interval */\n toggle: () => void;\n}\n\ninterface UseInterval {\n (callback: () => void, interval?: number, options?: UseIntervalOptions): UseIntervalReturn;\n\n (callback: () => void, options?: UseIntervalOptions & { interval?: number }): UseIntervalReturn;\n}\n\n/**\n * @name useInterval\n * @description - Hook that makes and interval and returns controlling functions\n * @category Time\n * @usage high\n *\n * @overload\n * @param {() => void} callback Any callback function\n * @param {number} [interval=1000] Time in milliseconds\n * @param {boolean} [options.immediately=true] Start the interval immediately\n * @returns {UseIntervalReturn}\n *\n * @example\n * const { active, pause, resume, toggle } = useInterval(() => console.log('inside interval'), 2500);\n *\n * @overload\n * @param {() => void} callback Any callback function\n * @param {number} [options.interval=1000] Time in milliseconds\n * @param {boolean} [options.immediately=true] Start the interval immediately\n *\n * @example\n * const { active, pause, resume, toggle } = useInterval(() => console.log('inside interval'), { interval: 2500 });\n */\nexport const useInterval = ((...params: any[]): UseIntervalReturn => {\n const callback = params[0] as () => void;\n const interval =\n ((typeof params[1] === 'number'\n ? params[1]\n : (params[1] as UseIntervalOptions & { interval?: number }).interval) as number) ?? 1000;\n const options =\n typeof params[1] === 'object'\n ? (params[1] as (UseIntervalOptions & { interval?: number }) | undefined)\n : (params[2] as UseIntervalOptions | undefined);\n const immediately = options?.immediately ?? true;\n\n const [active, setActive] = useState<boolean>(immediately ?? true);\n\n const intervalIdRef = useRef<ReturnType<typeof setInterval>>(undefined);\n const internalCallbackRef = useRef(callback);\n internalCallbackRef.current = callback;\n\n useEffect(() => {\n if (!active) return;\n\n intervalIdRef.current = setInterval(() => internalCallbackRef.current(), interval);\n return () => {\n clearInterval(intervalIdRef.current);\n };\n }, [active, interval]);\n\n const pause = () => setActive(false);\n\n const resume = () => {\n if (interval <= 0) return;\n setActive(true);\n };\n\n const toggle = () => setActive(!active);\n\n return {\n active,\n pause,\n resume,\n toggle\n };\n}) as UseInterval;\n"],"names":["useInterval","params","callback","interval","immediately","active","setActive","useState","intervalIdRef","useRef","internalCallbackRef","useEffect"],"mappings":";AAiDO,MAAMA,KAAe,IAAIC,MAAqC;AACnE,QAAMC,IAAWD,EAAO,CAAC,GACnBE,KACF,OAAOF,EAAO,CAAC,KAAM,WACnBA,EAAO,CAAC,IACPA,EAAO,CAAC,EAAiD,aAAwB,KAKlFG,KAHJ,OAAOH,EAAO,CAAC,KAAM,WAChBA,EAAO,CAAC,IACRA,EAAO,CAAC,IACc,eAAe,IAEtC,CAACI,GAAQC,CAAS,IAAIC,EAAkBH,KAAe,EAAI,GAE3DI,IAAgBC,EAAuC,MAAS,GAChEC,IAAsBD,EAAOP,CAAQ;AAC3C,SAAAQ,EAAoB,UAAUR,GAE9BS,EAAU,MAAM;AACd,QAAKN;AAEL,aAAAG,EAAc,UAAU,YAAY,MAAME,EAAoB,QAAA,GAAWP,CAAQ,GAC1E,MAAM;AACX,sBAAcK,EAAc,OAAO;AAAA,MAAA;AAAA,EACrC,GACC,CAACH,GAAQF,CAAQ,CAAC,GAWd;AAAA,IACL,QAAAE;AAAA,IACA,OAXY,MAAMC,EAAU,EAAK;AAAA,IAYjC,QAVa,MAAM;AACnB,MAAIH,KAAY,KAChBG,EAAU,EAAI;AAAA,IAAA;AAAA,IASd,QANa,MAAMA,EAAU,CAACD,CAAM;AAAA,EAMpC;AAEJ;"}
1
+ {"version":3,"file":"useInterval.mjs","sources":["../../../../src/hooks/useInterval/useInterval.ts"],"sourcesContent":["import { useEffect, useRef, useState } from 'react';\n\n/** The use interval options */\nexport interface UseIntervalOptions {\n /** Start the interval immediately */\n immediately?: boolean;\n}\n\n/** The use interval return type */\nexport interface UseIntervalReturn {\n /** Is the interval active */\n active: boolean;\n /** Pause the interval */\n pause: () => void;\n /** Resume the interval */\n resume: () => void;\n /** Toggle the interval */\n toggle: () => void;\n}\n\ninterface UseInterval {\n (callback: () => void, interval?: number, options?: UseIntervalOptions): UseIntervalReturn;\n\n (callback: () => void, options?: UseIntervalOptions & { interval?: number }): UseIntervalReturn;\n}\n\n/**\n * @name useInterval\n * @description - Hook that makes and interval and returns controlling functions\n * @category Time\n * @usage high\n *\n * @overload\n * @param {() => void} callback Any callback function\n * @param {number} [interval=1000] Time in milliseconds\n * @param {boolean} [options.immediately=true] Start the interval immediately\n * @returns {UseIntervalReturn}\n *\n * @example\n * const { active, pause, resume, toggle } = useInterval(() => console.log('inside interval'), 2500);\n *\n * @overload\n * @param {() => void} callback Any callback function\n * @param {number} [options.interval=1000] Time in milliseconds\n * @param {boolean} [options.immediately=true] Start the interval immediately\n *\n * @example\n * const { active, pause, resume, toggle } = useInterval(() => console.log('inside interval'), { interval: 2500 });\n */\nexport const useInterval = ((...params: any[]): UseIntervalReturn => {\n const callback = params[0] as () => void;\n const interval =\n ((typeof params[1] === 'number'\n ? params[1]\n : (params[1] as UseIntervalOptions & { interval?: number }).interval) as number) ?? 1000;\n const options =\n typeof params[1] === 'object'\n ? (params[1] as (UseIntervalOptions & { interval?: number }) | undefined)\n : (params[2] as UseIntervalOptions | undefined);\n const immediately = options?.immediately ?? true;\n\n const [active, setActive] = useState<boolean>(immediately ?? true);\n\n const intervalIdRef = useRef<ReturnType<typeof setInterval>>(undefined);\n const internalCallbackRef = useRef(callback);\n internalCallbackRef.current = callback;\n\n useEffect(() => {\n if (!active) return;\n\n intervalIdRef.current = setInterval(() => internalCallbackRef.current(), interval);\n return () => {\n clearInterval(intervalIdRef.current);\n };\n }, [active, interval]);\n\n const pause = () => setActive(false);\n\n const resume = () => {\n if (interval <= 0) return;\n setActive(true);\n };\n\n const toggle = (value = !active) => setActive(value);\n\n return {\n active,\n pause,\n resume,\n toggle\n };\n}) as UseInterval;\n"],"names":["useInterval","params","callback","interval","immediately","active","setActive","useState","intervalIdRef","useRef","internalCallbackRef","useEffect","value"],"mappings":";AAiDO,MAAMA,KAAe,IAAIC,MAAqC;AACnE,QAAMC,IAAWD,EAAO,CAAC,GACnBE,KACF,OAAOF,EAAO,CAAC,KAAM,WACnBA,EAAO,CAAC,IACPA,EAAO,CAAC,EAAiD,aAAwB,KAKlFG,KAHJ,OAAOH,EAAO,CAAC,KAAM,WAChBA,EAAO,CAAC,IACRA,EAAO,CAAC,IACc,eAAe,IAEtC,CAACI,GAAQC,CAAS,IAAIC,EAAkBH,KAAe,EAAI,GAE3DI,IAAgBC,EAAuC,MAAS,GAChEC,IAAsBD,EAAOP,CAAQ;AAC3C,SAAAQ,EAAoB,UAAUR,GAE9BS,EAAU,MAAM;AACd,QAAKN;AAEL,aAAAG,EAAc,UAAU,YAAY,MAAME,EAAoB,QAAA,GAAWP,CAAQ,GAC1E,MAAM;AACX,sBAAcK,EAAc,OAAO;AAAA,MAAA;AAAA,EACrC,GACC,CAACH,GAAQF,CAAQ,CAAC,GAWd;AAAA,IACL,QAAAE;AAAA,IACA,OAXY,MAAMC,EAAU,EAAK;AAAA,IAYjC,QAVa,MAAM;AACnB,MAAIH,KAAY,KAChBG,EAAU,EAAI;AAAA,IAAA;AAAA,IASd,QANa,CAACM,IAAQ,CAACP,MAAWC,EAAUM,CAAK;AAAA,EAMjD;AAEJ;"}
@@ -2,17 +2,17 @@ import { useState as w, useRef as a } from "react";
2
2
  import { useIsomorphicLayoutEffect as g } from "../useIsomorphicLayoutEffect/useIsomorphicLayoutEffect.mjs";
3
3
  import { useRefState as v } from "../useRefState/useRefState.mjs";
4
4
  import { isTarget as i } from "../../utils/helpers/isTarget.mjs";
5
- const R = ((...r) => {
6
- const o = i(r[0]) ? r[0] : void 0, n = (o ? r[1] : r[0])?.enabled ?? !0, [l, s] = w(n), c = v(), t = a(null);
5
+ const R = ((...o) => {
6
+ const r = i(o[0]) ? o[0] : void 0, n = (r ? o[1] : o[0])?.enabled ?? !0, [l, s] = w(n), u = v(), t = a(null);
7
7
  g(() => {
8
- const e = (o ? i.getElement(o) : c.current) ?? document.body;
8
+ const e = (r ? i.getElement(r) : u.current) ?? document.body;
9
9
  if (!(e instanceof HTMLElement) || (t.current = e, !n)) return;
10
10
  const m = window.getComputedStyle(e).overflow;
11
11
  return t.current.__originalOverflow = m, e.style.overflow = "hidden", () => {
12
12
  e.style.overflow = m, t.current = null;
13
13
  };
14
- }, [o, c.state, i.getRefState(o), n]);
15
- const u = () => {
14
+ }, [r, u.state, i.getRefState(r), n]);
15
+ const c = () => {
16
16
  if (!t.current) return;
17
17
  const e = t.current;
18
18
  t.current.__originalOverflow = window.getComputedStyle(e).overflow, e.style.overflow = "hidden", s(!0);
@@ -20,19 +20,16 @@ const R = ((...r) => {
20
20
  if (!t.current) return;
21
21
  const e = t.current;
22
22
  e.style.overflow = t.current.__originalOverflow, s(!1);
23
- }, d = () => {
24
- if (l) return f();
25
- u();
26
- };
27
- return o ? {
23
+ }, d = (e = !l) => e ? c() : f();
24
+ return r ? {
28
25
  value: l,
29
- lock: u,
26
+ lock: c,
30
27
  unlock: f,
31
28
  toggle: d
32
29
  } : {
33
- ref: c,
30
+ ref: u,
34
31
  value: l,
35
- lock: u,
32
+ lock: c,
36
33
  unlock: f,
37
34
  toggle: d
38
35
  };
@@ -1 +1 @@
1
- {"version":3,"file":"useLockScroll.mjs","sources":["../../../../src/hooks/useLockScroll/useLockScroll.ts"],"sourcesContent":["import { 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 { useIsomorphicLayoutEffect } from '../useIsomorphicLayoutEffect/useIsomorphicLayoutEffect';\nimport { useRefState } from '../useRefState/useRefState';\n\n/** The use lock scroll options type */\nexport interface UseLockScrollOptions {\n /** Enable or disable scroll locking. Default: true */\n enabled?: boolean;\n}\n\n/** The use lock scroll return type */\nexport interface UseLockScrollReturn<Target extends Element> {\n /** The ref to attach to the element */\n ref: StateRef<Target>;\n /** The value of the lock state */\n value: boolean;\n /** Lock the scroll */\n lock: () => void;\n /** Toggle the scroll lock */\n toggle: () => void;\n /** Unlock the scroll */\n unlock: () => void;\n}\n\nexport interface UseLockScroll {\n (target: HookTarget, options?: UseLockScrollOptions): UseLockScrollReturn<Element>;\n\n <Target extends Element>(\n options?: UseLockScrollOptions,\n target?: never\n ): UseLockScrollReturn<Target> & { ref: StateRef<Target> };\n}\n\n/**\n * @name useLockScroll\n * @description - Hook that locks scroll on an element or document body\n * @category Elements\n * @usage medium\n *\n * @overload\n * @param {HookTarget} [target=document.body] The target element to lock scroll on\n * @param {UseLockScrollOptions} [options] The options for scroll locking\n * @returns {void}\n *\n * @example\n * const { lock, unlock, value, toggle } = useLockScroll(ref);\n *\n * @overload\n * @template Target The target element\n * @param {UseLockScrollOptions} [options] The options for scroll locking\n * @returns {StateRef<Target>} Ref to attach to element, or locks body scroll by default\n *\n * @example\n * const { ref, lock, unlock, value, toggle } = useLockScroll();\n */\nexport const useLockScroll = ((...params: any[]): any => {\n const target = (isTarget(params[0]) ? params[0] : undefined) as HookTarget | undefined;\n const options = (target ? params[1] : params[0]) as UseLockScrollOptions | undefined;\n\n const enabled = options?.enabled ?? true;\n const [locked, setLocked] = useState(enabled);\n\n const internalRef = useRefState<Element>();\n const elementRef = useRef<Element>(null);\n\n useIsomorphicLayoutEffect(() => {\n const element =\n ((target ? isTarget.getElement(target) : internalRef.current) as Element) ?? document.body;\n\n if (!(element instanceof HTMLElement)) return;\n\n elementRef.current = element;\n\n if (!enabled) return;\n\n const originalStyle = window.getComputedStyle(element).overflow;\n (elementRef.current as any).__originalOverflow = originalStyle;\n element.style.overflow = 'hidden';\n\n return () => {\n element.style.overflow = originalStyle;\n elementRef.current = null;\n };\n }, [target, internalRef.state, isTarget.getRefState(target), enabled]);\n\n const lock = () => {\n if (!elementRef.current) return;\n const element = elementRef.current as HTMLElement;\n (elementRef.current as any).__originalOverflow = window.getComputedStyle(element).overflow;\n element.style.overflow = 'hidden';\n setLocked(true);\n };\n\n const unlock = () => {\n if (!elementRef.current) return;\n const element = elementRef.current as HTMLElement;\n element.style.overflow = (elementRef.current as any).__originalOverflow;\n setLocked(false);\n };\n\n const toggle = () => {\n if (locked) return unlock();\n lock();\n };\n\n if (target)\n return {\n value: locked,\n lock,\n unlock,\n toggle\n };\n return {\n ref: internalRef,\n value: locked,\n lock,\n unlock,\n toggle\n };\n}) as UseLockScroll;\n"],"names":["useLockScroll","params","target","isTarget","enabled","locked","setLocked","useState","internalRef","useRefState","elementRef","useRef","useIsomorphicLayoutEffect","element","originalStyle","lock","unlock","toggle"],"mappings":";;;;AA8DO,MAAMA,KAAiB,IAAIC,MAAuB;AACvD,QAAMC,IAAUC,EAASF,EAAO,CAAC,CAAC,IAAIA,EAAO,CAAC,IAAI,QAG5CG,KAFWF,IAASD,EAAO,CAAC,IAAIA,EAAO,CAAC,IAErB,WAAW,IAC9B,CAACI,GAAQC,CAAS,IAAIC,EAASH,CAAO,GAEtCI,IAAcC,EAAA,GACdC,IAAaC,EAAgB,IAAI;AAEvC,EAAAC,EAA0B,MAAM;AAC9B,UAAMC,KACFX,IAASC,EAAS,WAAWD,CAAM,IAAIM,EAAY,YAAwB,SAAS;AAMxF,QAJI,EAAEK,aAAmB,iBAEzBH,EAAW,UAAUG,GAEjB,CAACT,GAAS;AAEd,UAAMU,IAAgB,OAAO,iBAAiBD,CAAO,EAAE;AACtD,WAAAH,EAAW,QAAgB,qBAAqBI,GACjDD,EAAQ,MAAM,WAAW,UAElB,MAAM;AACX,MAAAA,EAAQ,MAAM,WAAWC,GACzBJ,EAAW,UAAU;AAAA,IAAA;AAAA,EACvB,GACC,CAACR,GAAQM,EAAY,OAAOL,EAAS,YAAYD,CAAM,GAAGE,CAAO,CAAC;AAErE,QAAMW,IAAO,MAAM;AACjB,QAAI,CAACL,EAAW,QAAS;AACzB,UAAMG,IAAUH,EAAW;AAC1B,IAAAA,EAAW,QAAgB,qBAAqB,OAAO,iBAAiBG,CAAO,EAAE,UAClFA,EAAQ,MAAM,WAAW,UACzBP,EAAU,EAAI;AAAA,EAAA,GAGVU,IAAS,MAAM;AACnB,QAAI,CAACN,EAAW,QAAS;AACzB,UAAMG,IAAUH,EAAW;AAC3B,IAAAG,EAAQ,MAAM,WAAYH,EAAW,QAAgB,oBACrDJ,EAAU,EAAK;AAAA,EAAA,GAGXW,IAAS,MAAM;AACnB,QAAIZ,UAAeW,EAAA;AACnB,IAAAD,EAAA;AAAA,EAAK;AAGP,SAAIb,IACK;AAAA,IACL,OAAOG;AAAA,IACP,MAAAU;AAAA,IACA,QAAAC;AAAA,IACA,QAAAC;AAAA,EAAA,IAEG;AAAA,IACL,KAAKT;AAAA,IACL,OAAOH;AAAA,IACP,MAAAU;AAAA,IACA,QAAAC;AAAA,IACA,QAAAC;AAAA,EAAA;AAEJ;"}
1
+ {"version":3,"file":"useLockScroll.mjs","sources":["../../../../src/hooks/useLockScroll/useLockScroll.ts"],"sourcesContent":["import { 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 { useIsomorphicLayoutEffect } from '../useIsomorphicLayoutEffect/useIsomorphicLayoutEffect';\nimport { useRefState } from '../useRefState/useRefState';\n\n/** The use lock scroll options type */\nexport interface UseLockScrollOptions {\n /** Enable or disable scroll locking. Default: true */\n enabled?: boolean;\n}\n\n/** The use lock scroll return type */\nexport interface UseLockScrollReturn<Target extends Element> {\n /** The ref to attach to the element */\n ref: StateRef<Target>;\n /** The value of the lock state */\n value: boolean;\n /** Lock the scroll */\n lock: () => void;\n /** Toggle the scroll lock */\n toggle: (value?: boolean) => void;\n /** Unlock the scroll */\n unlock: () => void;\n}\n\nexport interface UseLockScroll {\n (target: HookTarget, options?: UseLockScrollOptions): UseLockScrollReturn<Element>;\n\n <Target extends Element>(\n options?: UseLockScrollOptions,\n target?: never\n ): UseLockScrollReturn<Target> & { ref: StateRef<Target> };\n}\n\n/**\n * @name useLockScroll\n * @description - Hook that locks scroll on an element or document body\n * @category Elements\n * @usage medium\n *\n * @overload\n * @param {HookTarget} [target=document.body] The target element to lock scroll on\n * @param {UseLockScrollOptions} [options] The options for scroll locking\n * @returns {void}\n *\n * @example\n * const { lock, unlock, value, toggle } = useLockScroll(ref);\n *\n * @overload\n * @template Target The target element\n * @param {UseLockScrollOptions} [options] The options for scroll locking\n * @returns {StateRef<Target>} Ref to attach to element, or locks body scroll by default\n *\n * @example\n * const { ref, lock, unlock, value, toggle } = useLockScroll();\n */\nexport const useLockScroll = ((...params: any[]): any => {\n const target = (isTarget(params[0]) ? params[0] : undefined) as HookTarget | undefined;\n const options = (target ? params[1] : params[0]) as UseLockScrollOptions | undefined;\n\n const enabled = options?.enabled ?? true;\n const [locked, setLocked] = useState(enabled);\n\n const internalRef = useRefState<Element>();\n const elementRef = useRef<Element>(null);\n\n useIsomorphicLayoutEffect(() => {\n const element =\n ((target ? isTarget.getElement(target) : internalRef.current) as Element) ?? document.body;\n\n if (!(element instanceof HTMLElement)) return;\n\n elementRef.current = element;\n\n if (!enabled) return;\n\n const originalStyle = window.getComputedStyle(element).overflow;\n (elementRef.current as any).__originalOverflow = originalStyle;\n element.style.overflow = 'hidden';\n\n return () => {\n element.style.overflow = originalStyle;\n elementRef.current = null;\n };\n }, [target, internalRef.state, isTarget.getRefState(target), enabled]);\n\n const lock = () => {\n if (!elementRef.current) return;\n const element = elementRef.current as HTMLElement;\n (elementRef.current as any).__originalOverflow = window.getComputedStyle(element).overflow;\n element.style.overflow = 'hidden';\n setLocked(true);\n };\n\n const unlock = () => {\n if (!elementRef.current) return;\n const element = elementRef.current as HTMLElement;\n element.style.overflow = (elementRef.current as any).__originalOverflow;\n setLocked(false);\n };\n\n const toggle = (value = !locked) => {\n if (value) return lock();\n return unlock();\n };\n\n if (target)\n return {\n value: locked,\n lock,\n unlock,\n toggle\n };\n return {\n ref: internalRef,\n value: locked,\n lock,\n unlock,\n toggle\n };\n}) as UseLockScroll;\n"],"names":["useLockScroll","params","target","isTarget","enabled","locked","setLocked","useState","internalRef","useRefState","elementRef","useRef","useIsomorphicLayoutEffect","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AAAC;AAAA,IACA,QAAAC;AAAA,EAAA,IAEG;AAAA,IACL,KAAKT;AAAA,IACL,OAAOH;AAAA,IACP,MAAAU;AAAA,IACA,QAAAC;AAAA,IACA,QAAAC;AAAA,EAAA;AAEJ;"}
@@ -43,7 +43,7 @@ const O = (n) => {
43
43
  volume: I,
44
44
  play: p,
45
45
  pause: k,
46
- toggle: async () => u ? k() : p(),
46
+ toggle: async (e = !u) => e ? p() : k(),
47
47
  seek: (e) => {
48
48
  t.current && (t.current.currentTime = Math.min(Math.max(e, 0), d));
49
49
  },
@@ -1 +1 @@
1
- {"version":3,"file":"useMediaControls.mjs","sources":["../../../../src/hooks/useMediaControls/useMediaControls.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 const timeRangeToArray = (timeRanges: TimeRanges) => {\n let ranges: [number, number][] = [];\n\n for (let i = 0; i < timeRanges.length; ++i)\n ranges = [...ranges, [timeRanges.start(i), timeRanges.end(i)]];\n\n return ranges;\n};\n\n/** The media source configuration type */\nexport interface UseMediaSource {\n /** The media attribute of the media */\n media?: string;\n /** The source URL of the media */\n src: string;\n /** The MIME type of the media */\n type?: string;\n}\n\n/** The media controls return type */\nexport interface UseMediaControlsReturn {\n /** Whether the media is currently buffering */\n buffered: [number, number][];\n /** The current playback position in seconds */\n currentTime: number;\n /** The total duration of the media in seconds */\n duration: number;\n /** Whether the media has ended */\n ended: boolean;\n /** Whether the media is currently muted */\n muted: boolean;\n /** The current playback rate (1.0 is normal speed) */\n playbackRate: number;\n /** Whether the media is currently playing */\n playing: boolean;\n /** Whether the media is currently seeking */\n seeking: boolean;\n /** Whether the media is currently stalled */\n stalled: boolean;\n /** The current volume level (0.0 to 1.0) */\n volume: number;\n /** Whether the media is currently waiting */\n waiting: boolean;\n\n /** Set the playback rate */\n changePlaybackRate: (rate: number) => void;\n /** Set the volume level (0.0 to 1.0) */\n changeVolume: (volume: number) => void;\n /** Set the muted state */\n mute: () => void;\n /** Pause the media */\n pause: () => void;\n /** Start playing the media */\n play: () => Promise<void>;\n /** Seek to a specific time in seconds */\n seek: (time: number) => void;\n /** Toggle between play and pause */\n toggle: () => Promise<void>;\n /** Set the unmuted state */\n unmute: () => void;\n}\n\nexport interface UseMediaControls {\n (target: HookTarget, src: string): UseMediaControlsReturn;\n\n (target: HookTarget, options: UseMediaSource): UseMediaControlsReturn;\n\n <Target extends HTMLMediaElement>(\n src: string\n ): UseMediaControlsReturn & {\n ref: StateRef<Target>;\n };\n\n <Target extends HTMLMediaElement>(\n options: UseMediaSource\n ): UseMediaControlsReturn & { ref: StateRef<Target> };\n}\n\n/**\n * @name useMediaControls\n * @description Hook that provides controls for HTML media elements (audio/video)\n * @category Browser\n * @usage low\n *\n * @overload\n * @param {HookTarget} target The target media element\n * @param {string} src The source URL of the media\n * @returns {UseMediaControlsReturn} An object containing media controls and state\n *\n * @example\n * const { playing, play, pause } = useMediaControls(videoRef, 'video.mp4');\n *\n * @overload\n * @param {HookTarget} target The target media element\n * @param {UseMediaSource} options The media source configuration\n * @returns {UseMediaControlsReturn} An object containing media controls and state\n *\n * @example\n * const { playing, play, pause } = useMediaControls(audioRef, { src: 'audio.mp3', type: 'audio/mp3' });\n *\n * @overload\n * @template Target The target media element type\n * @param {string} src The source URL of the media\n * @returns {UseMediaControlsReturn & { ref: StateRef<Target> }} An object containing media controls, state and ref\n *\n * @example\n * const { ref, playing, play, pause } = useMediaControls<HTMLVideoElement>('video.mp4');\n *\n * @overload\n * @template Target The target media element type\n * @param {UseMediaSource} options The media source configuration\n * @returns {UseMediaControlsReturn & { ref: StateRef<Target> }} An object containing media controls, state and ref\n *\n * @example\n * const { ref, playing, play, pause } = useMediaControls<HTMLVideoElement>({ src: 'video.mp4', type: 'video/mp4' });\n */\nexport const useMediaControls = ((...params: any[]) => {\n const target = (isTarget(params[0]) ? params[0] : undefined) as HookTarget | undefined;\n const options = (\n target\n ? typeof params[1] === 'object'\n ? params[1]\n : { src: params[1] }\n : typeof params[0] === 'object'\n ? params[0]\n : { src: params[0] }\n ) as UseMediaSource;\n\n const internalRef = useRefState<HTMLMediaElement>();\n const elementRef = useRef<HTMLMediaElement | null>(null);\n\n const [playing, setPlaying] = useState(false);\n const [duration, setDuration] = useState(0);\n const [currentTime, setCurrentTime] = useState(0);\n const [seeking, setSeeking] = useState(false);\n const [waiting, setWaiting] = useState(false);\n const [buffered, setBuffered] = useState<[number, number][]>([]);\n const [stalled, setStalled] = useState(false);\n const [ended, setEnded] = useState(false);\n const [playbackRate, setPlaybackRateState] = useState(1);\n\n const [muted, setMutedState] = useState(false);\n const [volume, setVolumeState] = useState(1);\n\n useEffect(() => {\n const element = (\n target ? isTarget.getElement(target) : internalRef.current\n ) as HTMLMediaElement;\n\n if (!element) return;\n\n elementRef.current = element;\n element.src = options.src;\n\n if (options.type) element.setAttribute('type', options.type);\n if (options.media) element.setAttribute('media', options.media);\n\n setDuration(element.duration);\n setCurrentTime(element.currentTime);\n setPlaying(false);\n setEnded(element.ended);\n setMutedState(element.muted);\n setVolumeState(element.volume);\n setPlaybackRateState(element.playbackRate);\n\n const onPlaying = () => {\n setPlaying(true);\n setStalled(false);\n };\n const onPause = () => setPlaying(false);\n const onWaiting = () => setWaiting(true);\n const onStalled = () => setStalled(true);\n const onSeeking = () => setSeeking(true);\n const onSeeked = () => setSeeking(false);\n const onEnded = () => {\n setPlaying(false);\n setEnded(true);\n };\n const onDurationChange = () => setDuration(element.duration);\n const onTimeUpdate = () => setCurrentTime(element.currentTime);\n const onVolumechange = () => {\n setMutedState(element.muted);\n setVolumeState(element.volume);\n };\n const onRatechange = () => setPlaybackRateState(element.playbackRate);\n const onProgress = () => setBuffered(timeRangeToArray(element.buffered));\n\n element.addEventListener('playing', onPlaying);\n element.addEventListener('pause', onPause);\n element.addEventListener('waiting', onWaiting);\n element.addEventListener('progress', onProgress);\n element.addEventListener('stalled', onStalled);\n element.addEventListener('seeking', onSeeking);\n element.addEventListener('seeked', onSeeked);\n element.addEventListener('ended', onEnded);\n element.addEventListener('loadedmetadata', onDurationChange);\n element.addEventListener('timeupdate', onTimeUpdate);\n element.addEventListener('volumechange', onVolumechange);\n element.addEventListener('ratechange', onRatechange);\n\n return () => {\n element.removeEventListener('playing', onPlaying);\n element.removeEventListener('pause', onPause);\n element.removeEventListener('waiting', onWaiting);\n element.removeEventListener('progress', onProgress);\n element.removeEventListener('stalled', onStalled);\n element.removeEventListener('seeking', onSeeking);\n element.removeEventListener('seeked', onSeeked);\n element.removeEventListener('ended', onEnded);\n element.removeEventListener('loadedmetadata', onDurationChange);\n element.removeEventListener('timeupdate', onTimeUpdate);\n element.removeEventListener('volumechange', onVolumechange);\n element.removeEventListener('ratechange', onRatechange);\n };\n }, [target, internalRef.state, isTarget.getRefState(target)]);\n\n const play = async () => {\n const element = elementRef.current;\n if (!element) return;\n\n await element.play();\n };\n\n const pause = () => {\n if (!elementRef.current) return;\n elementRef.current.pause();\n };\n\n const toggle = async () => {\n if (playing) return pause();\n return play();\n };\n\n const seek = (time: number) => {\n if (!elementRef.current) return;\n elementRef.current.currentTime = Math.min(Math.max(time, 0), duration);\n };\n\n const changeVolume = (value: number) => {\n if (!elementRef.current) return;\n elementRef.current.volume = Math.min(Math.max(value, 0), 1);\n };\n\n const mute = () => {\n if (!elementRef.current) return;\n elementRef.current.muted = true;\n };\n\n const unmute = () => {\n if (!elementRef.current) return;\n elementRef.current.muted = false;\n };\n\n const changePlaybackRate = (value: number) => {\n if (!elementRef.current) return;\n elementRef.current.playbackRate = value;\n };\n\n return {\n playing,\n duration,\n currentTime,\n seeking,\n waiting,\n buffered,\n stalled,\n ended,\n playbackRate,\n muted,\n volume,\n\n play,\n pause,\n toggle,\n seek,\n changeVolume,\n mute,\n unmute,\n changePlaybackRate,\n\n ...(!target && { ref: internalRef })\n };\n}) as UseMediaControls;\n"],"names":["timeRangeToArray","timeRanges","ranges","i","useMediaControls","params","target","isTarget","options","internalRef","useRefState","elementRef","useRef","playing","setPlaying","useState","duration","setDuration","currentTime","setCurrentTime","seeking","setSeeking","waiting","setWaiting","buffered","setBuffered","stalled","setStalled","ended","setEnded","playbackRate","setPlaybackRateState","muted","setMutedState","volume","setVolumeState","useEffect","element","onPlaying","onPause","onWaiting","onStalled","onSeeking","onSeeked","onEnded","onDurationChange","onTimeUpdate","onVolumechange","onRatechange","onProgress","play","pause","time","value"],"mappings":";;;AAUO,MAAMA,IAAmB,CAACC,MAA2B;AAC1D,MAAIC,IAA6B,CAAA;AAEjC,WAASC,IAAI,GAAGA,IAAIF,EAAW,QAAQ,EAAEE;AACvC,IAAAD,IAAS,CAAC,GAAGA,GAAQ,CAACD,EAAW,MAAME,CAAC,GAAGF,EAAW,IAAIE,CAAC,CAAC,CAAC;AAE/D,SAAOD;AACT,GA6GaE,MAAoB,IAAIC,MAAkB;AACrD,QAAMC,IAAUC,EAASF,EAAO,CAAC,CAAC,IAAIA,EAAO,CAAC,IAAI,QAC5CG,IACJF,IACI,OAAOD,EAAO,CAAC,KAAM,WACnBA,EAAO,CAAC,IACR,EAAE,KAAKA,EAAO,CAAC,EAAA,IACjB,OAAOA,EAAO,CAAC,KAAM,WACnBA,EAAO,CAAC,IACR,EAAE,KAAKA,EAAO,CAAC,EAAA,GAGjBI,IAAcC,EAAA,GACdC,IAAaC,EAAgC,IAAI,GAEjD,CAACC,GAASC,CAAU,IAAIC,EAAS,EAAK,GACtC,CAACC,GAAUC,CAAW,IAAIF,EAAS,CAAC,GACpC,CAACG,GAAaC,CAAc,IAAIJ,EAAS,CAAC,GAC1C,CAACK,GAASC,CAAU,IAAIN,EAAS,EAAK,GACtC,CAACO,GAASC,CAAU,IAAIR,EAAS,EAAK,GACtC,CAACS,GAAUC,CAAW,IAAIV,EAA6B,CAAA,CAAE,GACzD,CAACW,GAASC,CAAU,IAAIZ,EAAS,EAAK,GACtC,CAACa,GA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MAAA;AAAA,EAAM;AAiC3B,SAAO;AAAA,IACL,SAAAE;AAAA,IACA,UAAAG;AAAA,IACA,aAAAE;AAAA,IACA,SAAAE;AAAA,IACA,SAAAE;AAAA,IACA,UAAAE;AAAA,IACA,SAAAE;AAAA,IACA,OAAAE;AAAA,IACA,cAAAE;AAAA,IACA,OAAAE;AAAA,IACA,QAAAE;AAAA,IAEA,MAAAgB;AAAA,IACA,OAAAC;AAAA,IACA,QA7Ca,YACTtC,IAAgBsC,EAAA,IACbD,EAAA;AAAA,IA4CP,MAzCW,CAACE,MAAiB;AAC7B,MAAKzC,EAAW,YAChBA,EAAW,QAAQ,cAAc,KAAK,IAAI,KAAK,IAAIyC,GAAM,CAAC,GAAGpC,CAAQ;AAAA,IAAA;AAAA,IAwCrE,cArCmB,CAACqC,MAAkB;AACtC,MAAK1C,EAAW,YAChBA,EAAW,QAAQ,SAAS,KAAK,IAAI,KAAK,IAAI0C,GAAO,CAAC,GAAG,CAAC;AAAA,IAAA;AAAA,IAoC1D,MAjCW,MAAM;AACjB,MAAK1C,EAAW,YAChBA,EAAW,QAAQ,QAAQ;AAAA,IAAA;AAAA,IAgC3B,QA7Ba,MAAM;AACnB,MAAKA,EAAW,YAChBA,EAAW,QAAQ,QAAQ;AAAA,IAAA;AAAA,IA4B3B,oBAzByB,CAAC0C,MAAkB;AAC5C,MAAK1C,EAAW,YAChBA,EAAW,QAAQ,eAAe0C;AAAA,IAAA;AAAA,IAyBlC,GAAI,CAAC/C,KAAU,EAAE,KAAKG,EAAA;AAAA,EAAY;AAEtC;"}
1
+ {"version":3,"file":"useMediaControls.mjs","sources":["../../../../src/hooks/useMediaControls/useMediaControls.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 const timeRangeToArray = (timeRanges: TimeRanges) => {\n let ranges: [number, number][] = [];\n\n for (let i = 0; i < timeRanges.length; ++i)\n ranges = [...ranges, [timeRanges.start(i), timeRanges.end(i)]];\n\n return ranges;\n};\n\n/** The media source configuration type */\nexport interface UseMediaSource {\n /** The media attribute of the media */\n media?: string;\n /** The source URL of the media */\n src: string;\n /** The MIME type of the media */\n type?: string;\n}\n\n/** The media controls return type */\nexport interface UseMediaControlsReturn {\n /** Whether the media is currently buffering */\n buffered: [number, number][];\n /** The current playback position in seconds */\n currentTime: number;\n /** The total duration of the media in seconds */\n duration: number;\n /** Whether the media has ended */\n ended: boolean;\n /** Whether the media is currently muted */\n muted: boolean;\n /** The current playback rate (1.0 is normal speed) */\n playbackRate: number;\n /** Whether the media is currently playing */\n playing: boolean;\n /** Whether the media is currently seeking */\n seeking: boolean;\n /** Whether the media is currently stalled */\n stalled: boolean;\n /** The current volume level (0.0 to 1.0) */\n volume: number;\n /** Whether the media is currently waiting */\n waiting: boolean;\n\n /** Set the playback rate */\n changePlaybackRate: (rate: number) => void;\n /** Set the volume level (0.0 to 1.0) */\n changeVolume: (volume: number) => void;\n /** Set the muted state */\n mute: () => void;\n /** Pause the media */\n pause: () => void;\n /** Start playing the media */\n play: () => Promise<void>;\n /** Seek to a specific time in seconds */\n seek: (time: number) => void;\n /** Toggle between play and pause */\n toggle: () => Promise<void>;\n /** Set the unmuted state */\n unmute: () => void;\n}\n\nexport interface UseMediaControls {\n (target: HookTarget, src: string): UseMediaControlsReturn;\n\n (target: HookTarget, options: UseMediaSource): UseMediaControlsReturn;\n\n <Target extends HTMLMediaElement>(\n src: string\n ): UseMediaControlsReturn & {\n ref: StateRef<Target>;\n };\n\n <Target extends HTMLMediaElement>(\n options: UseMediaSource\n ): UseMediaControlsReturn & { ref: StateRef<Target> };\n}\n\n/**\n * @name useMediaControls\n * @description Hook that provides controls for HTML media elements (audio/video)\n * @category Browser\n * @usage low\n *\n * @overload\n * @param {HookTarget} target The target media element\n * @param {string} src The source URL of the media\n * @returns {UseMediaControlsReturn} An object containing media controls and state\n *\n * @example\n * const { playing, play, pause } = useMediaControls(videoRef, 'video.mp4');\n *\n * @overload\n * @param {HookTarget} target The target media element\n * @param {UseMediaSource} options The media source configuration\n * @returns {UseMediaControlsReturn} An object containing media controls and state\n *\n * @example\n * const { playing, play, pause } = useMediaControls(audioRef, { src: 'audio.mp3', type: 'audio/mp3' });\n *\n * @overload\n * @template Target The target media element type\n * @param {string} src The source URL of the media\n * @returns {UseMediaControlsReturn & { ref: StateRef<Target> }} An object containing media controls, state and ref\n *\n * @example\n * const { ref, playing, play, pause } = useMediaControls<HTMLVideoElement>('video.mp4');\n *\n * @overload\n * @template Target The target media element type\n * @param {UseMediaSource} options The media source configuration\n * @returns {UseMediaControlsReturn & { ref: StateRef<Target> }} An object containing media controls, state and ref\n *\n * @example\n * const { ref, playing, play, pause } = useMediaControls<HTMLVideoElement>({ src: 'video.mp4', type: 'video/mp4' });\n */\nexport const useMediaControls = ((...params: any[]) => {\n const target = (isTarget(params[0]) ? params[0] : undefined) as HookTarget | undefined;\n const options = (\n target\n ? typeof params[1] === 'object'\n ? params[1]\n : { src: params[1] }\n : typeof params[0] === 'object'\n ? params[0]\n : { src: params[0] }\n ) as UseMediaSource;\n\n const internalRef = useRefState<HTMLMediaElement>();\n const elementRef = useRef<HTMLMediaElement | null>(null);\n\n const [playing, setPlaying] = useState(false);\n const [duration, setDuration] = useState(0);\n const [currentTime, setCurrentTime] = useState(0);\n const [seeking, setSeeking] = useState(false);\n const [waiting, setWaiting] = useState(false);\n const [buffered, setBuffered] = useState<[number, number][]>([]);\n const [stalled, setStalled] = useState(false);\n const [ended, setEnded] = useState(false);\n const [playbackRate, setPlaybackRateState] = useState(1);\n\n const [muted, setMutedState] = useState(false);\n const [volume, setVolumeState] = useState(1);\n\n useEffect(() => {\n const element = (\n target ? isTarget.getElement(target) : internalRef.current\n ) as HTMLMediaElement;\n\n if (!element) return;\n\n elementRef.current = element;\n element.src = options.src;\n\n if (options.type) element.setAttribute('type', options.type);\n if (options.media) element.setAttribute('media', options.media);\n\n setDuration(element.duration);\n setCurrentTime(element.currentTime);\n setPlaying(false);\n setEnded(element.ended);\n setMutedState(element.muted);\n setVolumeState(element.volume);\n setPlaybackRateState(element.playbackRate);\n\n const onPlaying = () => {\n setPlaying(true);\n setStalled(false);\n };\n const onPause = () => setPlaying(false);\n const onWaiting = () => setWaiting(true);\n const onStalled = () => setStalled(true);\n const onSeeking = () => setSeeking(true);\n const onSeeked = () => setSeeking(false);\n const onEnded = () => {\n setPlaying(false);\n setEnded(true);\n };\n const onDurationChange = () => setDuration(element.duration);\n const onTimeUpdate = () => setCurrentTime(element.currentTime);\n const onVolumechange = () => {\n setMutedState(element.muted);\n setVolumeState(element.volume);\n };\n const onRatechange = () => setPlaybackRateState(element.playbackRate);\n const onProgress = () => setBuffered(timeRangeToArray(element.buffered));\n\n element.addEventListener('playing', onPlaying);\n element.addEventListener('pause', onPause);\n element.addEventListener('waiting', onWaiting);\n element.addEventListener('progress', onProgress);\n element.addEventListener('stalled', onStalled);\n element.addEventListener('seeking', onSeeking);\n element.addEventListener('seeked', onSeeked);\n element.addEventListener('ended', onEnded);\n element.addEventListener('loadedmetadata', onDurationChange);\n element.addEventListener('timeupdate', onTimeUpdate);\n element.addEventListener('volumechange', onVolumechange);\n element.addEventListener('ratechange', onRatechange);\n\n return () => {\n element.removeEventListener('playing', onPlaying);\n element.removeEventListener('pause', onPause);\n element.removeEventListener('waiting', onWaiting);\n element.removeEventListener('progress', onProgress);\n element.removeEventListener('stalled', onStalled);\n element.removeEventListener('seeking', onSeeking);\n element.removeEventListener('seeked', onSeeked);\n element.removeEventListener('ended', onEnded);\n element.removeEventListener('loadedmetadata', onDurationChange);\n element.removeEventListener('timeupdate', onTimeUpdate);\n element.removeEventListener('volumechange', onVolumechange);\n element.removeEventListener('ratechange', onRatechange);\n };\n }, [target, internalRef.state, isTarget.getRefState(target)]);\n\n const play = async () => {\n const element = elementRef.current;\n if (!element) return;\n\n await element.play();\n };\n\n const pause = () => {\n if (!elementRef.current) return;\n elementRef.current.pause();\n };\n\n const toggle = async (value = !playing) => {\n if (value) return play();\n return pause();\n };\n\n const seek = (time: number) => {\n if (!elementRef.current) return;\n elementRef.current.currentTime = Math.min(Math.max(time, 0), duration);\n };\n\n const changeVolume = (value: number) => {\n if (!elementRef.current) return;\n elementRef.current.volume = Math.min(Math.max(value, 0), 1);\n };\n\n const mute = () => {\n if (!elementRef.current) return;\n elementRef.current.muted = true;\n };\n\n const unmute = () => {\n if (!elementRef.current) return;\n elementRef.current.muted = false;\n };\n\n const changePlaybackRate = (value: number) => {\n if (!elementRef.current) return;\n elementRef.current.playbackRate = value;\n };\n\n return {\n playing,\n duration,\n currentTime,\n seeking,\n waiting,\n buffered,\n stalled,\n ended,\n playbackRate,\n muted,\n volume,\n\n play,\n pause,\n toggle,\n seek,\n changeVolume,\n mute,\n unmute,\n changePlaybackRate,\n\n ...(!target && { ref: internalRef })\n };\n}) as UseMediaControls;\n"],"names":["timeRangeToArray","timeRanges","ranges","i","useMediaControls","params","target","isTarget","options","internalRef","useRefState","elementRef","useRef","playing","setPlaying","useState","duration","setDuration","currentTime","setCurrentTime","seeking","setSeeking","waiting","setWaiting","buffered","setBuffered","stalled","setStalled","ended","setEnded","playbackRate","setPlaybackRateState","muted","setMutedState","volume","setVolumeState","useEffect","element","onPlaying","onPause","onWaiting","onStalled","onSeeking","onSeeked","onEnded","onDurationChange","onTimeUpdate","onVolumechange","onRatechange","onProgress","play","pause","value","time"],"mappings":";;;AAUO,MAAMA,IAAmB,CAACC,MAA2B;AAC1D,MAAIC,IAA6B,CAAA;AAEjC,WAASC,IAAI,GAAGA,IAAIF,EAAW,QAAQ,EAAEE;AACvC,IAAAD,IAAS,CAAC,GAAGA,GAAQ,CAACD,EAAW,MAAME,CAAC,GAAGF,EAAW,IAAIE,CAAC,CAAC,CAAC;AAE/D,SAAOD;AACT,GA6GaE,MAAoB,IAAIC,MAAkB;AACrD,QAAMC,IAAUC,EA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G,CAAC;AAAA,IAAA;AAAA,IAoC1D,MAjCW,MAAM;AACjB,MAAKzC,EAAW,YAChBA,EAAW,QAAQ,QAAQ;AAAA,IAAA;AAAA,IAgC3B,QA7Ba,MAAM;AACnB,MAAKA,EAAW,YAChBA,EAAW,QAAQ,QAAQ;AAAA,IAAA;AAAA,IA4B3B,oBAzByB,CAACyC,MAAkB;AAC5C,MAAKzC,EAAW,YAChBA,EAAW,QAAQ,eAAeyC;AAAA,IAAA;AAAA,IAyBlC,GAAI,CAAC9C,KAAU,EAAE,KAAKG,EAAA;AAAA,EAAY;AAEtC;"}
@@ -1,24 +1,26 @@
1
- import { useState as i, useRef as l } from "react";
2
- const b = ((...t) => {
3
- const e = typeof navigator < "u" && "OTPCredential" in navigator && !!navigator.OTPCredential, c = typeof t[0] == "function" ? t[0] : t[0]?.onSuccess, s = typeof t[0] == "function" ? t[0]?.onError : void 0, [a, n] = i(!1), r = l(new AbortController());
1
+ import { useRef as c } from "react";
2
+ const l = ((...o) => {
3
+ const e = typeof navigator < "u" && "OTPCredential" in navigator && !!navigator.OTPCredential, n = typeof o[0] == "object" ? o[0] : {
4
+ onSuccess: o[0]
5
+ }, t = c(new AbortController());
4
6
  return { supported: e, abort: () => {
5
- r.current.abort(), r.current = new AbortController(), r.current.signal.onabort = () => n(!0);
6
- }, aborted: a, get: async () => {
7
+ t.current.abort(), t.current = new AbortController();
8
+ }, get: async () => {
7
9
  if (e) {
8
- r.current = new AbortController();
10
+ t.current = new AbortController();
9
11
  try {
10
- const o = await navigator.credentials.get({
12
+ const r = await navigator.credentials.get({
11
13
  otp: { transport: ["sms"] },
12
- signal: r.current.signal
14
+ signal: t.current.signal
13
15
  });
14
- return c?.(o), n(!1), o;
15
- } catch (o) {
16
- s?.(o);
16
+ return n.onSuccess?.(r), r;
17
+ } catch (r) {
18
+ n.onError?.(r);
17
19
  }
18
20
  }
19
21
  } };
20
22
  });
21
23
  export {
22
- b as useOtpCredential
24
+ l as useOtpCredential
23
25
  };
24
26
  //# sourceMappingURL=useOtpCredential.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"useOtpCredential.mjs","sources":["../../../../src/hooks/useOtpCredential/useOtpCredential.ts"],"sourcesContent":["import { useRef, useState } 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 aborted state of the query */\n aborted: boolean;\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 onSuccess =\n typeof params[0] === 'function'\n ? (params[0] as UseOtpCredentialCallback | undefined)\n : (params[0] as UseOtpCredentialParams | undefined)?.onSuccess;\n\n const onError =\n typeof params[0] === 'function'\n ? (params[0] as UseOtpCredentialParams | undefined)?.onError\n : undefined;\n\n const [aborted, setAborted] = useState(false);\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 onSuccess?.(credential);\n setAborted(false);\n return credential;\n } catch (error) {\n onError?.(error);\n }\n };\n\n const abort = () => {\n abortControllerRef.current.abort();\n abortControllerRef.current = new AbortController();\n abortControllerRef.current.signal.onabort = () => setAborted(true);\n };\n\n return { supported, abort, aborted, get };\n}) as UseOtpCredential;\n"],"names":["useOtpCredential","params","supported","onSuccess","onError","aborted","setAborted","useState","abortControllerRef","useRef","credential","error"],"mappings":";AAoEO,MAAMA,KAAoB,IAAIC,MAAkB;AACrD,QAAMC,IACJ,OAAO,YAAc,OAAe,mBAAmB,aAAa,CAAC,CAAC,UAAU,eAE5EC,IACJ,OAAOF,EAAO,CAAC,KAAM,aAChBA,EAAO,CAAC,IACRA,EAAO,CAAC,GAA0C,WAEnDG,IACJ,OAAOH,EAAO,CAAC,KAAM,aAChBA,EAAO,CAAC,GAA0C,UACnD,QAEA,CAACI,GAASC,CAAU,IAAIC,EAAS,EAAK,GAEtCC,IAAqBC,EAAwB,IAAI,iBAAiB;AAyBxE,SAAO,EAAE,WAAAP,GAAW,OANN,MAAM;AAClB,IAAAM,EAAmB,QAAQ,MAAA,GAC3BA,EAAmB,UAAU,IAAI,gBAAA,GACjCA,EAAmB,QAAQ,OAAO,UAAU,MAAMF,EAAW,EAAI;AAAA,EAAA,GAGxC,SAAAD,GAAS,KAvBxB,YAAY;AACtB,QAAKH,GAEL;AAAA,MAAAM,EAAmB,UAAU,IAAI,gBAAA;AACjC,UAAI;AACF,cAAME,IAAa,MAAM,UAAU,YAAY,IAAI;AAAA,UACjD,KAAK,EAAE,WAAW,CAAC,KAAK,EAAA;AAAA,UACxB,QAAQF,EAAmB,QAAQ;AAAA,QAAA,CACpC;AACD,eAAAL,IAAYO,CAAU,GACtBJ,EAAW,EAAK,GACTI;AAAA,MAAA,SACAC,GAAO;AACd,QAAAP,IAAUO,CAAK;AAAA,MAAA;AAAA;AAAA,EACjB,EASkC;AACtC;"}
1
+ {"version":3,"file":"useOtpCredential.mjs","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":";AAkEO,MAAMA,KAAoB,IAAIC,MAAkB;AACrD,QAAMC,IACJ,OAAO,YAAc,OAAe,mBAAmB,aAAa,CAAC,CAAC,UAAU,eAE5EC,IACJ,OAAOF,EAAO,CAAC,KAAM,WACjBA,EAAO,CAAC,IACR;AAAA,IACE,WAAWA,EAAO,CAAC;AAAA,EAAA,GAGrBG,IAAqBC,EAAwB,IAAI,iBAAiB;AAwBxE,SAAO,EAAE,WAAAH,GAAW,OALN,MAAM;AAClB,IAAAE,EAAmB,QAAQ,MAAA,GAC3BA,EAAmB,UAAU,IAAI,gBAAA;AAAA,EAAgB,GAGxB,KAtBf,YAAY;AACtB,QAAKF,GAEL;AAAA,MAAAE,EAAmB,UAAU,IAAI,gBAAA;AACjC,UAAI;AACF,cAAME,IAAa,MAAM,UAAU,YAAY,IAAI;AAAA,UACjD,KAAK,EAAE,WAAW,CAAC,KAAK,EAAA;AAAA,UACxB,QAAQF,EAAmB,QAAQ;AAAA,QAAA,CACpC;AACD,eAAAD,EAAQ,YAAYG,CAAU,GAEvBA;AAAA,MAAA,SACAC,GAAO;AACd,QAAAJ,EAAQ,UAAUI,CAAK;AAAA,MAAA;AAAA;AAAA,EACzB,EAQyB;AAC7B;"}
@@ -11,23 +11,21 @@ const f = () => window?.SpeechRecognition ?? window?.webkitSpeechRecognition, q
11
11
  onError: x,
12
12
  onResult: E
13
13
  } = d, [l, s] = e(!1), [A, b] = e(""), [k, y] = e(!1), [F, u] = e(null), [o] = e(() => {
14
- if (!i) return {};
14
+ if (!i) return;
15
15
  const r = f(), t = new r();
16
16
  return t.continuous = m, a && (t.grammars = a), t.interimResults = R, t.lang = c, t.maxAlternatives = w, t.onstart = () => {
17
17
  s(!0), y(!1), S?.();
18
- }, t.onend = () => {
19
- s(!1), h?.();
20
18
  }, t.onerror = (n) => {
21
19
  u(n), s(!1), x?.(n);
22
20
  }, t.onresult = (n) => {
23
21
  const I = n.results[n.resultIndex], { transcript: L } = I[0];
24
- b(L), u(null), E?.(n);
22
+ s(!1), b(L), u(null), E?.(n);
25
23
  }, t.onend = () => {
26
- s(!1), t.lang = c;
24
+ s(!1), h?.(), t.lang = c;
27
25
  }, t;
28
26
  });
29
- T(() => () => o.stop(), []);
30
- const g = () => o.start(), p = () => o.stop();
27
+ T(() => () => o?.stop(), []);
28
+ const g = () => o?.start(), p = () => o?.stop();
31
29
  return {
32
30
  supported: i,
33
31
  transcript: A,
@@ -37,10 +35,7 @@ const f = () => window?.SpeechRecognition ?? window?.webkitSpeechRecognition, q
37
35
  error: F,
38
36
  start: g,
39
37
  stop: p,
40
- toggle: (r = !l) => {
41
- if (r) return g();
42
- p();
43
- }
38
+ toggle: (r = !l) => r ? g() : p()
44
39
  };
45
40
  };
46
41
  export {
@@ -1 +1 @@
1
- {"version":3,"file":"useSpeechRecognition.mjs","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>(() => {\n if (!supported) return {} as SpeechRecognition;\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.onend = () => {\n setListening(false);\n onEnd?.();\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 setTranscript(transcript);\n setError(null);\n onResult?.(event);\n };\n speechRecognition.onend = () => {\n setListening(false);\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":";AA8CO,MAAMA,IAAuB,MAClC,QAAQ,qBAAqB,QAAQ,yBAwB1BC,IAAuB,CAClCC,IAAuC,OACR;AAC/B,QAAMC,IAAY,OAAO,SAAW,OAAe,CAAC,CAACH,EAAA,GAE/C;AAAA,IACJ,YAAAI,IAAa;AAAA,IACb,gBAAAC,IAAiB;AAAA,IACjB,UAAAC,IAAW;AAAA,IACX,UAAAC;AAAA,IACA,iBAAAC,IAAkB;AAAA,IAClB,SAAAC;AAAA,IACA,OAAAC;AAAA,IACA,SAAAC;AAAA,IACA,UAAAC;AAAA,EAAA,IACEV,GAEE,CAACW,GAAWC,CAAY,IAAIC,EAAS,EAAK,GAC1C,CAACC,GAAYC,CAAa,IAAIF,EAAS,EAAE,GACzC,CAACG,GAAOC,CAAQ,IAAIJ,EAAS,EAAK,GAClC,CAACK,GAAOC,CAAQ,IAAIN,EAA6C,IAAI,GACrE,CAACO,CAAW,IAAIP,EAA4B,MAAM;AACtD,QAAI,CAACZ,EAAW,QAAO,CAAA;AAEvB,UAAMoB,IAAoBvB,EAAA,GACpBwB,IAAoB,IAAID,EAAA;AAE9B,WAAAC,EAAkB,aAAapB,GAC3BG,QAA4B,WAAWA,IAC3CiB,EAAkB,iBAAiBnB,GACnCmB,EAAkB,OAAOlB,GACzBkB,EAAkB,kBAAkBhB,GAEpCgB,EAAkB,UAAU,MAAM;AAChC,MAAAV,EAAa,EAAI,GACjBK,EAAS,EAAK,GACdV,IAAA;AAAA,IAAU,GAEZe,EAAkB,QAAQ,MAAM;AAC9B,MAAAV,EAAa,EAAK,GAClBJ,IAAA;AAAA,IAAQ,GAEVc,EAAkB,UAAU,CAACC,MAAU;AACrC,MAAAJ,EAASI,CAAK,GACdX,EAAa,EAAK,GAClBH,IAAUc,CAAK;AAAA,IAAA,GAEjBD,EAAkB,WAAW,CAACC,MAAU;AACtC,YAAMC,IAAgBD,EAAM,QAAQA,EAAM,WAAW,GAC/C,EAAE,YAAAT,MAAeU,EAAc,CAAC;AAEtC,MAAAT,EAAcD,CAAU,GACxBK,EAAS,IAAI,GACbT,IAAWa,CAAK;AAAA,IAAA,GAElBD,EAAkB,QAAQ,MAAM;AAC9B,MAAAV,EAAa,EAAK,GAClBU,EAAkB,OAAOlB;AAAA,IAAA,GAGpBkB;AAAA,EAAA,CACR;AAED,EAAAG,EAAU,MAAM,MAAML,EAAY,KAAA,GAAQ,CAAA,CAAE;AAE5C,QAAMM,IAAQ,MAAMN,EAAY,MAAA,GAC1BO,IAAO,MAAMP,EAAY,KAAA;AAO/B,SAAO;AAAA,IACL,WAAAnB;AAAA,IACA,YAAAa;AAAA,IACA,aAAAM;AAAA,IACA,OAAAJ;AAAA,IACA,WAAAL;AAAA,IACA,OAAAO;AAAA,IACA,OAAAQ;AAAA,IACA,MAAAC;AAAA,IACA,QAda,CAACC,IAAQ,CAACjB,MAAc;AACrC,UAAIiB,UAAcF,EAAA;AAClB,MAAAC,EAAA;AAAA,IAAK;AAAA,EAYL;AAEJ;"}
1
+ {"version":3,"file":"useSpeechRecognition.mjs","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 return 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":";AA8CO,MAAMA,IAAuB,MAClC,QAAQ,qBAAqB,QAAQ,yBAwB1BC,IAAuB,CAClCC,IAAuC,OACR;AAC/B,QAAMC,IAAY,OAAO,SAAW,OAAe,CAAC,CAACH,EAAA,GAE/C;AAAA,IACJ,YAAAI,IAAa;AAAA,IACb,gBAAAC,IAAiB;AAAA,IACjB,UAAAC,IAAW;AAAA,IACX,UAAAC;AAAA,IACA,iBAAAC,IAAkB;AAAA,IAClB,SAAAC;AAAA,IACA,OAAAC;AAAA,IACA,SAAAC;AAAA,IACA,UAAAC;AAAA,EAAA,IACEV,GAEE,CAACW,GAAWC,CAAY,IAAIC,EAAS,EAAK,GAC1C,CAACC,GAAYC,CAAa,IAAIF,EAAS,EAAE,GACzC,CAACG,GAAOC,CAAQ,IAAIJ,EAAS,EAAK,GAClC,CAACK,GAAOC,CAAQ,IAAIN,EAA6C,IAAI,GACrE,CAACO,CAAW,IAAIP,EAAwC,MAAM;AAClE,QAAI,CAACZ,EAAW;AAEhB,UAAMoB,IAAoBvB,EAAA,GACpBwB,IAAoB,IAAID,EAAA;AAE9B,WAAAC,EAAkB,aAAapB,GAC3BG,QAA4B,WAAWA,IAC3CiB,EAAkB,iBAAiBnB,GACnCmB,EAAkB,OAAOlB,GACzBkB,EAAkB,kBAAkBhB,GAEpCgB,EAAkB,UAAU,MAAM;AAChC,MAAAV,EAAa,EAAI,GACjBK,EAAS,EAAK,GACdV,IAAA;AAAA,IAAU,GAEZe,EAAkB,UAAU,CAACC,MAAU;AACrC,MAAAJ,EAASI,CAAK,GACdX,EAAa,EAAK,GAClBH,IAAUc,CAAK;AAAA,IAAA,GAEjBD,EAAkB,WAAW,CAACC,MAAU;AACtC,YAAMC,IAAgBD,EAAM,QAAQA,EAAM,WAAW,GAC/C,EAAE,YAAAT,MAAeU,EAAc,CAAC;AAEtC,MAAAZ,EAAa,EAAK,GAClBG,EAAcD,CAAU,GACxBK,EAAS,IAAI,GACbT,IAAWa,CAAK;AAAA,IAAA,GAElBD,EAAkB,QAAQ,MAAM;AAC9B,MAAAV,EAAa,EAAK,GAClBJ,IAAA,GACAc,EAAkB,OAAOlB;AAAA,IAAA,GAGpBkB;AAAA,EAAA,CACR;AAED,EAAAG,EAAU,MAAM,MAAML,GAAa,KAAA,GAAQ,CAAA,CAAE;AAE7C,QAAMM,IAAQ,MAAMN,GAAa,MAAA,GAC3BO,IAAO,MAAMP,GAAa,KAAA;AAOhC,SAAO;AAAA,IACL,WAAAnB;AAAA,IACA,YAAAa;AAAA,IACA,aAAAM;AAAA,IACA,OAAAJ;AAAA,IACA,WAAAL;AAAA,IACA,OAAAO;AAAA,IACA,OAAAQ;AAAA,IACA,MAAAC;AAAA,IACA,QAda,CAACC,IAAQ,CAACjB,MACnBiB,IAAcF,EAAA,IACXC,EAAA;AAAA,EAYP;AAEJ;"}
@@ -1,58 +1,53 @@
1
- import { useState as H, useRef as y, useEffect as x } from "react";
1
+ import { useState as y, useRef as v, useEffect as R } from "react";
2
2
  import { useRefState as V } from "../useRefState/useRefState.mjs";
3
3
  import { isTarget as f } from "../../utils/helpers/isTarget.mjs";
4
- const d = ((...i) => {
5
- const t = f(i[0]) ? i[0] : void 0, r = t ? i[1] : typeof i[0] == "string" ? { initialValue: i[0] } : i[0], [a, c] = H(r?.initialValue ?? ""), o = V(), u = y(null), s = () => {
6
- const e = u.current;
4
+ const p = ((...t) => {
5
+ const n = f(t[0]) ? t[0] : void 0, o = n ? typeof t[1] == "object" ? t[1] : { initialValue: t[1] } : typeof t[0] == "object" ? t[0] : { initialValue: t[0] }, [g, h] = y(o?.initialValue ?? ""), s = V(), l = v(null), m = v(0), a = () => {
6
+ const e = l.current;
7
7
  if (!e) return;
8
- const n = e.style.minHeight, l = e.style.maxHeight;
8
+ const i = e.style.minHeight, u = e.style.maxHeight;
9
9
  e.style.height = "auto", e.style.minHeight = "auto", e.style.maxHeight = "none";
10
- const g = e.scrollHeight;
11
- e.style.height = `${g}px`, e.style.minHeight = n, e.style.maxHeight = l, r?.onResize?.();
10
+ const r = e.scrollHeight;
11
+ e.style.height = `${r}px`, e.style.minHeight = i, e.style.maxHeight = u, r !== m.current && o?.onResize?.(), m.current = r;
12
+ }, c = (e) => {
13
+ h(e);
14
+ const i = l.current;
15
+ i && (i.value = e, requestAnimationFrame(() => {
16
+ a();
17
+ }));
12
18
  };
13
- x(() => {
14
- if (!t && !o.state) return;
15
- const e = t ? f.getElement(t) : o.current;
19
+ R(() => {
20
+ if (!n && !s.state) return;
21
+ const e = n ? f.getElement(n) : s.current;
16
22
  if (!e) return;
17
- u.current = e, r?.initialValue && (e.value = r.initialValue), s();
18
- const n = (g) => {
19
- const v = g.target.value;
20
- c(v), requestAnimationFrame(() => {
21
- s();
23
+ l.current = e, o?.initialValue && (e.value = o.initialValue), a();
24
+ const i = (r) => {
25
+ const H = r.target.value;
26
+ c(H), requestAnimationFrame(() => {
27
+ a();
22
28
  });
23
- }, l = () => {
29
+ }, u = () => {
24
30
  requestAnimationFrame(() => {
25
- s();
31
+ a();
26
32
  });
27
33
  };
28
- return e.addEventListener("input", n), e.addEventListener("resize", l), () => {
29
- e.removeEventListener("input", n), e.removeEventListener("resize", l);
34
+ return e.addEventListener("input", i), e.addEventListener("resize", u), () => {
35
+ e.removeEventListener("input", i), e.removeEventListener("resize", u);
30
36
  };
31
- }, [t, o.state, f.getRefState(t), r?.initialValue]), x(() => {
32
- const e = u.current;
33
- e && (e.value = a, requestAnimationFrame(() => {
34
- s();
35
- }));
36
- }, [a]);
37
- const m = (e) => {
38
- c(e);
39
- const n = u.current;
40
- n && (n.value = e, requestAnimationFrame(() => {
41
- s();
42
- }));
43
- }, h = () => c("");
44
- return t ? {
45
- value: a,
46
- setValue: m,
47
- clear: h
37
+ }, [n, s.state, f.getRefState(n)]);
38
+ const x = () => h("");
39
+ return n ? {
40
+ value: g,
41
+ set: c,
42
+ clear: x
48
43
  } : {
49
- ref: o,
50
- value: a,
51
- setValue: m,
52
- clear: h
44
+ ref: s,
45
+ value: g,
46
+ set: c,
47
+ clear: x
53
48
  };
54
49
  });
55
50
  export {
56
- d as useTextareaAutosize
51
+ p as useTextareaAutosize
57
52
  };
58
53
  //# sourceMappingURL=useTextareaAutosize.mjs.map