-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
Copy pathamp-form.js
1664 lines (1522 loc) · 48.2 KB
/
amp-form.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
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Copyright 2016 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {ActionTrust} from '../../../src/action-constants';
import {AmpEvents} from '../../../src/amp-events';
import {AmpFormTextarea} from './amp-form-textarea';
import {
AsyncInputAttributes,
AsyncInputClasses,
} from '../../../src/async-input';
import {CSS} from '../../../build/amp-form-0.1.css';
import {Deferred, tryResolve} from '../../../src/utils/promise';
import {
FORM_VERIFY_OPTOUT,
FORM_VERIFY_PARAM,
getFormVerifier,
} from './form-verifiers';
import {FormDirtiness} from './form-dirtiness';
import {FormEvents} from './form-events';
import {FormSubmitService} from './form-submit-service';
import {Keys} from '../../../src/utils/key-codes';
import {
SOURCE_ORIGIN_PARAM,
addParamsToUrl,
isProxyOrigin,
parseQueryString,
} from '../../../src/url';
import {Services} from '../../../src/services';
import {SsrTemplateHelper} from '../../../src/ssr-template-helper';
import {
ancestorElementsByTag,
childElementByAttr,
createElementWithAttributes,
iterateCursor,
removeElement,
tryFocus,
} from '../../../src/dom';
import {createCustomEvent} from '../../../src/event-helper';
import {createFormDataWrapper} from '../../../src/form-data-wrapper';
import {deepMerge, dict} from '../../../src/utils/object';
import {dev, devAssert, user, userAssert} from '../../../src/log';
import {escapeCssSelectorIdent} from '../../../src/css';
import {
formOrNullForElement,
getFormAsObject,
setFormForElement,
} from '../../../src/form';
import {getFormValidator, isCheckValiditySupported} from './form-validators';
import {getMode} from '../../../src/mode';
import {
getViewerAuthTokenIfAvailable,
setupAMPCors,
setupInit,
setupInput,
} from '../../../src/utils/xhr-utils';
import {installFormProxy} from './form-proxy';
import {installStylesForDoc} from '../../../src/style-installer';
import {isAmp4Email} from '../../../src/format';
import {isArray, toArray, toWin} from '../../../src/types';
import {triggerAnalyticsEvent} from '../../../src/analytics';
import {tryParseJson} from '../../../src/json';
/** @const {string} */
const TAG = 'amp-form';
/**
* A list of external dependencies that can be included in forms.
* @const {!Array<string>}
*/
const EXTERNAL_DEPS = ['amp-selector'];
/** @const @enum {string} */
const FormState = {
INITIAL: 'initial',
VERIFYING: 'verifying',
VERIFY_ERROR: 'verify-error',
SUBMITTING: 'submitting',
SUBMIT_ERROR: 'submit-error',
SUBMIT_SUCCESS: 'submit-success',
};
/** @const @enum {string} */
const UserValidityState = {
NONE: 'none',
USER_VALID: 'valid',
USER_INVALID: 'invalid',
};
/** @private @const {string} */
const REDIRECT_TO_HEADER = 'AMP-Redirect-To';
/**
* Time to wait for services / async input before throwing an error.
* @private @const {number}
*/
const SUBMIT_TIMEOUT = 10000;
export class AmpForm {
/**
* Adds functionality to the passed form element and listens to submit event.
* @param {!HTMLFormElement} element
* @param {string} id
*/
constructor(element, id) {
//TODO(dvoytenko, #7063): Remove the try catch.
try {
installFormProxy(element);
} catch (e) {
dev().error(TAG, 'form proxy failed to install', e);
}
setFormForElement(element, this);
/** @private @const {string} */
this.id_ = id;
/** @const @private {!Window} */
this.win_ = toWin(element.ownerDocument.defaultView);
/** @const @private {!../../../src/service/timer-impl.Timer} */
this.timer_ = Services.timerFor(this.win_);
/** @const @private {!../../../src/service/url-replacements-impl.UrlReplacements} */
this.urlReplacement_ = Services.urlReplacementsForDoc(element);
/** @private {?Promise} */
this.dependenciesPromise_ = null;
/** @const @private {!HTMLFormElement} */
this.form_ = element;
/** @const @private {!../../../src/service/ampdoc-impl.AmpDoc} */
this.ampdoc_ = Services.ampdoc(this.form_);
/** @const @private {!../../../src/service/template-impl.Templates} */
this.templates_ = Services.templatesFor(this.win_);
/** @const @private {!../../../src/service/xhr-impl.Xhr} */
this.xhr_ = Services.xhrFor(this.win_);
/** @const @private {!../../../src/service/action-impl.ActionService} */
this.actions_ = Services.actionServiceForDoc(this.form_);
/** @const @private {!../../../src/service/mutator-interface.MutatorInterface} */
this.mutator_ = Services.mutatorForDoc(this.form_);
/** @const @private {!../../../src/service/viewer-interface.ViewerInterface} */
this.viewer_ = Services.viewerForDoc(this.form_);
/**
* @const {!../../../src/ssr-template-helper.SsrTemplateHelper}
* @private
*/
this.ssrTemplateHelper_ = new SsrTemplateHelper(
TAG,
this.viewer_,
this.templates_
);
/** @const @private {string} */
this.method_ = (this.form_.getAttribute('method') || 'GET').toUpperCase();
/** @const @private {string} */
this.target_ = this.form_.getAttribute('target');
/** @private {?string} */
this.xhrAction_ = this.getXhrUrl_('action-xhr');
/** @const @private {?string} */
this.xhrVerify_ = this.getXhrUrl_('verify-xhr');
/** @const @private {boolean} */
this.shouldValidate_ = !this.form_.hasAttribute('novalidate');
// Need to disable browser validation in order to allow us to take full
// control of this. This allows us to trigger validation APIs and reporting
// when we need to.
this.form_.setAttribute('novalidate', '');
if (!this.shouldValidate_) {
this.form_.setAttribute('amp-novalidate', '');
}
this.form_.classList.add('i-amphtml-form');
/** @private {!FormState} */
this.state_ = FormState.INITIAL;
const inputs = this.form_.elements;
for (let i = 0; i < inputs.length; i++) {
const {name} = inputs[i];
userAssert(
name != SOURCE_ORIGIN_PARAM && name != FORM_VERIFY_PARAM,
'Illegal input name, %s found: %s',
name,
inputs[i]
);
}
/** @const @private {!./form-dirtiness.FormDirtiness} */
this.dirtinessHandler_ = new FormDirtiness(this.form_, this.win_);
/** @const @private {!./form-validators.FormValidator} */
this.validator_ = getFormValidator(this.form_);
/** @const @private {!./form-verifiers.FormVerifier} */
this.verifier_ = getFormVerifier(this.form_, () => this.handleXhrVerify_());
this.actions_.installActionHandler(
this.form_,
this.actionHandler_.bind(this)
);
this.installEventHandlers_();
this.installInputMasking_();
this.maybeInitializeFromUrl_();
/** @private {?Promise} */
this.xhrSubmitPromise_ = null;
/** @private {?Promise} */
this.renderTemplatePromise_ = null;
/** @private {?./form-submit-service.FormSubmitService} */
this.formSubmitService_ = null;
Services.formSubmitForDoc(element).then((service) => {
this.formSubmitService_ = service;
});
}
/**
* Gets and validates an attribute for form request URLs.
* @param {string} attribute
* @return {?string}
* @private
*/
getXhrUrl_(attribute) {
const url = this.form_.getAttribute(attribute);
if (url) {
const urlService = Services.urlForDoc(this.form_);
urlService.assertHttpsUrl(url, this.form_, attribute);
userAssert(
!urlService.isProxyOrigin(url),
'form %s should not be on AMP CDN: %s',
attribute,
this.form_
);
}
return url;
}
/**
* @return {string|undefined} the value of the form's xssi-prefix attribute.
*/
getXssiPrefix() {
return this.form_.getAttribute('xssi-prefix');
}
/**
* Builds fetch request data for amp-form elements.
* @param {string} url
* @param {string} method
* @param {!Object<string, string>=} opt_extraFields
* @param {!Array<string>=} opt_fieldBlacklist
* @return {!Promise<!FetchRequestDef>}
*/
requestForFormFetch(url, method, opt_extraFields, opt_fieldBlacklist) {
let xhrUrl, body;
const isHeadOrGet = method == 'GET' || method == 'HEAD';
if (isHeadOrGet) {
this.assertNoSensitiveFields_();
const values = this.getFormAsObject_();
if (opt_fieldBlacklist) {
opt_fieldBlacklist.forEach((name) => {
delete values[name];
});
}
if (opt_extraFields) {
deepMerge(values, opt_extraFields);
}
xhrUrl = addParamsToUrl(url, values);
} else {
xhrUrl = url;
body = createFormDataWrapper(this.win_, this.form_);
if (opt_fieldBlacklist) {
opt_fieldBlacklist.forEach((name) => {
body.delete(name);
});
}
for (const key in opt_extraFields) {
body.append(key, opt_extraFields[key]);
}
}
/** @type {!FetchRequestDef}*/
const request = {
xhrUrl,
fetchOpt: dict({
'body': body,
'method': method,
'credentials': 'include',
'headers': dict({'Accept': 'application/json'}),
}),
};
return getViewerAuthTokenIfAvailable(this.form_).then((token) => {
if (token) {
userAssert(
request.fetchOpt['method'] == 'POST',
'Cannot attach auth token with GET request.'
);
body.append('ampViewerAuthToken', token);
}
return request;
});
}
/**
* Setter to change cached action-xhr.
* @param {string} url
*/
setXhrAction(url) {
this.xhrAction_ = url;
}
/**
* Handle actions that require at least high trust.
* @param {!../../../src/service/action-impl.ActionInvocation} invocation
* @return {?Promise}
* @private
*/
actionHandler_(invocation) {
if (!invocation.satisfiesTrust(ActionTrust.DEFAULT)) {
return null;
}
if (invocation.method == 'submit') {
return this.whenDependenciesReady_().then(() => {
return this.handleSubmitAction_(invocation);
});
} else if (invocation.method === 'clear') {
this.handleClearAction_();
}
return null;
}
/**
* Returns a promise that will be resolved when all dependencies used inside
* the form tag are loaded and built (e.g. amp-selector) or 2 seconds timeout
* - whichever is first.
* @return {!Promise}
* @private
*/
whenDependenciesReady_() {
if (this.dependenciesPromise_) {
return this.dependenciesPromise_;
}
const depElements = this.form_./*OK*/ querySelectorAll(
EXTERNAL_DEPS.join(',')
);
// Wait for an element to be built to make sure it is ready.
const promises = toArray(depElements).map((el) => el.whenBuilt());
return (this.dependenciesPromise_ = this.waitOnPromisesOrTimeout_(
promises,
2000
));
}
/** @private */
installEventHandlers_() {
this.ampdoc_.whenNextVisible().then(() => {
const autofocus = this.form_.querySelector('[autofocus]');
if (autofocus) {
tryFocus(autofocus);
}
});
this.form_.addEventListener(
'submit',
this.handleSubmitEvent_.bind(this),
true
);
this.form_.addEventListener(
'blur',
(e) => {
checkUserValidityAfterInteraction_(dev().assertElement(e.target));
this.validator_.onBlur(e);
},
true
);
this.form_.addEventListener(
AmpEvents.FORM_VALUE_CHANGE,
(e) => {
checkUserValidityAfterInteraction_(dev().assertElement(e.target));
this.validator_.onInput(e);
},
true
);
// Form verification is not supported when SSRing templates is enabled.
if (!this.ssrTemplateHelper_.isEnabled()) {
this.form_.addEventListener('change', (e) => {
this.verifier_.onCommit().then((updatedErrors) => {
const {updatedElements, errors} = updatedErrors;
updatedElements.forEach(checkUserValidityAfterInteraction_);
// Tell the validation to reveal any input.validationMessage added
// by the form verifier.
this.validator_.onBlur(e);
// Only make the verify XHR if the user hasn't pressed submit.
if (this.state_ === FormState.VERIFYING) {
if (errors.length) {
this.setState_(FormState.VERIFY_ERROR);
this.renderTemplate_(dict({'verifyErrors': errors})).then(() => {
this.triggerAction_(
FormEvents.VERIFY_ERROR,
errors,
ActionTrust.DEFAULT // DEFAULT because async after gesture.
);
});
} else {
this.setState_(FormState.INITIAL);
}
}
});
});
}
this.form_.addEventListener('input', (e) => {
checkUserValidityAfterInteraction_(dev().assertElement(e.target));
this.validator_.onInput(e);
});
}
/** @private */
installInputMasking_() {
Services.inputmaskServiceForDocOrNull(this.form_).then(
(inputmaskService) => {
if (inputmaskService) {
inputmaskService.install();
}
}
);
}
/**
* Triggers 'amp-form-submit' event in 'amp-analytics' and
* generates variables for form fields to be accessible in analytics
*
* @param {string} eventType
* @private
*/
triggerFormSubmitInAnalytics_(eventType) {
this.assertSsrTemplate_(false, 'Form analytics not supported');
const formDataForAnalytics = dict({});
const formObject = this.getFormAsObject_();
for (const k in formObject) {
if (Object.prototype.hasOwnProperty.call(formObject, k)) {
formDataForAnalytics['formFields[' + k + ']'] = formObject[k].join(',');
}
}
formDataForAnalytics['formId'] = this.form_.id;
this.analyticsEvent_(eventType, formDataForAnalytics);
}
/**
* Handles submissions through action service invocations.
* e.g. <img on=tap:form.submit>
* @param {!../../../src/service/action-impl.ActionInvocation} invocation
* @return {!Promise}
* @private
*/
handleSubmitAction_(invocation) {
if (this.state_ == FormState.SUBMITTING || !this.checkValidity_()) {
return Promise.resolve(null);
}
// "submit" has the same trust level as the action that caused it.
return this.submit_(invocation.trust, null);
}
/**
* Handles clearing the form through action service invocations.
* @private
*/
handleClearAction_() {
this.form_.reset();
this.setState_(FormState.INITIAL);
this.form_.classList.remove('user-valid');
this.form_.classList.remove('user-invalid');
const validityElements = this.form_.querySelectorAll(
'.user-valid, .user-invalid'
);
iterateCursor(validityElements, (element) => {
element.classList.remove('user-valid');
element.classList.remove('user-invalid');
});
const messageElements = this.form_.querySelectorAll(
'.visible[validation-for]'
);
iterateCursor(messageElements, (element) => {
element.classList.remove('visible');
});
removeValidityStateClasses(this.form_);
}
/**
* Note on stopImmediatePropagation usage here, it is important to emulate
* native browser submit event blocking. Otherwise any other submit listeners
* would get the event.
*
* For example, action service shouldn't trigger 'submit' event if form is
* actually invalid. stopImmediatePropagation allows us to make sure we don't
* trigger it.
*
* This prevents the default submission event in any of following cases:
* - The form is still finishing a previous submission.
* - The form is invalid.
* - Handling an XHR submission.
* - It's a non-XHR POST submission (unsupported).
*
* @param {!Event} event
* @return {!Promise}
* @private
*/
handleSubmitEvent_(event) {
if (this.state_ == FormState.SUBMITTING || !this.checkValidity_()) {
event.stopImmediatePropagation();
event.preventDefault();
return Promise.resolve(null);
}
if (this.xhrAction_ || this.method_ == 'POST') {
event.preventDefault();
}
// Submits caused by user input have high trust.
return this.submit_(ActionTrust.HIGH, event);
}
/**
* Helper method that actual handles the different cases (post, get, xhr...).
* @param {ActionTrust} trust
* @param {?Event} event
* @return {!Promise}
* @private
*/
submit_(trust, event) {
try {
const event = {
form: this.form_,
actionXhrMutator: this.setXhrAction.bind(this),
};
devAssert(this.formSubmitService_).fire(event);
} catch (e) {
dev().error(TAG, 'Form submit service failed: %s', e);
}
// Get our special fields
const varSubsFields = this.getVarSubsFields_();
const asyncInputs = this.form_.getElementsByClassName(
AsyncInputClasses.ASYNC_INPUT
);
this.dirtinessHandler_.onSubmitting();
// Do any assertions we may need to do
// For NonXhrGET
// That way we can determine if
// we can submit synchronously
if (!this.xhrAction_ && this.method_ == 'GET') {
this.assertSsrTemplate_(false, 'Non-XHR GETs not supported.');
this.assertNoSensitiveFields_();
// If we have no async inputs, we can just submit synchronously
if (asyncInputs.length === 0) {
for (let i = 0; i < varSubsFields.length; i++) {
this.urlReplacement_.expandInputValueSync(varSubsFields[i]);
}
/**
* If the submit was called with an event, then we shouldn't
* manually submit the form
*/
const shouldSubmitFormElement = !event;
this.handleNonXhrGet_(shouldSubmitFormElement);
this.dirtinessHandler_.onSubmitSuccess();
return Promise.resolve();
}
if (event) {
event.preventDefault();
}
}
// Set ourselves to the SUBMITTING State
this.setState_(FormState.SUBMITTING);
// Promises to run before submit without timeout.
const requiredActionPromises = [];
// Promises to run before submitting the form
const presubmitPromises = [];
presubmitPromises.push(this.doVarSubs_(varSubsFields));
iterateCursor(asyncInputs, (asyncInput) => {
const asyncCall = this.getValueForAsyncInput_(asyncInput);
if (
asyncInput.classList.contains(AsyncInputClasses.ASYNC_REQUIRED_ACTION)
) {
requiredActionPromises.push(asyncCall);
} else {
presubmitPromises.push(asyncCall);
}
});
return Promise.all(requiredActionPromises).then(
() => {
return this.waitOnPromisesOrTimeout_(
presubmitPromises,
SUBMIT_TIMEOUT
).then(
() => this.handlePresubmitSuccess_(trust),
(error) => this.handlePresubmitError_(error, trust)
);
},
(error) => this.handlePresubmitError_(error, trust)
);
}
/**
* Handle form error for presubmit async calls.
* @param {*} error
* @param {!ActionTrust} trust
* @return {Promise}
* @private
*/
handlePresubmitError_(error, trust) {
const detail = dict();
if (error && error.message) {
detail['error'] = error.message;
}
return this.handleSubmitFailure_(error, detail, trust);
}
/**
* Get form fields that require variable substitutions
* @return {!IArrayLike<!HTMLInputElement>}
* @private
*/
getVarSubsFields_() {
// Fields that support var substitutions.
return this.form_.querySelectorAll('[type="hidden"][data-amp-replace]');
}
/**
* Handle successful presubmit tasks
* @param {!ActionTrust} trust
* @return {!Promise}
*/
handlePresubmitSuccess_(trust) {
if (this.xhrAction_) {
return this.handleXhrSubmit_(trust);
} else if (this.method_ == 'POST') {
this.handleNonXhrPost_();
} else if (this.method_ == 'GET') {
this.handleNonXhrGet_(/* shouldSubmitFormElement */ true);
}
return Promise.resolve();
}
/**
* Send the verify request and control the VERIFYING state.
* @return {!Promise}
* @private
*/
handleXhrVerify_() {
if (this.state_ === FormState.SUBMITTING) {
return Promise.resolve();
}
this.setState_(FormState.VERIFYING);
this.triggerAction_(FormEvents.VERIFY, /* detail */ null, ActionTrust.HIGH);
return this.doVarSubs_(this.getVarSubsFields_()).then(() =>
this.doVerifyXhr_()
);
}
/**
* @param {ActionTrust} trust
* @return {!Promise}
* @private
*/
handleXhrSubmit_(trust) {
let p;
if (this.ssrTemplateHelper_.isEnabled()) {
p = this.handleSsrTemplate_(trust);
} else {
this.submittingWithTrust_(trust);
p = this.doActionXhr_().then(
(response) => this.handleXhrSubmitSuccess_(response, trust),
(error) => this.handleXhrSubmitFailure_(error, trust)
);
}
if (getMode().test) {
this.xhrSubmitPromise_ = p;
}
return p;
}
/**
* Handles the server side proxying and then rendering of the template.
* @param {ActionTrust} trust
* @return {!Promise}
* @private
*/
handleSsrTemplate_(trust) {
let request;
// Render template for the form submitting state.
const values = this.getFormAsObject_();
return this.renderTemplate_(values)
.then(() =>
this.actions_.trigger(
this.form_,
FormEvents.SUBMIT,
/* event */ null,
trust
)
)
.then(() =>
this.requestForFormFetch(
dev().assertString(this.xhrAction_),
this.method_
)
)
.then((formRequest) => {
request = formRequest;
request.fetchOpt = setupInit(request.fetchOpt);
request.fetchOpt = setupAMPCors(
this.win_,
request.xhrUrl,
request.fetchOpt
);
request.xhrUrl = setupInput(
this.win_,
request.xhrUrl,
request.fetchOpt
);
return this.ssrTemplateHelper_.ssr(
this.form_,
request,
this.templatesForSsr_()
);
})
.then(
(response) => this.handleSsrTemplateResponse_(response, trust),
(error) => {
const detail = dict();
if (error && error.message) {
detail['error'] = error.message;
}
return this.handleSubmitFailure_(error, detail, trust);
}
);
}
/**
* If present, finds and returns the success and error response templates.
* Note that we do not render the submitting state template and only
* deal with submit-success or submit-error.
* @return {!../../../src/ssr-template-helper.SsrTemplateDef}
* @private
*/
templatesForSsr_() {
let successTemplate;
const successContainer = this.form_.querySelector('[submit-success]');
if (successContainer) {
successTemplate = this.templates_.maybeFindTemplate(successContainer);
}
let errorTemplate;
const errorContainer = this.form_.querySelector('[submit-error]');
if (errorContainer) {
errorTemplate = this.templates_.maybeFindTemplate(errorContainer);
}
return {successTemplate, errorTemplate};
}
/**
* Transition the form to the submit-success or submit-error state depending on the response status.
* @param {!JsonObject} response
* @param {!ActionTrust} trust
* @return {!Promise}
* @private
*/
handleSsrTemplateResponse_(response, trust) {
const init = response['init'];
// response['body'] is serialized as a string in the response.
const body = tryParseJson(response['body'], (error) =>
user().error(TAG, 'Failed to parse response JSON: %s', error)
);
if (init) {
const status = init['status'];
if (status >= 300) {
/** HTTP status codes of 300+ mean redirects and errors. */
return this.handleSubmitFailure_(status, response, trust, body);
}
}
return this.handleSubmitSuccess_(response, trust, body);
}
/**
* Triggers the analytics and renders any template for submitting state.
* @param {ActionTrust} trust
*/
submittingWithTrust_(trust) {
this.triggerFormSubmitInAnalytics_('amp-form-submit');
// After variable substitution
const values = this.getFormAsObject_();
// At the form submitting state, we want to display any template
// messages with the submitting attribute.
this.renderTemplate_(values).then(() => {
this.actions_.trigger(
this.form_,
FormEvents.SUBMIT,
/* event */ null,
trust
);
});
}
/**
* Perform asynchronous variable substitution on the fields that require it.
* @param {!IArrayLike<!HTMLInputElement>} varSubsFields
* @return {!Promise}
* @private
*/
doVarSubs_(varSubsFields) {
const varSubPromises = [];
for (let i = 0; i < varSubsFields.length; i++) {
varSubPromises.push(
this.urlReplacement_.expandInputValueAsync(varSubsFields[i])
);
}
return this.waitOnPromisesOrTimeout_(varSubPromises, 100);
}
/**
* Call getValue() on Async Input elements, and
* Create hidden inputs containing their returned values
* @param {!Element} asyncInput
* @return {!Promise}
* @private
*/
getValueForAsyncInput_(asyncInput) {
return asyncInput
.getImpl()
.then((implementation) => implementation.getValue())
.then((value) => {
const name = asyncInput.getAttribute(AsyncInputAttributes.NAME);
let input = this.form_.querySelector(
`input[name=${escapeCssSelectorIdent(name)}]`
);
if (!input) {
input = createElementWithAttributes(
this.win_.document,
'input',
dict({
'name': asyncInput.getAttribute(AsyncInputAttributes.NAME),
'hidden': 'true',
})
);
}
input.setAttribute('value', value);
this.form_.appendChild(input);
});
}
/**
* Send a request to the form's action endpoint.
* @return {!Promise<!Response>}
* @private
*/
doActionXhr_() {
return this.doXhr_(dev().assertString(this.xhrAction_), this.method_);
}
/**
* Send a request to the form's verify endpoint.
* @return {!Promise<!Response>}
* @private
*/
doVerifyXhr_() {
const noVerifyFields = toArray(
this.form_.querySelectorAll(
`[${escapeCssSelectorIdent(FORM_VERIFY_OPTOUT)}]`
)
);
const blacklist = noVerifyFields.map((field) => field.name || field.id);
return this.doXhr_(
dev().assertString(this.xhrVerify_),
this.method_,
/**opt_extraFields*/ {[FORM_VERIFY_PARAM]: true},
/**opt_fieldBlacklist*/ blacklist
);
}
/**
* Send a request to a form endpoint.
* @param {string} url
* @param {string} method
* @param {!Object<string, string>=} opt_extraFields
* @param {!Array<string>=} opt_fieldBlacklist
* @return {!Promise<!Response>}
* @private
*/
doXhr_(url, method, opt_extraFields, opt_fieldBlacklist) {
this.assertSsrTemplate_(false, 'XHRs should be proxied.');
return this.requestForFormFetch(
url,
method,
opt_extraFields,
opt_fieldBlacklist
).then((request) => this.xhr_.fetch(request.xhrUrl, request.fetchOpt));
}
/**
* Returns the action trust for submit-success and submit-error events.
* @param {!ActionTrust} incomingTrust
* @return {!ActionTrust}
* @private
*/
trustForSubmitResponse_(incomingTrust) {
// TODO(choumx): Remove this expected error before Q1 2020.
if (incomingTrust <= ActionTrust.DEFAULT) {
dev().expectedError(
TAG,
'Recursive form submissions are scheduled to be deprecated by 1/1/2020. ' +
'See https://github.com/ampproject/amphtml/issues/24894.'
);
}
const doc = this.form_.ownerDocument;
// Only degrade trust across form submission in AMP4EMAIL for now.
return doc && isAmp4Email(doc)
? /** @type {!ActionTrust} */ (incomingTrust - 1)
: incomingTrust;
}
/**
* @param {!Response} response
* @param {!ActionTrust} incomingTrust Trust of the originating submit action.
* @return {!Promise}
* @private
*/
handleXhrSubmitSuccess_(response, incomingTrust) {
return this.xhr_
.xssiJson(response, this.getXssiPrefix())
.then(
(json) =>
this.handleSubmitSuccess_(
/** @type {!JsonObject} */ (json),
incomingTrust
),
(error) => user().error(TAG, 'Failed to parse response JSON: %s', error)
)
.then(() => {
this.triggerFormSubmitInAnalytics_('amp-form-submit-success');
this.maybeHandleRedirect_(response);
});
}
/**
* Transition the form to the submit success state.
* @param {!JsonObject} result
* @param {!ActionTrust} incomingTrust Trust of the originating submit action.
* @param {?JsonObject=} opt_eventData
* @return {!Promise}
* @private
*/
handleSubmitSuccess_(result, incomingTrust, opt_eventData) {
this.setState_(FormState.SUBMIT_SUCCESS);
// TODO: Investigate if `tryResolve()` can be removed here.
return tryResolve(() => {
this.renderTemplate_(result || {}).then(() => {