|
| 1 | +import React, { useState, cloneElement } from 'react'; |
| 2 | +import PropTypes from 'prop-types'; |
| 3 | +import WizardStep from './wizard/wizard-step'; |
| 4 | +import Grid from '@material-ui/core/Grid'; |
| 5 | +import Typography from '@material-ui/core/Typography'; |
| 6 | +import { useFormApi } from '@data-driven-forms/react-form-renderer'; |
| 7 | + |
| 8 | +const Wizard = ({ fields, title, description }) => { |
| 9 | + const [activeStep, setActiveStep] = useState(fields[0].name); |
| 10 | + const [prevSteps, setPrevSteps] = useState([]); |
| 11 | + |
| 12 | + const formOptions = useFormApi(); |
| 13 | + |
| 14 | + const handleNext = (nextStep) => { |
| 15 | + setPrevSteps([...prevSteps, activeStep]); |
| 16 | + setActiveStep(nextStep); |
| 17 | + }; |
| 18 | + |
| 19 | + const handlePrev = () => { |
| 20 | + setActiveStep(prevSteps[prevSteps.length - 1]); |
| 21 | + |
| 22 | + const newSteps = prevSteps; |
| 23 | + newSteps.pop(); |
| 24 | + setPrevSteps(newSteps); |
| 25 | + }; |
| 26 | + |
| 27 | + const findCurrentStep = (activeStep) => fields.find(({ name }) => name === activeStep); |
| 28 | + |
| 29 | + const findActiveFields = (visitedSteps) => |
| 30 | + visitedSteps.map((key) => findCurrentStep(key).fields.map(({ name }) => name)).reduce((acc, curr) => curr.concat(acc.map((item) => item)), []); |
| 31 | + |
| 32 | + const getValues = (values, visitedSteps) => |
| 33 | + Object.keys(values) |
| 34 | + .filter((key) => findActiveFields(visitedSteps).includes(key)) |
| 35 | + .reduce((acc, curr) => ({ ...acc, [curr]: values[curr] }), {}); |
| 36 | + |
| 37 | + const handleSubmit = () => formOptions.onSubmit(getValues(formOptions.getState().values, [...prevSteps, activeStep])); |
| 38 | + |
| 39 | + const currentStep = ( |
| 40 | + <WizardStep |
| 41 | + {...findCurrentStep(activeStep)} |
| 42 | + formOptions={{ |
| 43 | + ...formOptions, |
| 44 | + handleSubmit |
| 45 | + }} |
| 46 | + /> |
| 47 | + ); |
| 48 | + |
| 49 | + return ( |
| 50 | + <Grid container spacing={6}> |
| 51 | + <Grid item xs={12}> |
| 52 | + <Typography component="h3">{title}</Typography> |
| 53 | + <Typography paragraph>{description}</Typography> |
| 54 | + <Typography component="h5">{`Step ${prevSteps.length + 1}`}</Typography> |
| 55 | + </Grid> |
| 56 | + <Grid item xs={12}> |
| 57 | + {cloneElement(currentStep, { |
| 58 | + handleNext, |
| 59 | + handlePrev, |
| 60 | + disableBack: prevSteps.length === 0 |
| 61 | + })} |
| 62 | + </Grid> |
| 63 | + </Grid> |
| 64 | + ); |
| 65 | +}; |
| 66 | + |
| 67 | +Wizard.propTypes = { |
| 68 | + title: PropTypes.node, |
| 69 | + description: PropTypes.node, |
| 70 | + fields: PropTypes.arrayOf( |
| 71 | + PropTypes.shape({ |
| 72 | + name: PropTypes.string |
| 73 | + }) |
| 74 | + ).isRequired |
| 75 | +}; |
| 76 | + |
| 77 | +export default Wizard; |
0 commit comments