forked from Nova-reward/Nova-Rewards
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMultiStepForm.js
More file actions
203 lines (186 loc) · 6.5 KB
/
Copy pathMultiStepForm.js
File metadata and controls
203 lines (186 loc) · 6.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
'use client';
import { useState, useCallback, useEffect } from 'react';
import { useRouter } from 'next/router';
/**
* Generic multi-step form component.
*
* Props:
* steps — array of { title, fields: (data) => JSX, validate: (data) => errors{} }
* initialData — initial form data object
* storageKey — localStorage key for progress persistence (optional)
* onSubmit — async (data) => void called on final submission
* renderSummary — (data) => JSX custom summary view (optional)
* urlParamKey — URL search param name to persist step index (optional, e.g. 'step')
*/
export default function MultiStepForm({
steps,
initialData = {},
storageKey,
onSubmit,
renderSummary,
urlParamKey,
}) {
const REVIEW_INDEX = steps.length;
const router = useRouter();
// Resolve initial step from URL param if provided
const getInitialStep = () => {
if (urlParamKey && typeof window !== 'undefined') {
const params = new URLSearchParams(window.location.search);
const s = parseInt(params.get(urlParamKey), 10);
if (!isNaN(s) && s >= 0 && s <= REVIEW_INDEX) return s;
}
return 0;
};
const [current, setCurrent] = useState(getInitialStep);
const [data, setData] = useState(() => {
if (storageKey && typeof window !== 'undefined') {
try {
const saved = localStorage.getItem(storageKey);
if (saved) return { ...initialData, ...JSON.parse(saved) };
} catch { /* ignore */ }
}
return initialData;
});
const [errors, setErrors] = useState({});
const [submitting, setSubmitting] = useState(false);
const [submitError, setSubmitError] = useState('');
const [liveMessage, setLiveMessage] = useState('');
const [done, setDone] = useState(false);
// Sync step to URL param
useEffect(() => {
if (!urlParamKey || done) return;
const params = new URLSearchParams(window.location.search);
params.set(urlParamKey, String(current));
const newUrl = `${window.location.pathname}?${params.toString()}`;
window.history.replaceState(null, '', newUrl);
}, [current, urlParamKey, done]);
// Persist form data to localStorage
useEffect(() => {
if (!storageKey || done) return;
try { localStorage.setItem(storageKey, JSON.stringify(data)); } catch { /* ignore */ }
}, [data, storageKey, done]);
const update = useCallback((field, value) => {
setData((d) => ({ ...d, [field]: value }));
setErrors((e) => { const n = { ...e }; delete n[field]; return n; });
}, []);
const validateCurrent = useCallback(() => {
if (current === REVIEW_INDEX) return true;
const errs = steps[current].validate?.(data) ?? {};
setErrors(errs);
if (Object.keys(errs).length > 0) {
setLiveMessage('Please fix the highlighted errors before continuing.');
} else {
setLiveMessage('');
}
return Object.keys(errs).length === 0;
}, [current, data, steps, REVIEW_INDEX]);
const next = useCallback(() => {
if (!validateCurrent()) return;
setCurrent((c) => c + 1);
setErrors({});
setLiveMessage('');
}, [validateCurrent]);
const prev = useCallback(() => {
setCurrent((c) => c - 1);
setErrors({});
setLiveMessage('');
}, []);
const handleSubmit = useCallback(async () => {
setSubmitError('');
setSubmitting(true);
try {
await onSubmit(data);
if (storageKey) localStorage.removeItem(storageKey);
if (urlParamKey) {
const params = new URLSearchParams(window.location.search);
params.delete(urlParamKey);
window.history.replaceState(null, '', `${window.location.pathname}?${params.toString()}`);
}
setDone(true);
} catch (err) {
const message = err.message || 'Submission failed. Please try again.';
setSubmitError(message);
setLiveMessage(message);
} finally {
setSubmitting(false);
}
}, [data, onSubmit, storageKey, urlParamKey]);
if (done) {
return (
<div className="msf-done">
<span className="msf-done-icon">✅</span>
<p>Submitted successfully!</p>
</div>
);
}
const isReview = current === REVIEW_INDEX;
const totalSteps = steps.length;
return (
<div className="msf">
<div role="status" aria-live="polite" aria-atomic="true" style={{ position: 'absolute', width: 1, height: 1, padding: 0, margin: -1, overflow: 'hidden', clip: 'rect(0, 0, 0, 0)', whiteSpace: 'nowrap', border: 0 }}>
{liveMessage}
</div>
{/* Step indicator */}
<div className="msf-indicator" role="list">
{steps.map((step, i) => (
<div
key={i}
role="listitem"
className={`msf-step ${i < current ? 'msf-step-done' : ''} ${i === current ? 'msf-step-active' : ''}`}
>
<div className="msf-step-circle">
{i < current ? '✓' : i + 1}
</div>
<span className="msf-step-label">{step.title}</span>
{i < totalSteps - 1 && <div className="msf-step-line" />}
</div>
))}
</div>
{/* Step content */}
<div className="msf-body">
{isReview ? (
<div className="msf-review">
<h3 className="msf-review-title">Review your details</h3>
{renderSummary ? renderSummary(data) : <DefaultSummary data={data} />}
{submitError && <p className="error" style={{ marginTop: '1rem' }}>{submitError}</p>}
</div>
) : (
<div className="msf-fields">
<h3 className="msf-step-title">{steps[current].title}</h3>
{steps[current].fields(data, update, errors)}
</div>
)}
</div>
{/* Navigation */}
<div className="msf-nav">
{current > 0 && (
<button className="btn btn-secondary" onClick={prev} disabled={submitting}>
← Previous
</button>
)}
<div style={{ flex: 1 }} />
{isReview ? (
<button className="btn btn-primary" onClick={handleSubmit} disabled={submitting}>
{submitting ? 'Submitting…' : 'Submit'}
</button>
) : (
<button className="btn btn-primary" onClick={next}>
{current === totalSteps - 1 ? 'Review →' : 'Next →'}
</button>
)}
</div>
</div>
);
}
function DefaultSummary({ data }) {
return (
<dl className="msf-summary-list">
{Object.entries(data).map(([k, v]) => (
<div key={k} className="msf-summary-row">
<dt>{k}</dt>
<dd>{String(v ?? '—')}</dd>
</div>
))}
</dl>
);
}