UNPKG

@modern-kit/react

Version:
84 lines (80 loc) 2.13 kB
'use strict'; var React = require('react'); var utils = require('@modern-kit/utils'); function useStep({ maxStep, initialStep = 0, infinite = false }) { const [currentStep, setCurrentStep] = React.useState(initialStep); const hasNextStep = currentStep < maxStep; const hasPrevStep = currentStep > 0; const getNextStep = React.useCallback( (type, isOverflow) => { const isNextStepType = type === "nextStep"; if (isOverflow) { return isNextStepType ? 0 : maxStep; } return isNextStepType ? currentStep + 1 : currentStep - 1; }, [maxStep, currentStep] ); const handleStep = React.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 = React.useCallback( (action) => { handleStep("nextStep", !hasNextStep, action); }, [hasNextStep, handleStep] ); const goToPrevStep = React.useCallback( (action) => { handleStep("prevStep", !hasPrevStep, action); }, [hasPrevStep, handleStep] ); const setStep = React.useCallback( (step, action) => { const nextStep = utils.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 = React.useCallback( (action) => { if (action) { action({ prev: currentStep, next: initialStep }); } setCurrentStep(initialStep); }, [currentStep, initialStep] ); return { currentStep, hasNextStep, hasPrevStep, goToNextStep, goToPrevStep, setStep, resetStep }; } exports.useStep = useStep; //# sourceMappingURL=index.cjs.map