UNPKG

@modern-kit/react

Version:
82 lines (79 loc) 2.09 kB
import { useState, useCallback } from 'react'; import { isFunction } from '@modern-kit/utils'; function useStep({ maxStep, initialStep = 0, infinite = false }) { const [currentStep, setCurrentStep] = useState(initialStep); const hasNextStep = currentStep < maxStep; const hasPrevStep = currentStep > 0; const getNextStep = useCallback( (type, isOverflow) => { const isNextStepType = type === "nextStep"; if (isOverflow) { return isNextStepType ? 0 : maxStep; } return isNextStepType ? currentStep + 1 : currentStep - 1; }, [maxStep, currentStep] ); const handleStep = useCallback( (type, isOverflow, action) => { if (isOverflow && !infinite) return; const nextStep = getNextStep(type, isOverflow); if (action) { action({ prev: currentStep, next: nextStep }); } setCurrentStep(nextStep); }, [infinite, currentStep, getNextStep] ); const goToNextStep = useCallback( (action) => { handleStep("nextStep", !hasNextStep, action); }, [hasNextStep, handleStep] ); const goToPrevStep = useCallback( (action) => { handleStep("prevStep", !hasPrevStep, action); }, [hasPrevStep, handleStep] ); const setStep = useCallback( (step, action) => { const nextStep = isFunction(step) ? step(currentStep) : step; const isValidNextStep = nextStep >= 0 && nextStep <= maxStep; if (isValidNextStep) { if (action) { action({ prev: currentStep, next: nextStep }); } setCurrentStep(step); return; } throw new Error("Step not valid"); }, [currentStep, maxStep] ); const resetStep = useCallback( (action) => { if (action) { action({ prev: currentStep, next: initialStep }); } setCurrentStep(initialStep); }, [currentStep, initialStep] ); return { currentStep, hasNextStep, hasPrevStep, goToNextStep, goToPrevStep, setStep, resetStep }; } export { useStep }; //# sourceMappingURL=index.mjs.map