{"version":3,"sources":["../../src/useStateController/useStateController.ts"],"names":["useCallback","useMemo","useState","useStateController","valueProp","defaultValue","onChange","shouldUpdate","prev","next","valueState","setValue","isControlled","value","updateValue","nextValue","useStateController_default"],"mappings":"8BAAA,OAAS,eAAAA,EAAkC,WAAAC,MAAe,QAE1D,OAAOC,MAAc,yCAGrB,MAAMC,EAAqB,CAAI,CAC7B,MAAOC,EACP,aAAAC,EACA,SAAAC,EACA,aAAAC,EAAe,CAACC,EAAMC,IAASD,IAASC,CAC1C,IAAkE,CAChE,KAAM,CAACC,EAAYC,CAAQ,EAAIT,EAAYG,CAAY,EAEjDO,EAAeR,IAAc,OAE7BS,EAAQZ,EACZ,IAAOW,EAAeR,EAAYM,EAClC,CAACA,EAAYN,EAAWQ,CAAY,CACtC,EAEME,EAAcd,EACjBS,GAA4B,CAC3B,MAAMM,EAAa,OAAON,GAAS,WAAcA,EAAyBI,CAAK,EAAIJ,EAE9EF,EAAaM,EAAOE,CAAS,IAI7BH,GACHD,EAASI,CAAS,EAGpBT,GAAA,MAAAA,EAAWS,GACb,EACA,CAACF,EAAON,EAAcK,EAAcN,CAAQ,CAC9C,EAEA,MAAO,CAACO,EAAOC,CAAW,CAC5B,EAEA,IAAOE,EAAQb","sourcesContent":["import { useCallback, type SetStateAction, useMemo } from 'react';\nimport type { GeneralFunction } from '@asherng/common-types';\nimport useState from '../useStateIfMounted/useStateIfMounted';\nimport type { UseStateControllerParams, UseStateControllerResponse } from './types';\n\nconst useStateController = <T>({\n  value: valueProp,\n  defaultValue,\n  onChange,\n  shouldUpdate = (prev, next) => prev !== next\n}: UseStateControllerParams<T>): UseStateControllerResponse<T> => {\n  const [valueState, setValue] = useState<T>(defaultValue);\n\n  const isControlled = valueProp !== undefined;\n\n  const value = useMemo(\n    () => (isControlled ? valueProp : valueState),\n    [valueState, valueProp, isControlled]\n  );\n\n  const updateValue = useCallback(\n    (next: SetStateAction<T>) => {\n      const nextValue = (typeof next === 'function' ? (next as GeneralFunction)(value) : next) as T;\n\n      if (!shouldUpdate(value, nextValue)) {\n        return;\n      }\n\n      if (!isControlled) {\n        setValue(nextValue);\n      }\n\n      onChange?.(nextValue);\n    },\n    [value, shouldUpdate, isControlled, onChange]\n  );\n\n  return [value, updateValue] as UseStateControllerResponse<T>;\n};\n\nexport default useStateController;\n"]}