-
-
Notifications
You must be signed in to change notification settings - Fork 177
/
Copy pathmain.js
385 lines (335 loc) · 13.6 KB
/
main.js
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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Promise from 'promise';
export default class StepZilla extends Component {
constructor(props) {
super(props);
this.state = {
compState: this.props.startAtStep,
navState: this.getNavStates(this.props.startAtStep, this.props.steps.length)
};
this.hidden = {
display: 'none'
};
// if user did not give a custom nextTextOnFinalActionStep, the nextButtonText becomes the default
this.nextTextOnFinalActionStep = (this.props.nextTextOnFinalActionStep) ? this.props.nextTextOnFinalActionStep : this.props.nextButtonText;
this.applyValidationFlagsToSteps();
}
// extend the "steps" array with flags to indicate if they have been validated
applyValidationFlagsToSteps() {
this.props.steps.map((i, idx) => {
if (this.props.dontValidate) {
i.validated = true;
} else {
// check if isValidated was exposed in the step, if yes then set initial state as not validated (false) or vice versa
// if HOCValidation is used for the step then mark it as "requires to be validated. i.e. false"
i.validated = i.component.type && i.component.type.prototype && i.component.type.prototype.isValidated && this.isStepAtIndexHOCValidationBased(idx) ? false : true;
}
return i;
});
}
// update the header nav states via classes so they can be styled via css
getNavStates(indx, length) {
const styles = [];
for (let i = 0; i < length; i++) {
if (i < indx || (!this.props.prevBtnOnLastStep && (indx === length - 1))) {
styles.push('done');
} else if (i === indx) {
styles.push('doing');
} else {
styles.push('todo');
}
}
return { styles };
}
getPrevNextBtnLayout(currentStep) {
// first set default values
let showPreviousBtn = true;
let showNextBtn = true;
let nextStepText = this.props.nextButtonText;
// first step hide previous btn
if (currentStep === 0) {
showPreviousBtn = false;
}
// second to last step change next btn text if supplied as props
if (currentStep === this.props.steps.length - 2) {
nextStepText = this.props.nextTextOnFinalActionStep || nextStepText;
}
// last step hide next btn, hide previous btn if supplied as props
if (currentStep >= this.props.steps.length - 1) {
showNextBtn = false;
showPreviousBtn = this.props.prevBtnOnLastStep === false ? false : true;
}
return {
showPreviousBtn,
showNextBtn,
nextStepText
};
}
// which step are we in?
checkNavState(nextStep) {
if (this.props.onStepChange) {
this.props.onStepChange(nextStep);
}
}
// set the nav state
setNavState(next) {
this.setState({ navState: this.getNavStates(next, this.props.steps.length) });
if (next < this.props.steps.length) {
this.setState({ compState: next });
}
this.checkNavState(next);
}
// handles keydown on enter being pressed in any Child component input area. in this case it goes to the next (ignore textareas as they should allow line breaks)
handleKeyDown(evt) {
if (evt.which === 13) {
if (!this.props.preventEnterSubmission && evt.target.type !== 'textarea') {
this.next();
} else if (evt.target.type !== 'textarea') {
evt.preventDefault();
}
}
}
// this utility method lets Child components invoke a direct jump to another step
jumpToStep(evt) {
if (typeof evt.target === 'undefined') {
// a child step wants to invoke a jump between steps. in this case 'evt' is the numeric step number and not the JS event
this.setNavState(evt);
} else { // the main navigation step ui is invoking a jump between steps
// if stepsNavigation is turned off or user clicked on existing step again (on step 2 and clicked on 2 again) then ignore
if (!this.props.stepsNavigation || evt.target.value === this.state.compState) {
evt.preventDefault();
evt.stopPropagation();
return;
}
// evt is a react event so we need to persist it as we deal with aync promises which nullifies these events (https://facebook.github.io/react/docs/events.html#event-pooling)
evt.persist();
const movingBack = evt.target.value < this.state.compState; // are we trying to move back or front?
let passThroughStepsNotValid = false; // if we are jumping forward, only allow that if inbetween steps are all validated. This flag informs the logic...
let proceed = false; // flag on if we should move on
this.abstractStepMoveAllowedToPromise(movingBack)
.then((valid = true) => {
// validation was a success (promise or sync validation). In it was a Promise's resolve()
// ... then proceed will be undefined, so make it true. Or else 'proceed' will carry the true/false value from sync
proceed = valid;
if (!movingBack) {
this.updateStepValidationFlag(proceed);
}
if (proceed) {
if (!movingBack) {
// looks like we are moving forward, 'reduce' a new array of step>validated values we need to check and
// ... 'some' that to get a decision on if we should allow moving forward
passThroughStepsNotValid = this.props.steps
.reduce((a, c, i) => {
if (i >= this.state.compState && i < evt.target.value) {
a.push(c.validated);
}
return a;
}, [])
.some((c) => {
return c === false;
});
}
}
})
.catch(() => {
// Promise based validation was a fail (i.e reject())
if (!movingBack) {
this.updateStepValidationFlag(false);
}
})
.then(() => {
// this is like finally(), executes if error no no error
if (proceed && !passThroughStepsNotValid) {
if (evt.target.value === (this.props.steps.length - 1)
&& this.state.compState === (this.props.steps.length - 1)) {
this.setNavState(this.props.steps.length);
} else {
this.setNavState(evt.target.value);
}
}
})
.catch(e => {
if (e) {
// see note below called "CatchRethrowing"
// ... plus the finally then() above is what throws the JS Error so we need to catch that here specifically
setTimeout(() => { throw e; });
}
});
}
}
// move next via next button
next() {
this.abstractStepMoveAllowedToPromise()
.then((proceed = true) => {
// validation was a success (promise or sync validation). In it was a Promise's resolve() then proceed will be undefined,
// ... so make it true. Or else 'proceed' will carry the true/false value from sync validation
this.updateStepValidationFlag(proceed);
if (proceed) {
this.setNavState(this.state.compState + 1);
}
})
.catch((e) => {
if (e) {
// CatchRethrowing: as we wrap StepMoveAllowed() to resolve as a Promise, the then() is invoked and the next React Component is loaded.
// ... during the render, if there are JS errors thrown (e.g. ReferenceError) it gets swallowed by the Promise library and comes in here (catch)
// ... so we need to rethrow it outside the execution stack so it behaves like a notmal JS error (i.e. halts and prints to console)
//
setTimeout(() => { throw e; });
}
// Promise based validation was a fail (i.e reject())
this.updateStepValidationFlag(false);
});
}
// move behind via previous button
previous() {
if (this.state.compState > 0) {
this.setNavState(this.state.compState - 1);
}
}
// update step's validation flag
updateStepValidationFlag(val = true) {
this.props.steps[this.state.compState].validated = val; // note: if a step component returns 'underfined' then treat as "true".
}
// are we allowed to move forward? via the next button or via jumpToStep?
stepMoveAllowed(skipValidationExecution = false) {
let proceed = false;
if (this.props.dontValidate) {
proceed = true;
} else {
if (skipValidationExecution) {
// we are moving backwards in steps, in this case dont validate as it means the user is not commiting to "save"
proceed = true;
} else if (this.isStepAtIndexHOCValidationBased(this.state.compState)) {
// the user is using a higer order component (HOC) for validation (e.g react-validation-mixin), this wraps the StepZilla steps as a HOC,
// so use hocValidationAppliedTo to determine if this step needs the aync validation as per react-validation-mixin interface
proceed = this.refs.activeComponent.refs.component.isValidated();
} else if (Object.keys(this.refs).length === 0 || typeof this.refs.activeComponent.isValidated === 'undefined') {
// if its a form component, it should have implemeted a public isValidated class (also pure componenets wont even have refs - i.e. a empty object). If not then continue
proceed = true;
} else {
// user is moving forward in steps, invoke validation as its available
proceed = this.refs.activeComponent.isValidated();
}
}
return proceed;
}
isStepAtIndexHOCValidationBased(stepIndex) {
return (this.props.hocValidationAppliedTo.length > 0 && this.props.hocValidationAppliedTo.indexOf(stepIndex) > -1);
}
// a validation method is each step can be sync or async (Promise based), this utility abstracts the wrapper stepMoveAllowed to be Promise driven regardless of validation return type
abstractStepMoveAllowedToPromise(movingBack) {
return Promise.resolve(this.stepMoveAllowed(movingBack));
}
// get the classmame of steps
getClassName(className, i) {
let liClassName = `${className}-${this.state.navState.styles[i]}`;
// if step ui based navigation is disabled, then dont highlight step
if (!this.props.stepsNavigation) {
liClassName += ' no-hl';
}
return liClassName;
}
// render the steps as stepsNavigation
renderSteps() {
return this.props.steps.map((s, i) => (
<li className={this.getClassName('progtrckr', i)} onClick={(evt) => { this.jumpToStep(evt); }} key={i} value={i}>
<em>{i + 1}</em>
<span>{this.props.steps[i].name}</span>
</li>
));
}
// main render of stepzilla container
render() {
const { props } = this;
const { nextStepText, showNextBtn, showPreviousBtn } = this.getPrevNextBtnLayout(this.state.compState);
// clone the step component dynamically and tag it as activeComponent so we can validate it on next. also bind the jumpToStep piping method
const cloneExtensions = {
jumpToStep: (t) => {
this.jumpToStep(t);
}
};
const componentPointer = this.props.steps[this.state.compState].component;
// can only update refs if its a regular React component (not a pure component), so lets check that
if (componentPointer instanceof Component
|| (componentPointer.type && componentPointer.type.prototype instanceof Component)) {
// unit test deteceted that instanceof Component can be in either of these locations so test both (not sure why this is the case)
cloneExtensions.ref = 'activeComponent';
}
const compToRender = React.cloneElement(componentPointer, cloneExtensions);
return (
<div className="multi-step" onKeyDown={(evt) => { this.handleKeyDown(evt); }}>
{
this.props.showSteps
? <ol className="progtrckr">
{this.renderSteps()}
</ol>
: <span></span>
}
{compToRender}
<div style={this.props.showNavigation ? {} : this.hidden} className="footer-buttons">
<button
type="button"
style={showPreviousBtn ? {} : this.hidden}
className={props.backButtonCls}
onClick={() => { this.previous(); }}
id="prev-button"
>
{this.props.backButtonText}
</button>
<button
type="button"
style={showNextBtn ? {} : this.hidden}
className={props.nextButtonCls}
onClick={() => { this.next(); }}
id="next-button"
>
{nextStepText}
</button>
</div>
</div>
);
}
}
StepZilla.defaultProps = {
showSteps: true,
showNavigation: true,
stepsNavigation: true,
prevBtnOnLastStep: true,
dontValidate: false,
preventEnterSubmission: false,
startAtStep: 0,
nextButtonText: 'Next',
nextButtonCls: 'btn btn-prev btn-primary btn-lg pull-right',
backButtonText: 'Previous',
backButtonCls: 'btn btn-next btn-primary btn-lg pull-left',
hocValidationAppliedTo: []
};
StepZilla.propTypes = {
steps: PropTypes.arrayOf(PropTypes.shape({
name: PropTypes.oneOfType([
PropTypes.string,
PropTypes.object
]).isRequired,
component: PropTypes.element.isRequired
})).isRequired,
showSteps: PropTypes.bool,
showNavigation: PropTypes.bool,
stepsNavigation: PropTypes.bool,
prevBtnOnLastStep: PropTypes.bool,
dontValidate: PropTypes.bool,
preventEnterSubmission: PropTypes.bool,
startAtStep: PropTypes.number,
nextButtonText: PropTypes.oneOfType([
PropTypes.string,
PropTypes.element
]),
nextButtonCls: PropTypes.string,
backButtonCls: PropTypes.string,
backButtonText: PropTypes.oneOfType([
PropTypes.string,
PropTypes.element
]),
hocValidationAppliedTo: PropTypes.array,
onStepChange: PropTypes.func
};