Files
sign/packages/ui/primitives/stepper.tsx

86 lines
2.2 KiB
TypeScript
Raw Normal View History

2023-12-03 01:15:59 -05:00
import React, { createContext, useContext, useEffect, useState } from 'react';
2023-12-02 22:30:10 -05:00
import type { FC } from 'react';
2023-12-03 01:15:59 -05:00
type StepContextType = {
stepIndex: number;
currentStep: number;
totalSteps: number;
isFirst: boolean;
isLast: boolean;
nextStep: () => void;
previousStep: () => void;
2023-12-02 22:30:10 -05:00
};
2023-12-03 01:15:59 -05:00
const StepContext = createContext<StepContextType | null>(null);
2023-12-02 22:30:10 -05:00
type StepperProps = {
children: React.ReactNode;
onComplete?: () => void;
onStepChanged?: (currentStep: number) => void;
2023-12-03 01:15:59 -05:00
currentStep?: number; // external control prop
setCurrentStep?: (step: number) => void; // external control function
2023-12-02 22:30:10 -05:00
};
export const Stepper: FC<StepperProps> = ({
children,
onComplete,
onStepChanged,
currentStep: propCurrentStep,
setCurrentStep: propSetCurrentStep,
}) => {
const [stateCurrentStep, stateSetCurrentStep] = useState(1);
// Determine if props are provided, otherwise use state
const isControlled = propCurrentStep !== undefined && propSetCurrentStep !== undefined;
const currentStep = isControlled ? propCurrentStep : stateCurrentStep;
const setCurrentStep = isControlled ? propSetCurrentStep : stateSetCurrentStep;
const totalSteps = React.Children.count(children);
const nextStep = () => {
if (currentStep < totalSteps) {
setCurrentStep(currentStep + 1);
} else {
onComplete && onComplete();
}
};
const previousStep = () => {
if (currentStep > 1) {
setCurrentStep(currentStep - 1);
}
};
useEffect(() => {
onStepChanged && onStepChanged(currentStep);
}, [currentStep, onStepChanged]);
2023-12-03 01:15:59 -05:00
// Empty stepper
2023-12-03 11:21:51 -05:00
if (totalSteps === 0) {
return null;
}
2023-12-03 01:15:59 -05:00
const currentChild = React.Children.toArray(children)[currentStep - 1];
const stepContextValue: StepContextType = {
2023-12-02 23:56:07 -05:00
stepIndex: currentStep - 1,
2023-12-02 22:30:10 -05:00
currentStep,
totalSteps,
isFirst: currentStep === 1,
isLast: currentStep === totalSteps,
nextStep,
previousStep,
2023-12-03 01:15:59 -05:00
};
2023-12-02 23:56:07 -05:00
2023-12-03 01:15:59 -05:00
return <StepContext.Provider value={stepContextValue}>{currentChild}</StepContext.Provider>;
};
2023-12-02 22:30:10 -05:00
2023-12-03 01:15:59 -05:00
/** Hook for children to use the step context */
export const useStep = (): StepContextType => {
const context = useContext(StepContext);
2023-12-03 11:21:51 -05:00
if (!context) {
throw new Error('useStep must be used within a Stepper');
}
2023-12-03 01:15:59 -05:00
return context;
2023-12-02 22:30:10 -05:00
};