/
AddForm.jsx
94 lines (79 loc) · 2.63 KB
/
AddForm.jsx
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
import React, { Component } from "react"
import PropTypes from "prop-types"
import YAML from "js-yaml"
import { checkForErrors } from "../helpers/validation-helpers"
class AddForm extends Component {
constructor(props) {
super(props)
this.state = {
formErrors: false,
formData: this.props.existingData ?
this.props.getFormData( (newForm, path) => this.updateForm(newForm, path), [], this.props.existingData) :
this.props.getFormData( (newForm, path) => this.updateForm(newForm, path), [] )
}
this.updateForm = this.updateForm.bind(this)
this.submit = this.submit.bind(this)
}
submit = () => {
const formData = this.state.formData
// Prevent form submission if the data was invalid.
if (checkForErrors(formData)[1]) {
this.setState(prevState => ({
formErrors: true,
formData: checkForErrors(prevState.formData)[0]
}))
return
}
this.setState({
formErrors: false
})
// Update the Swagger UI state.
this.props.updateSpecJson(formData)
// Update the spec string in the Swagger UI state with the new json.
const currentJson = this.props.specSelectors.specJson()
this.props.specActions.updateSpec(YAML.dump(currentJson.toJS()), "insert")
// Perform any parent component actions for the form.
this.props.submit()
}
updateForm = (newFormData, path) => {
this.setState(prevState => ({
formData: prevState.formData.setIn(path, newFormData)
}))
}
render() {
const { getComponent } = this.props
const InsertForm = getComponent("InsertForm")
return (
<div>
<div className="modal-body">
<div className="form-container">
<InsertForm formData={this.state.formData} getComponent={getComponent} />
</div>
</div>
<div className="modal-footer">
{ this.state.formErrors && <div className="invalid-feedback">Please fix errors before submitting.</div>}
<button className="btn btn-default" onClick={this.submit}>{this.props.submitButtonText}</button>
</div>
</div>
)
}
}
AddForm.propTypes = {
specActions: PropTypes.shape({
updateSpec: PropTypes.func.isRequired
}),
specSelectors: PropTypes.shape({
specStr: PropTypes.func.isRequired,
specJson: PropTypes.func.isRequired
}),
submit: PropTypes.func.isRequired,
submitButtonText: PropTypes.string.isRequired,
getFormData: PropTypes.func.isRequired,
updateSpecJson: PropTypes.func.isRequired,
existingData: PropTypes.oneOfType([
PropTypes.object,
PropTypes.array
]),
getComponent: PropTypes.func.isRequired
}
export default AddForm