{"version":3,"file":"use-state-history.mjs","names":[],"sources":["../../src/use-state-history/use-state-history.ts"],"sourcesContent":["import { useCallback, useMemo, useState } from 'react';\n\nexport interface UseStateHistoryHandlers<T> {\n  set: (value: T) => void;\n  back: (steps?: number) => void;\n  forward: (steps?: number) => void;\n  reset: () => void;\n}\n\nexport interface UseStateHistoryValue<T> {\n  history: T[];\n  current: number;\n}\n\nexport type UseStateHistoryReturnValue<T> = [\n  T,\n  UseStateHistoryHandlers<T>,\n  UseStateHistoryValue<T>,\n];\n\nexport function useStateHistory<T>(initialValue: T): UseStateHistoryReturnValue<T> {\n  const [state, setState] = useState<UseStateHistoryValue<T>>({\n    history: [initialValue],\n    current: 0,\n  });\n\n  const set = useCallback(\n    (val: T) =>\n      setState((currentState) => {\n        const nextState = [...currentState.history.slice(0, currentState.current + 1), val];\n        return {\n          history: nextState,\n          current: nextState.length - 1,\n        };\n      }),\n    []\n  );\n\n  const back = useCallback(\n    (steps = 1) =>\n      setState((currentState) => ({\n        history: currentState.history,\n        current: Math.max(0, currentState.current - steps),\n      })),\n    []\n  );\n\n  const forward = useCallback(\n    (steps = 1) =>\n      setState((currentState) => ({\n        history: currentState.history,\n        current: Math.min(currentState.history.length - 1, currentState.current + steps),\n      })),\n    []\n  );\n\n  const reset = useCallback(() => {\n    setState({ history: [initialValue], current: 0 });\n  }, [initialValue]);\n\n  const handlers = useMemo(() => ({ back, forward, reset, set }), [back, forward, reset, set]);\n\n  return [state.history[state.current], handlers, state];\n}\n\nexport namespace useStateHistory {\n  export type Handlers<T> = UseStateHistoryHandlers<T>;\n  export type Value<T> = UseStateHistoryValue<T>;\n  export type ReturnValue<T> = UseStateHistoryReturnValue<T>;\n}\n"],"mappings":";;;AAoBA,SAAgB,gBAAmB,cAAgD;CACjF,MAAM,CAAC,OAAO,YAAY,SAAkC;EAC1D,SAAS,CAAC,YAAY;EACtB,SAAS;CACX,CAAC;CAED,MAAM,MAAM,aACT,QACC,UAAU,iBAAiB;EACzB,MAAM,YAAY,CAAC,GAAG,aAAa,QAAQ,MAAM,GAAG,aAAa,UAAU,CAAC,GAAG,GAAG;EAClF,OAAO;GACL,SAAS;GACT,SAAS,UAAU,SAAS;EAC9B;CACF,CAAC,GACH,CAAC,CACH;CAEA,MAAM,OAAO,aACV,QAAQ,MACP,UAAU,kBAAkB;EAC1B,SAAS,aAAa;EACtB,SAAS,KAAK,IAAI,GAAG,aAAa,UAAU,KAAK;CACnD,EAAE,GACJ,CAAC,CACH;CAEA,MAAM,UAAU,aACb,QAAQ,MACP,UAAU,kBAAkB;EAC1B,SAAS,aAAa;EACtB,SAAS,KAAK,IAAI,aAAa,QAAQ,SAAS,GAAG,aAAa,UAAU,KAAK;CACjF,EAAE,GACJ,CAAC,CACH;CAEA,MAAM,QAAQ,kBAAkB;EAC9B,SAAS;GAAE,SAAS,CAAC,YAAY;GAAG,SAAS;EAAE,CAAC;CAClD,GAAG,CAAC,YAAY,CAAC;CAEjB,MAAM,WAAW,eAAe;EAAE;EAAM;EAAS;EAAO;CAAI,IAAI;EAAC;EAAM;EAAS;EAAO;CAAG,CAAC;CAE3F,OAAO;EAAC,MAAM,QAAQ,MAAM;EAAU;EAAU;CAAK;AACvD"}