-
Notifications
You must be signed in to change notification settings - Fork 21
/
index.js
360 lines (356 loc) · 15 KB
/
index.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
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import CharacterCounter from 'react-character-counter';
import classNames from 'classnames';
import is from 'is';
import Paragraph from '../../atoms/text/Paragraph';
import './style.css';
// These components exist to make it clear in FeedbackForm's render what's going on.
const RefererField = (props) => <input type="hidden" {...props} />;
const NodeIdField = (props) => <input type="hidden" {...props} />;
// Required for jsonp responses to work.
const JsonPField = () => <input type="hidden" name="jsonp" value={1} />;
// A hidden input field that prevents FormStack from looking for a required field that wasn't filled in.
const HiddenFields = (props) => {
const { formId, ...rest } = props;
return(<input type="hidden" name="hidden_fields" id={`hidden_fields${formId}`} {...rest} />);
};
HiddenFields.propTypes = {
/** The form id that the hidden input will be rendered within. */
formId: PropTypes.number
};
export default class FeedbackForm extends Component {
static defaultProps = {
formId: 2521317,
radioId: 47054416,
yesFeedbackId: 52940022,
noFeedbackId: 47054414,
refererId: 47056299
};
static propTypes = {
/** A ref object as created by React.createRef(). Will be applied to the form element. */
formRef: PropTypes.oneOfType([
PropTypes.func,
PropTypes.shape({ current: PropTypes.instanceOf(Element) })
]),
/** A function whose return value is displayed after a successful form submission. */
successMessage: PropTypes.func.isRequired,
/** The field id number for the yes textarea. */
yesFeedbackId: PropTypes.number,
/** The field id number for the no textarea. */
noFeedbackId: PropTypes.number,
/** The field id number for the referer. */
refererId: PropTypes.number,
/** The id number for the form from FormStack. */
formId: PropTypes.number,
/** The field id number for the yes/no radio buttons. */
radioId: PropTypes.number,
/** A drupal node id number for the referer. */
nodeId: PropTypes.number,
/** A function whose return value is rendered under the yes textarea. */
yesDisclaimer: PropTypes.func,
/** A function whose return value is rendered under the no textarea. */
noDisclaimer: PropTypes.func
}
state = {
yesText: '',
noText: '',
errorMessage: <Paragraph className="error">Please go back and fill in any required fields (marked with an *)</Paragraph>,
feedbackChoice: null,
hasError: [],
success: false,
formSubmitted: false
};
componentDidMount() {
if (window) {
// We don't have the FormStack class available, but we can fake like we do:
window[`form${this.props.formId}`] = {
onSubmitError: (err) => {
if (err) {
const hasError = [...this.state.hasError];
hasError.push(this.props.radioId);
hasError.push(this.props.noFeedbackId);
const errorMessage = <Paragraph className="error">{err.error}</Paragraph>;
this.setState({ hasError, errorMessage });
}
},
onPostSubmit: () => {
this.setState({ success: true });
}
};
}
}
yesRadio = React.createRef();
yesTextArea = React.createRef();
noRadio = React.createRef();
noTextArea = React.createRef();
submitButton = React.createRef();
defaultDisclaimer = () => (
<div id="feedback-note" className="ma__disclaimer">We use your feedback to help us improve this site but we are not able to respond directly. <strong>Please do not include personal or contact information.</strong> If you need a response, please locate the contact information elsewhere on this page or in the footer.</div>
);
prefixLabel = (id) => `label${id}`;
prefixField = (id) => `field${id}`;
handleRadioChange = (e) => {
if (e.currentTarget === this.yesRadio.current) {
return{ feedbackChoice: true };
}
if (e.currentTarget === this.noRadio.current) {
return{ feedbackChoice: false };
}
return{};
}
// Handles the onChange event for the yes/no radio buttons as well as the yes/no textareas.
handleChange = (e) => {
let newState = {};
e.persist();
if (e.currentTarget === this.yesRadio.current || e.currentTarget === this.noRadio.current) {
newState = Object.assign(newState, this.handleRadioChange(e));
}
if (e.currentTarget === this.yesTextArea.current) {
newState = Object.assign(newState, { yesText: e.currentTarget.value });
}
if (e.currentTarget === this.noTextArea.current) {
newState = Object.assign(newState, { noText: e.currentTarget.value });
}
// If the form was previously submitted but the user made a new change, reset the form submitted status.
if (this.state.formSubmitted && Object.keys(newState).length > 0) {
newState.formSubmitted = false;
newState.success = false;
newState.successMessage = '';
}
this.setState(newState, this.checkForErrors);
}
removeError = (errors, idToRemove) => errors.filter((fieldId) => !is.equal(fieldId, idToRemove));
checkForErrors = () => {
let hasError = [...this.state.hasError];
const { radioId, noFeedbackId } = this.props;
const { feedbackChoice, formSubmitted } = this.state;
// The user has not selected yes or no.
if (!hasError.includes(radioId) && feedbackChoice === null) {
hasError.push(radioId);
}
if (hasError.includes(radioId) && !is.nil(feedbackChoice)) {
hasError = this.removeError(hasError, radioId);
}
// The user has selected no but has not typed any feedback.
if (!hasError.includes(noFeedbackId) && feedbackChoice === false && formSubmitted && is.empty(this.noTextArea.current.value)) {
hasError.push(noFeedbackId);
} else if (hasError.includes(noFeedbackId) && feedbackChoice === false && !is.empty(this.noTextArea.current.value)) {
hasError = this.removeError(hasError, noFeedbackId);
}
// If the user changed choices from no to yes, remove the error for no if there was one.
if (feedbackChoice === true && hasError.includes(noFeedbackId)) {
hasError = this.removeError(hasError, noFeedbackId);
}
// Prevent calling setState too often while typing in textareas.
if (!is.equal(hasError, this.state.hasError)) {
this.setState({ hasError });
}
return hasError;
};
handleSubmit = (e) => {
e.preventDefault();
// Update the component state to know that the form was just submitted,
// then check the form for any errors based on this new state.
this.setState({ formSubmitted: true }, () => {
// checkForErrors doesn't immediately update state, so it returns what this.state.hasError is being set to.
const errors = this.checkForErrors();
// If no remaining errors, submit form.
// Since we have to use jsonp and this component could be used with server side rendering, ensure that window exists.
if (window && is.array.empty(errors)) {
import('b-jsonp').then((module) => {
const jsonp = module.default;
const form = document.getElementById(`fsForm${this.props.formId}`);
const data = new FormData(form);
const body = {};
new Map(data.entries()).forEach((value, key) => {
body[key] = value;
});
// This library leaves behind the script added by formstack in the head of the document.
// Any errors are handled by onSubmitError and the response is handled through onPostSubmit.
// jsonp requires you to pass a function for the last param though.
jsonp('https://www.formstack.com/forms/index.php', body, {
prefix: `form${this.props.formId}`,
name: 'onPostSubmit'
}, () => {});
});
}
});
};
render() {
const {
yesFeedbackId, yesDisclaimer, noFeedbackId, noDisclaimer, refererId, formId, formRef, radioId, nodeId, successMessage
} = this.props;
const {
hasError, success, feedbackChoice, formSubmitted, noText, yesText, errorMessage
} = this.state;
const yesId = this.prefixField(yesFeedbackId);
const noId = this.prefixField(noFeedbackId);
const formProps = {
id: `fsForm${formId}`,
method: 'post',
className: 'formForm',
onSubmit: this.handleSubmit,
action: 'https://www.formstack.com/forms/index.php',
encType: 'multipart/form-data'
};
// Allows other components to have direct access to the form element.
if (formRef) {
formProps.ref = formRef;
}
const refererProps = {
id: this.prefixField(refererId),
name: this.prefixField(refererId),
size: '50',
value: window.location.href,
className: 'fsField'
};
const yesFieldSetClassNames = classNames({
'radio-yes': true,
error: (hasError.includes(yesFeedbackId))
});
const noFieldSetClassNames = classNames({
'radio-no': true,
error: (hasError.includes(noFeedbackId))
});
const noTextAreaClassNames = classNames({
'fsField required': true,
error: (hasError.includes(noFeedbackId))
});
const radiosClassNames = (hasError.includes(radioId)) ? 'error' : null;
const messsageClassNames = classNames({
messages: true,
hide: success === false && is.array.empty(hasError)
});
const messageStyle = {
fontWeight: 'bold'
};
if (!is.array.empty(hasError)) {
messageStyle.color = 'red';
}
const characterCounterProps = {
maxLength: 10000,
wrapperStyle: {
display: 'block',
fontSize: '17px',
lineHeight: '1.625rem',
textAlign: 'right'
},
characterCounterStyle: {
position: 'relative',
display: 'block',
bottom: '32px',
right: '5px',
top: 'auto',
fontSize: '1rem',
fontWeight: 400,
lineHeight: '1.625rem'
},
overrideStyle: true
};
return(success && formSubmitted) ? (
<div className="ma__feedback-form" data-mass-feedback-form>
<h2 className="visually-hidden">Feedback</h2>
<form noValidate {...formProps}>
<fieldset>
<div className={messsageClassNames} style={messageStyle}>
{is.fn(successMessage) && successMessage()}
</div>
</fieldset>
</form>
</div>
) : (
<div className="ma__feedback-form" data-mass-feedback-form>
<h2 className="visually-hidden">Feedback</h2>
<form noValidate {...formProps}>
<input type="hidden" name="form" value={formId} />
<JsonPField />
<input type="hidden" name="viewkey" value="vx39GBYJhi" />
{ feedbackChoice === true && <HiddenFields formId={formId} value={noId} />}
{ feedbackChoice === false && <HiddenFields formId={formId} value={yesId} />}
<input type="hidden" name="_submit" value="1" />
<input type="hidden" name="style_version" value="3" />
<input type="hidden" id="viewparam" name="viewparam" value="524744" />
<RefererField {...refererProps} />
<NodeIdField id="field58154059" name="field58154059" value={nodeId} />
<NodeIdField id="field57432673" name="field57432673" value={nodeId} />
<fieldset className={radiosClassNames}>
<legend className="fsLabel requiredLabel fsLabelVertical">
Did you find what you were looking for on this webpage?<span> * <span className="visually-hidden">required</span></span>
</legend>
<div className="ma__input-group__items ma__input-group__items--inline">
<div className="ma__input-group__item">
<span className="ma__input-radio">
<input className="fsField required" id={`${this.prefixField(radioId)}_1`} onChange={this.handleChange} ref={this.yesRadio} name={this.prefixField(radioId)} type="radio" value="Yes" />
<label className="fsOptionLabel ma__input-radio__label" htmlFor={`${this.prefixField(radioId)}_1`}>Yes</label>
</span>
</div>
<div className="ma__input-group__item">
<span className="ma__input-radio">
<input className="fsField required" id={`${this.prefixField(radioId)}_2`} onChange={this.handleChange} ref={this.noRadio} name={this.prefixField(radioId)} type="radio" value="No" />
<label className="fsOptionLabel ma__input-radio__label" htmlFor={`${this.prefixField(radioId)}_2`}>No</label>
</span>
</div>
</div>
</fieldset>
{(feedbackChoice === false) &&
(
<fieldset className={noFieldSetClassNames}>
<label htmlFor={noId}>If "No," please tell us what you were looking for:<span> * <span className="visually-hidden">required</span></span></label>
<div className="ma__textarea__wrapper">
<CharacterCounter value={noText} {...characterCounterProps}>
<textarea
id={noId}
ref={this.noTextArea}
onChange={this.handleChange}
className={noTextAreaClassNames}
name={noId}
aria-required="true"
maxLength="10000"
disabled={feedbackChoice === false ? null : 'disabled'}
aria-describedby="feedback-note"
/>
</CharacterCounter>
</div>
<input type="hidden" id={yesId} name={yesId} value="" />
{(is.fn(noDisclaimer)) ? noDisclaimer() : this.defaultDisclaimer()}
</fieldset>
)}
{(feedbackChoice === true) && (
<fieldset className={yesFieldSetClassNames}>
<label htmlFor={yesId}>Is there anything else you would like to tell us?</label>
<div className="ma__textarea__wrapper">
<CharacterCounter value={yesText} {...characterCounterProps}>
<textarea
ref={this.yesTextArea}
onChange={this.handleChange}
id={yesId}
name={yesId}
maxLength="10000"
disabled={feedbackChoice === true ? null : 'disabled'}
aria-describedby="feedback-note2"
/>
</CharacterCounter>
</div>
<input type="hidden" id={noId} name={noId} value="" />
{is.fn(yesDisclaimer) ? yesDisclaimer() : this.defaultDisclaimer()}
</fieldset>
)}
<fieldset className="ma_feedback-fieldset ma__mass-feedback-form__form--submit-wrapper">
<div className={messsageClassNames} style={messageStyle}>
{success === false && errorMessage}
</div>
<input
id="submitButton2521317"
ref={this.submitButton}
className="submitButton ma__button ma__button--small"
style={{ display: 'block' }}
type="submit"
value="Send Feedback"
/>
</fieldset>
</form>
</div>
);
}
}