/
Button.js
527 lines (467 loc) · 16.5 KB
/
Button.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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
import _ from 'lodash';
import Field from '../_classes/field/Field';
import Input from '../_classes/input/Input';
import { componentValueTypes, eachComponent, getArrayFromComponentPath, getComponentSavedTypes } from '../../utils/utils';
export default class ButtonComponent extends Field {
static schema(...extend) {
return Input.schema({
type: 'button',
label: 'Submit',
key: 'submit',
size: 'md',
leftIcon: '',
rightIcon: '',
block: false,
action: 'submit',
persistent: false,
disableOnInvalid: false,
theme: 'primary',
dataGridLabel: true
}, ...extend);
}
static get builderInfo() {
return {
title: 'Button',
group: 'basic',
icon: 'stop',
documentation: '/userguide/form-building/form-components#button',
weight: 110,
schema: ButtonComponent.schema()
};
}
static savedValueTypes(schema) {
return getComponentSavedTypes(schema) || [componentValueTypes.boolean];
}
constructor(component, options, data) {
super(component, options, data);
this.filesUploading = [];
}
get defaultSchema() {
return ButtonComponent.schema();
}
get inputInfo() {
const info = super.elementInfo();
info.type = 'button';
info.attr.type = (['submit', 'saveState'].includes(this.component.action)) ? 'submit' : 'button';
this.component.theme = this.component.theme || 'default';
info.attr.class = `btn btn-${this.component.theme}`;
if (this.component.size) {
info.attr.class += ` btn-${this.component.size}`;
}
if (this.component.block) {
info.attr.class += ' btn-block';
}
if (this.component.customClass) {
info.attr.class += ` ${this.component.customClass}`;
}
info.content = this.t(this.component.label, { _userInput: true });
return info;
}
get labelInfo() {
return {
hidden: true
};
}
set loading(loading) {
this.setLoading(this.refs.button, loading);
}
get skipInEmail() {
return true;
}
// No label needed for buttons.
createLabel() {}
createInput(container) {
this.refs.button = super.createInput(container);
return this.refs.button;
}
get emptyValue() {
return false;
}
getValue() {
return this.dataValue;
}
get clicked() {
return this.dataValue;
}
get defaultValue() {
return false;
}
get className() {
let className = super.className;
className += ` ${this.transform('class', 'form-group')}`;
return className;
}
get oauthConfig() {
if (_.has(this, 'root.form.config.oauth') && this.component.oauthProvider) {
return this.root.form.config.oauth[this.component.oauthProvider];
}
// Legacy oauth location.
if (this.component.oauth) {
return this.component.oauth;
}
return false;
}
render() {
if (this.viewOnly || this.options.hideButtons) {
this._visible = false;
}
return super.render(this.renderTemplate('button', {
component: this.component,
input: this.inputInfo,
}));
}
attachButton() {
this.addShortcut(this.refs.button);
let onChange = null;
let onError = null;
if (this.component.action === 'submit') {
this.on('submitButton', () => {
this.disabled = true;
}, true);
this.on('cancelSubmit', () => {
this.disabled = false;
}, true);
this.on('submitDone', (message) => {
const resultMessage = _.isString(message) ? message : this.t('complete');
this.loading = false;
this.disabled = false;
this.addClass(this.refs.button, 'btn-success submit-success');
this.removeClass(this.refs.button, 'btn-danger submit-fail');
this.addClass(this.refs.buttonMessageContainer, 'has-success');
this.removeClass(this.refs.buttonMessageContainer, 'has-error');
this.setContent(this.refs.buttonMessage, resultMessage);
}, true);
this.on('submitError', (message) => {
const resultMessage = _.isString(message) ? this.t(message) : this.t(this.errorMessage('submitError'));
this.loading = false;
this.disabled = false;
this.hasError = true;
this.removeClass(this.refs.button, 'btn-success submit-success');
this.addClass(this.refs.button, 'btn-danger submit-fail');
this.removeClass(this.refs.buttonMessageContainer, 'has-success');
this.addClass(this.refs.buttonMessageContainer, 'has-error');
this.setContent(this.refs.buttonMessage, resultMessage);
}, true);
this.on('fileUploadingStart', (filePromise) => {
this.filesUploading.push(filePromise);
this.disabled = true;
this.setDisabled(this.refs.button, this.disabled);
}, true);
this.on('fileUploadingEnd', (filePromise) => {
const index = this.filesUploading.indexOf(filePromise);
if (index !== -1) {
this.filesUploading.splice(index, 1);
}
this.disabled = this.shouldDisabled ? true : false;
this.setDisabled(this.refs.button, this.disabled);
}, true);
onChange = (value, isValid) => {
this.removeClass(this.refs.button, 'btn-success submit-success');
if (isValid) {
this.removeClass(this.refs.button, 'btn-danger submit-fail');
if (this.hasError) {
this.hasError = false;
this.setContent(this.refs.buttonMessage, '');
this.removeClass(this.refs.buttonMessageContainer, 'has-success');
this.removeClass(this.refs.buttonMessageContainer, 'has-error');
}
}
};
onError = () => {
this.hasError = true;
this.removeClass(this.refs.button, 'btn-success submit-success');
this.addClass(this.refs.button, 'btn-danger submit-fail');
this.removeClass(this.refs.buttonMessageContainer, 'has-success');
this.addClass(this.refs.buttonMessageContainer, 'has-error');
this.setContent(this.refs.buttonMessage, this.t(this.errorMessage('submitError')));
};
}
if (this.component.action === 'url') {
this.on('requestButton', () => {
this.disabled = true;
}, true);
this.on('requestDone', () => {
this.loading = false;
this.disabled = false;
}, true);
}
this.on('change', (value, flags) => {
let isValid = value.isValid;
const isSilent = flags && flags.silent;
//check root validity only if disableOnInvalid is set and when it is not possible to make submission because of validation errors
if (flags && flags.noValidate && (this.component.disableOnInvalid || this.hasError)) {
isValid = flags.rootValidity || (this.root ? (this.root.validate(this.root.data, { dirty: false, silentCheck: true }).length === 0) : true);
flags.rootValidity = isValid;
}
this.isDisabledOnInvalid = this.component.disableOnInvalid && (isSilent || !isValid);
this.disabled = this.shouldDisabled;
this.setDisabled(this.refs.button, this.disabled);
if (onChange) {
onChange(value, isValid);
}
}, true);
this.on('error', () => {
this.loading = false;
this.disabled = false;
if (onError) {
onError();
}
}, true);
if (this.component.saveOnEnter) {
this.root.addEventListener(this.root.element, 'keyup', (event) => {
if (event.keyCode === 13) {
this.onClick.call(this, event);
}
});
}
this.addEventListener(this.refs.button, 'click', this.onClick.bind(this));
this.addEventListener(this.refs.buttonMessageContainer, 'click', () => {
if (this.refs.buttonMessageContainer.classList.contains('has-error')) {
if (this.root && this.root.alert) {
this.scrollIntoView(this.root.alert);
}
}
});
this.disabled = this.shouldDisabled;
this.setDisabled(this.refs.button, this.disabled);
function getUrlParameter(name) {
name = name.replace(/[[]/, '\\[').replace(/[\]]/, '\\]');
const regex = new RegExp(`[\\?&]${name}=([^&#]*)`);
const results = regex.exec(location.search);
if (!results) {
return results;
}
return decodeURIComponent(results[1].replace(/\+/g, ' '));
}
// If this is an OpenID Provider initiated login, perform the click event immediately
if ((this.component.action === 'oauth') && this.oauthConfig && !this.oauthConfig.error) {
const iss = getUrlParameter('iss');
if (iss && (this.oauthConfig.authURI.indexOf(iss) === 0)) {
this.openOauth(this.oauthConfig);
}
}
}
get shouldDisabled() {
return super.shouldDisabled || !!this.filesUploading?.length || this.isDisabledOnInvalid;
}
attach(element) {
this.loadRefs(element, {
button: 'single',
buttonMessageContainer: 'single',
buttonMessage: 'single'
});
const superAttach = super.attach(element);
this.attachButton();
return superAttach;
}
/* eslint-enable max-statements */
detach(element) {
if (element && this.refs.button) {
this.removeShortcut(this.refs.button);
}
super.detach();
}
onClick(event) {
this.triggerReCaptcha();
// Don't click if disabled or in builder mode.
if (this.disabled || this.options.attachMode === 'builder') {
return;
}
this.dataValue = true;
if (this.component.action !== 'submit' && this.component.showValidations) {
this.emit('checkValidity', this.data);
}
switch (this.component.action) {
case 'saveState':
case 'submit':
event.preventDefault();
event.stopPropagation();
this.loading = true;
this.emit('submitButton', {
noValidate: this.component.state === 'draft',
state: this.component.state || 'submitted',
component: this.component,
instance: this
});
break;
case 'event':
this.emit(this.interpolate(this.component.event), this.data);
this.events.emit(this.interpolate(this.component.event), this.data);
this.emit('customEvent', {
type: this.interpolate(this.component.event),
component: this.component,
data: this.data,
event: event
});
break;
case 'custom': {
// Get the FormioForm at the root of this component's tree
const form = this.getRoot();
const flattened = {};
const components = {};
eachComponent(form.components, (componentWrapper, path) => {
const component = componentWrapper.component || componentWrapper;
flattened[path] = component;
components[component.key] = component;
}, true);
this.evaluate(this.component.custom, {
form,
flattened,
components
});
this.triggerChange();
break;
}
case 'url':
this.loading = true;
this.emit('requestButton', {
component: this.component,
instance: this
});
this.emit('requestUrl', {
url: this.interpolate(this.component.url),
headers: this.component.headers
});
break;
case 'reset':
this.emit('resetForm');
break;
case 'delete':
this.emit('deleteSubmission');
break;
case 'oauth':
if (this.root === this) {
console.warn('You must add the OAuth button to a form for it to function properly');
return;
}
// Display Alert if OAuth config is missing
if (!this.oauthConfig) {
this.root.setAlert('danger', 'OAuth not configured. You must configure oauth for your project before it will work.');
break;
}
// Display Alert if oAuth has an error is missing
if (this.oauthConfig.error) {
this.root.setAlert('danger', `The Following Error Has Occured ${this.oauthConfig.error}`);
break;
}
this.openOauth(this.oauthConfig);
break;
}
}
openOauth(settings) {
if (!this.root.formio) {
console.warn('You must attach a Form API url to your form in order to use OAuth buttons.');
return;
}
/*eslint-disable camelcase */
let params = {
response_type: 'code',
client_id: settings.clientId,
redirect_uri: (settings.redirectURI && this.interpolate(settings.redirectURI)) || window.location.origin || `${window.location.protocol}//${window.location.host}`,
scope: settings.scope
};
if (settings.state) {
params.state = settings.state;
}
else if (settings.code_challenge) {
params.code_challenge = settings.code_challenge;
params.code_challenge_method = 'S256';
}
/*eslint-enable camelcase */
// Needs for the correct redirection URI for the OpenID
const originalRedirectUri = params.redirect_uri;
// Make display optional.
if (settings.display) {
params.display = settings.display;
}
params = Object.keys(params).map(key => {
return `${key}=${encodeURIComponent(params[key])}`;
}).join('&');
const separator = settings.authURI.indexOf('?') !== -1 ? '&' : '?';
const url = `${settings.authURI}${separator}${params}`;
const popup = window.open(url, settings.provider, 'width=1020,height=618');
const interval = setInterval(() => {
try {
const popupHost = popup.location.host;
const currentHost = window.location.host;
if (popup && !popup.closed && popupHost === currentHost) {
popup.close();
const params = popup.location.search.substr(1).split('&').reduce((params, param) => {
const split = param.split('=');
params[split[0]] = split[1];
return params;
}, {});
if (params.error) {
alert(params.error_description || params.error);
this.root.setAlert('danger', params.error_description || params.error);
return;
}
// TODO: check for error response here
if (settings.state !== params.state) {
this.root.setAlert('danger', 'OAuth state does not match. Please try logging in again.');
return;
}
// Depending on where the settings came from, submit to either the submission endpoint (old) or oauth endpoint (new).
let requestPromise = Promise.resolve();
if (_.has(this, 'root.form.config.oauth') && this.root.form.config.oauth[this.component.oauthProvider]) {
params.provider = settings.provider;
params.redirectURI = originalRedirectUri;
// Needs for the exclude oAuth Actions that not related to this button
params.triggeredBy = this.oauthComponentPath;
requestPromise = this.root.formio.makeRequest('oauth', `${this.root.formio.projectUrl}/oauth2`, 'POST', params);
}
else {
const submission = { data: {}, oauth: {} };
submission.oauth[settings.provider] = params;
submission.oauth[settings.provider].redirectURI = originalRedirectUri;
if (settings.logoutURI) {
this.root.formio.oauthLogoutURI(settings.logoutURI);
}
// Needs for the exclude oAuth Actions that not related to this button
submission.oauth[settings.provider].triggeredBy = this.oauthComponentPath;
requestPromise = this.root.formio.saveSubmission(submission);
}
requestPromise.then((result) => {
this.root.onSubmit(result, true);
})
.catch((err) => {
this.root.onSubmissionError(err);
});
}
}
catch (error) {
if (error.name !== 'SecurityError' && (error.name !== 'Error' || error.message !== 'Permission denied')) {
this.root.setAlert('danger', error.message || error);
}
}
if (!popup || popup.closed || popup.closed === undefined) {
clearInterval(interval);
}
}, 100);
}
get oauthComponentPath() {
const pathArray = getArrayFromComponentPath(this.path);
return _.chain(pathArray).filter(pathPart => !_.isNumber(pathPart)).join('.').value();
}
focus() {
if (this.refs.button) {
this.refs.button.focus();
}
}
triggerReCaptcha() {
if (!this.root) {
return;
}
let recaptchaComponent;
this.root.everyComponent((component)=> {
if ( component.component.type === 'recaptcha' &&
component.component.eventType === 'buttonClick' &&
component.component.buttonKey === this.component.key) {
recaptchaComponent = component;
}
});
if (recaptchaComponent) {
recaptchaComponent.verify(`${this.component.key}Click`);
}
}
}