mirror of
https://github.com/shishantbiswas/bknd.git
synced 2026-03-16 12:37:20 +00:00
public commit
This commit is contained in:
67
app/src/ui/components/steps/Steps.tsx
Normal file
67
app/src/ui/components/steps/Steps.tsx
Normal file
@@ -0,0 +1,67 @@
|
||||
import {
|
||||
Children,
|
||||
type Dispatch,
|
||||
type SetStateAction,
|
||||
createContext,
|
||||
useContext,
|
||||
useState
|
||||
} from "react";
|
||||
|
||||
export type TStepsProps = {
|
||||
children: any;
|
||||
initialPath?: string[];
|
||||
lastBack?: () => void;
|
||||
[key: string]: any;
|
||||
};
|
||||
|
||||
type TStepContext<T = any> = {
|
||||
nextStep: (step: string) => () => void;
|
||||
stepBack: () => void;
|
||||
close: () => void;
|
||||
state: T;
|
||||
setState: Dispatch<SetStateAction<T>>;
|
||||
};
|
||||
|
||||
const StepContext = createContext<TStepContext>(undefined as any);
|
||||
|
||||
export function Steps({ children, initialPath = [], lastBack }: TStepsProps) {
|
||||
const [state, setState] = useState<any>({});
|
||||
const [path, setPath] = useState<string[]>(initialPath);
|
||||
const steps: any[] = Children.toArray(children).filter(
|
||||
(child: any) => child.props.disabled !== true
|
||||
);
|
||||
|
||||
function stepBack() {
|
||||
if (path.length === 0) {
|
||||
lastBack?.();
|
||||
} else {
|
||||
setPath((prev) => prev.slice(0, -1));
|
||||
}
|
||||
}
|
||||
|
||||
const nextStep = (step: string) => () => {
|
||||
setPath((prev) => [...prev, step]);
|
||||
};
|
||||
|
||||
const current = steps.find((step) => step.props.id === path[path.length - 1]) || steps[0];
|
||||
|
||||
return (
|
||||
<StepContext.Provider value={{ nextStep, stepBack, state, setState, close: lastBack! }}>
|
||||
{current}
|
||||
</StepContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useStepContext<T = any>(): TStepContext<T> {
|
||||
return useContext(StepContext);
|
||||
}
|
||||
|
||||
export function Step({
|
||||
children,
|
||||
disabled = false,
|
||||
path = [],
|
||||
id,
|
||||
...rest
|
||||
}: { children: React.ReactNode; disabled?: boolean; id: string; path?: string[] }) {
|
||||
return <div {...rest}>{children}</div>;
|
||||
}
|
||||
Reference in New Issue
Block a user