UNPKG

@mantine/hooks

Version:

A collection of 50+ hooks for state and UI management

1 lines 2.22 kB
{"version":3,"file":"use-counter.mjs","names":[],"sources":["../../src/use-counter/use-counter.ts"],"sourcesContent":["import { useCallback, useState } from 'react';\nimport { clamp } from '../utils';\n\nconst DEFAULT_OPTIONS = {\n min: -Infinity,\n max: Infinity,\n};\n\nexport interface UseCounterOptions {\n min?: number;\n max?: number;\n step?: number;\n}\n\nexport interface UseCounterHandlers {\n increment: () => void;\n decrement: () => void;\n set: (value: number) => void;\n reset: () => void;\n}\n\nexport type UseCounterReturnValue = [number, UseCounterHandlers];\n\nexport function useCounter(initialValue = 0, options?: UseCounterOptions): UseCounterReturnValue {\n const { min, max, step: _step = 1 } = { ...DEFAULT_OPTIONS, ...options };\n const step = Math.abs(_step);\n const [count, setCount] = useState<number>(clamp(initialValue, min, max));\n\n const increment = useCallback(\n () => setCount((current) => clamp(current + step, min, max)),\n [min, max, step]\n );\n\n const decrement = useCallback(\n () => setCount((current) => clamp(current - step, min, max)),\n [min, max, step]\n );\n\n const set = useCallback((value: number) => setCount(clamp(value, min, max)), [min, max]);\n\n const reset = useCallback(\n () => setCount(clamp(initialValue, min, max)),\n [initialValue, min, max]\n );\n\n return [count, { increment, decrement, set, reset }];\n}\n\nexport namespace useCounter {\n export type Options = UseCounterOptions;\n export type Handlers = UseCounterHandlers;\n export type ReturnValue = UseCounterReturnValue;\n}\n"],"mappings":";;;;AAGA,MAAM,kBAAkB;CACtB,KAAK;CACL,KAAK;AACP;AAiBA,SAAgB,WAAW,eAAe,GAAG,SAAoD;CAC/F,MAAM,EAAE,KAAK,KAAK,MAAM,QAAQ,MAAM;EAAE,GAAG;EAAiB,GAAG;CAAQ;CACvE,MAAM,OAAO,KAAK,IAAI,KAAK;CAC3B,MAAM,CAAC,OAAO,YAAY,SAAiB,MAAM,cAAc,KAAK,GAAG,CAAC;CAmBxE,OAAO,CAAC,OAAO;EAAE,WAjBC,kBACV,UAAU,YAAY,MAAM,UAAU,MAAM,KAAK,GAAG,CAAC,GAC3D;GAAC;GAAK;GAAK;EAAI,CAeQ;EAAG,WAZV,kBACV,UAAU,YAAY,MAAM,UAAU,MAAM,KAAK,GAAG,CAAC,GAC3D;GAAC;GAAK;GAAK;EAAI,CAUmB;EAAG,KAP3B,aAAa,UAAkB,SAAS,MAAM,OAAO,KAAK,GAAG,CAAC,GAAG,CAAC,KAAK,GAAG,CAO7C;EAAG,OAL9B,kBACN,SAAS,MAAM,cAAc,KAAK,GAAG,CAAC,GAC5C;GAAC;GAAc;GAAK;EAAG,CAGuB;CAAE,CAAC;AACrD"}