1
1
import createField from './form-fields.js' ;
2
- import { sampleRUM } from '../../scripts/aem.js' ;
3
2
4
- async function createForm ( formHref ) {
3
+ async function createForm ( formHref , submitHref ) {
5
4
const { pathname } = new URL ( formHref ) ;
6
5
const resp = await fetch ( pathname ) ;
7
6
const json = await resp . json ( ) ;
8
7
9
8
const form = document . createElement ( 'form' ) ;
10
- // eslint-disable-next-line prefer-destructuring
11
- form . dataset . action = pathname . split ( '.json' ) [ 0 ] ;
9
+ form . dataset . action = submitHref ;
12
10
13
11
const fields = await Promise . all ( json . data . map ( ( fd ) => createField ( fd , form ) ) ) ;
14
12
fields . forEach ( ( field ) => {
@@ -45,13 +43,6 @@ function generatePayload(form) {
45
43
return payload ;
46
44
}
47
45
48
- function handleSubmitError ( form , error ) {
49
- // eslint-disable-next-line no-console
50
- console . error ( error ) ;
51
- form . querySelector ( 'button[type="submit"]' ) . disabled = false ;
52
- sampleRUM ( 'form:error' , { source : '.form' , target : error . stack || error . message || 'unknown error' } ) ;
53
- }
54
-
55
46
async function handleSubmit ( form ) {
56
47
if ( form . getAttribute ( 'data-submitting' ) === 'true' ) return ;
57
48
@@ -70,7 +61,6 @@ async function handleSubmit(form) {
70
61
} ,
71
62
} ) ;
72
63
if ( response . ok ) {
73
- sampleRUM ( 'form:submit' , { source : '.form' , target : form . dataset . action } ) ;
74
64
if ( form . dataset . confirmation ) {
75
65
window . location . href = form . dataset . confirmation ;
76
66
}
@@ -79,17 +69,21 @@ async function handleSubmit(form) {
79
69
throw new Error ( error ) ;
80
70
}
81
71
} catch ( e ) {
82
- handleSubmitError ( form , e ) ;
72
+ // eslint-disable-next-line no-console
73
+ console . error ( e ) ;
83
74
} finally {
84
75
form . setAttribute ( 'data-submitting' , 'false' ) ;
76
+ submit . disabled = false ;
85
77
}
86
78
}
87
79
88
80
export default async function decorate ( block ) {
89
- const formLink = block . querySelector ( 'a[href$=".json"]' ) ;
90
- if ( ! formLink ) return ;
81
+ const links = [ ...block . querySelectorAll ( 'a' ) ] . map ( ( a ) => a . href ) ;
82
+ const formLink = links . find ( ( link ) => link . startsWith ( window . location . origin ) && link . endsWith ( '.json' ) ) ;
83
+ const submitLink = links . find ( ( link ) => link !== formLink ) ;
84
+ if ( ! formLink || ! submitLink ) return ;
91
85
92
- const form = await createForm ( formLink . href ) ;
86
+ const form = await createForm ( formLink , submitLink ) ;
93
87
block . replaceChildren ( form ) ;
94
88
95
89
form . addEventListener ( 'submit' , ( e ) => {
0 commit comments