-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathui-form-controller.js
260 lines (236 loc) · 8.11 KB
/
ui-form-controller.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
import React, { Component } from "react";
import WizardStep from "./lib/wizardStep.js";
import jQuery from "jquery";
import t from "tcomb-form";
import deepclone from "deepclone";
var _lastUrl;
var _lastRequestData;
var _lastMethod;
/**
* utility function
*/
function doRequest(url, onSuccess,
onError = function(errorText) {
alert(errorText);
},
requestMethod="GET", requestData, responseDataType = "json",
requestContentType = "application/json; charset=utf-8") {
if (!onSuccess) {
throw "onSuccess must be defined";
}
_lastUrl = url;
_lastMethod = requestMethod;
_lastRequestData = requestData;
jQuery.ajax({
dataType : responseDataType,
method : requestMethod,
data: requestData,
contentType: requestContentType,
url: url,
success : function(data){
onSuccess(data);
},
error : function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
let errorText = "Error loading data from URL " + url + " errorText: " + textStatus;
onError(errorText);
}
});
}
/**
* Class that encapsulates wizard, related sequence of web forms, functionality
*/
class UiFormController extends Component{
/**
*
*/
constructor() {
super();
this.state = {};
}
/**
* @param data to be evaluated
*/
parseDescriptor(data) {
if (!data || data == null) {
console.warn("Descriptor to be parsed to JS is null");
return undefined;
}
try {
let configFactory = eval(data);
let descriptor = configFactory(t);
return descriptor;
}catch(e) {
console.error(e.stack);
if (this.props.descriptorErrorReportURL) {
doRequest(this.props.descriptorErrorReportURL, ()=>{}, undefined,
"POST", {
url: _lastUrl,
method: _lastMethod,
requestData: _lastRequestData,
obtainedDescriptor: data,
stackTrace: e.stack
}, "text", "application/x-www-form-urlencoded");
}
throw e;
}
}
getDescriptorFromData(data) {
try {
this.descriptor = this.parseDescriptor(data);
}catch(e) {
this.setState({
errorMessage: "Error parsing wizard descriptor."
});
return;
}
console.log(this.descriptor);
return this.descriptor;
}
/**
* starts the wizard
*/
componentWillMount() {
let descriptorURL = this.props.descriptorURL;
if (!descriptorURL) {
throw "descriptorURL should be suplied";
}
var onDescriptorUrlSuccess = (data)=>{
console.log("got wizard descriptor from " + descriptorURL + " : " + data);
if (!this.getDescriptorFromData(data)) return;
let descriptor = this.descriptor;
// sets initial options
this.setState({currentStep: descriptor.main, options: descriptor.main.formConfig.options, value: descriptor.main.data});
};
doRequest(descriptorURL, onDescriptorUrlSuccess, this.onError, undefined, undefined, "text");
}
/**
* when step is loaded creates form
*/
render() {
if (this.state.errorMessage) {//loading wizard for the first time probably
return <div className='alert alert-danger'> {this.state.errorMessage} </div>;
}
if (this.state.responseStatus == "0" || this.state.responseStatus == "end") {//finishes the wizard
let message = (this.state.message||"Uspješno ste dovršili unos podataka");
return <div className="alert alert-success"><i className="glyphicon glyphicon-ok" dangerouslySetInnerHTML={{__html: message}} /></div>;//cleans
}
if (!this.state.currentStep) {//loading wizard for the first time probably
return <div className='alert alert-info'> Loading data...</div>;
}
let stepConfig = this.state.currentStep;
let formDescriptor = stepConfig.formConfig;
console.log("rendering step:");
console.log(stepConfig);
return <WizardStep model={formDescriptor.model} options={this.state.options}
value={this.state.value} buttonLabel={this.state.currentStep.save.buttonLabel || this.descriptor.buttonLabel}
savingButtonLabel={this.state.currentStep.messageWhenSaving || this.descriptor.messageWhenSaving}
expectedSaveDurationSeconds={this.state.currentStep.save.expectedSaveDurationSeconds}
next={this.onCurrentStepSubmitted.bind(this)}
title={stepConfig.title} description={stepConfig.description} saving={this.state.saving} />;
}
/**
* when current step su submitted in form, and all client side data verifications are passed.
* This calls "save" url defined in StepConfiguration
*/
onCurrentStepSubmitted(value) {
let state = this.state;
let save = this.state.currentStep.save;
if (!save) {
throw "'save' attribute in wizard step descriptor is mandatory";
}
if (!save.method || !save.url) {
throw "'save.method' and 'save.url' are mandatory.";
}
//changes state
state.value = value;
state.saving = true;
this.setState(state);
doRequest(save.url, (data)=>{
console.log("invoked save script: " + save.url + " and got result: ");
console.log(data);
this.processResponse(data);
}, (errorMessage)=>this.setState({errorMessage: errorMessage}), save.method,
JSON.stringify(value), "text", save.requestContentType);
}
/**
* processes response from 'save' action
*/
processResponse(responseData) {
if (!this.getDescriptorFromData(responseData)) return;
let descriptor = this.descriptor;
let status = descriptor.status;
if (!status) {
console.warn(descriptor);
console.warn("status field is not defined in response! Finishing the wizard by convention.");
status = "0";
}
// let stateStep = jQuery.isEmptyObject(descriptor.validationErrors)?descriptor.next:this.state.currentStep;
let isResponseOK = jQuery.isEmptyObject(descriptor.validationErrors);
let nextState = {responseStatus: status,
message: descriptor.message,
validationErrors: descriptor.validationErrors,
value: (isResponseOK && descriptor.next)?descriptor.next.data:this.state.value,//this.state.value,
currentStep: (isResponseOK)?descriptor.next:this.state.currentStep,
saving: false
};
if (status == "0" || status == "end") {
console.log("Finishing the wizard");
this.setState(nextState);
return;//nothing to do
}
if (descriptor.message && descriptor.message != "") {
alert(descriptor.message);
}
this.mergeAsyncErrorsAndSetOptions(nextState);
console.log("Next state:");
console.log(nextState);
this.setState(nextState);
}
/**
* async errors are expected to be something like:
* {username : "name allready taken", age : "You must be over 18"}
*/
mergeAsyncErrorsAndSetOptions(state) {
let asyncSaveErrors = state.validationErrors;
let initialOptions = state.currentStep.formConfig.options;
if (jQuery.isEmptyObject(asyncSaveErrors)) {
state.options = initialOptions;
return;
}
console.log("Logging async save error");
console.log(asyncSaveErrors);
/*creates new options*/
let newOptions = deepclone(initialOptions);
for (let errorField in asyncSaveErrors) {
let fieldConfig = newOptions.fields[errorField];
if (!fieldConfig) {
fieldConfig = {};
newOptions.fields[errorField] = fieldConfig;
}
fieldConfig.hasError = true;
fieldConfig.error = asyncSaveErrors[errorField];
}
console.log("Async errors set in options");
console.log(newOptions);
state.options = newOptions;
}
/**
*
*/
// loadNextStep(nextStep) {
// if (nextStep) {
// this.loadWizardStep(nextStep);
// }else {
// console.warn("Next step for status: " + status +
// " does not exists in wizardConfig. If status is '0' or 'end' wizard will be finished. Otherwise expecting 'next' " +
// "field (with configuration for next step) inside response.");
// }
// }
// end class WizardController (finall bracket follows)
}
UiFormController.propTypes = {
descriptorURL : React.PropTypes.string.isRequired,
descriptorErrorReportURL: React.PropTypes.string
};
export default UiFormController;