@stegopop/fetch-data-forms 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.idea/jpa-buddy.xml +6 -0
- package/.idea/misc.xml +9 -0
- package/.idea/modules.xml +8 -0
- package/.idea/snap-ajax-forms.iml +9 -0
- package/.idea/vcs.xml +6 -0
- package/.swcrc +21 -0
- package/LICENSE +21 -0
- package/README.md +219 -0
- package/index.js +31 -0
- package/package.json +45 -0
- package/public/db2.json +17 -0
- package/public/dist/fetch-data-forms.js +10 -0
- package/public/src/FetchDataForms.js +236 -0
- package/spack.config.js +12 -0
package/.idea/misc.xml
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
<?xml version="1.0" encoding="UTF-8"?>
|
|
2
|
+
<project version="4">
|
|
3
|
+
<component name="ProjectRootManager" version="2" languageLevel="JDK_11" default="true" project-jdk-name="11" project-jdk-type="JavaSDK">
|
|
4
|
+
<output url="file://$PROJECT_DIR$/out" />
|
|
5
|
+
</component>
|
|
6
|
+
<component name="ProjectType">
|
|
7
|
+
<option name="id" value="jpab" />
|
|
8
|
+
</component>
|
|
9
|
+
</project>
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
<?xml version="1.0" encoding="UTF-8"?>
|
|
2
|
+
<project version="4">
|
|
3
|
+
<component name="ProjectModuleManager">
|
|
4
|
+
<modules>
|
|
5
|
+
<module fileurl="file://$PROJECT_DIR$/.idea/snap-ajax-forms.iml" filepath="$PROJECT_DIR$/.idea/snap-ajax-forms.iml" />
|
|
6
|
+
</modules>
|
|
7
|
+
</component>
|
|
8
|
+
</project>
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
<?xml version="1.0" encoding="UTF-8"?>
|
|
2
|
+
<module type="JAVA_MODULE" version="4">
|
|
3
|
+
<component name="NewModuleRootManager" inherit-compiler-output="true">
|
|
4
|
+
<exclude-output />
|
|
5
|
+
<content url="file://$MODULE_DIR$" />
|
|
6
|
+
<orderEntry type="inheritedJdk" />
|
|
7
|
+
<orderEntry type="sourceFolder" forTests="false" />
|
|
8
|
+
</component>
|
|
9
|
+
</module>
|
package/.idea/vcs.xml
ADDED
package/.swcrc
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
{
|
|
2
|
+
"jsc": {
|
|
3
|
+
"parser": {
|
|
4
|
+
"syntax": "ecmascript",
|
|
5
|
+
"jsx": false
|
|
6
|
+
},
|
|
7
|
+
"loose": false,
|
|
8
|
+
"minify": {
|
|
9
|
+
"compress": false,
|
|
10
|
+
"mangle": false
|
|
11
|
+
}
|
|
12
|
+
},
|
|
13
|
+
"module": {
|
|
14
|
+
"type": "es6"
|
|
15
|
+
},
|
|
16
|
+
"minify": false,
|
|
17
|
+
"isModule": false,
|
|
18
|
+
"env": {
|
|
19
|
+
"targets": "IE 11"
|
|
20
|
+
}
|
|
21
|
+
}
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2023 Nick Adams
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
# FetchDataForms
|
|
2
|
+
|
|
3
|
+
[](https://badge.fury.io/js/@stegopop%2Fajax-tap)
|
|
4
|
+
[](https://opensource.org/licenses/MIT)
|
|
5
|
+
|
|
6
|
+
Instantly turn an HTML form element into an AJAX request just by adding an attribute.
|
|
7
|
+
|
|
8
|
+
## Dependencies
|
|
9
|
+
|
|
10
|
+
Requires jQuery's AJAX.
|
|
11
|
+
|
|
12
|
+
## Usage
|
|
13
|
+
|
|
14
|
+
Make your web apps feel snappier by converting server-side requests into AJAX requests.
|
|
15
|
+
|
|
16
|
+
Instantiate FetchDataForms
|
|
17
|
+
|
|
18
|
+
```
|
|
19
|
+
new FetchDataForms();
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
Just add the `data-fetch` attribute to any form you'd like to convert.
|
|
23
|
+
|
|
24
|
+
```html
|
|
25
|
+
<form action="/url" method="POST" data-fetch>
|
|
26
|
+
...
|
|
27
|
+
</form>
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
## Install
|
|
31
|
+
|
|
32
|
+
With NPM
|
|
33
|
+
|
|
34
|
+
```markdown
|
|
35
|
+
npm install @stegopop/data-fetch-forms
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
With a CDN
|
|
39
|
+
|
|
40
|
+
```html
|
|
41
|
+
<script src="https://cdn.jsdelivr.net/npm/@stegopop/data-fetch-forms"></script>
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
## Options
|
|
45
|
+
|
|
46
|
+
Below are optional features that can be configured via an options object passed the the FetchDataForms constructor, or via data attributes.
|
|
47
|
+
|
|
48
|
+
### Selector
|
|
49
|
+
|
|
50
|
+
By default, any form with the `data-fetch` attribute will submit with FetchDataForms.
|
|
51
|
+
|
|
52
|
+
You may modify this with a css style selector in the options object.
|
|
53
|
+
|
|
54
|
+
```js
|
|
55
|
+
new FetchDataForms({
|
|
56
|
+
select: "form.fetch"
|
|
57
|
+
});
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
### reCAPTCHA
|
|
61
|
+
|
|
62
|
+
*Note: FetchDataForms only supports reCAPTCHA v3.*
|
|
63
|
+
|
|
64
|
+
Added Google reCAPTCHA to FetchDataForms is super simple. Just add a recaptcha object with a version and siteKey as in the options object.
|
|
65
|
+
|
|
66
|
+
```html
|
|
67
|
+
<script src="https://www.google.com/recaptcha/api.js?render=YourKeyHere11111111111111111111111111111"></script>
|
|
68
|
+
<script>
|
|
69
|
+
new FetchDataForms({
|
|
70
|
+
recaptcha: {
|
|
71
|
+
version: "v3",
|
|
72
|
+
siteKey: "YourKeyHere11111111111111111111111111111"
|
|
73
|
+
},
|
|
74
|
+
});
|
|
75
|
+
</script>
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
Then add the `data-fetch-recaptcha` attribute to any form you'd like to protect.
|
|
79
|
+
|
|
80
|
+
```html
|
|
81
|
+
<form action="/url" method="POST" data-fetch data-fetch-recaptcha>
|
|
82
|
+
...
|
|
83
|
+
</form>
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
*Note: This version of the Google reCAPTCHA is score-based. If you wanted to perform certain actions based on that score,
|
|
87
|
+
then pass the `score` from Google's Site Verify Response. You can access that in the form submit event, or the `done`, `always`, or `fail` callbacks.*
|
|
88
|
+
|
|
89
|
+
### Showing Errors
|
|
90
|
+
|
|
91
|
+
Displaying errors in form inputs requires you to specify where you'd like the error to show.
|
|
92
|
+
|
|
93
|
+
Do that with the `data-fetch-errors` attribute.
|
|
94
|
+
|
|
95
|
+
```html
|
|
96
|
+
<form action="/url" method="POST" data-fetch>
|
|
97
|
+
|
|
98
|
+
<label for="favorite_sandwich">
|
|
99
|
+
<input type="text" name="favorite_sandwich" id="favorite_sandwich" required>
|
|
100
|
+
<div data-fetch-errors="favorite_sandwich"></div>
|
|
101
|
+
</label>
|
|
102
|
+
|
|
103
|
+
</form>
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
Then when the server finds an error, return a JSON message with this format for errors.
|
|
107
|
+
|
|
108
|
+
```json
|
|
109
|
+
{
|
|
110
|
+
"errors": {
|
|
111
|
+
"favorite_sandwich": {
|
|
112
|
+
"messages": [
|
|
113
|
+
"This is the 'favorite_sandwich' error message.",
|
|
114
|
+
"There could multiple errors."
|
|
115
|
+
]
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
### Submission Events
|
|
122
|
+
|
|
123
|
+
If you assign your form an id, then an event will be dispatched whenever your form is submitted.
|
|
124
|
+
|
|
125
|
+
Whatever casing you use for your form id will be converted to kebab-casing for the event name.
|
|
126
|
+
|
|
127
|
+
*Example: `<form id="testForm">` requires listening like this `addEventListener("test-form-submit", function() { ... })`*
|
|
128
|
+
|
|
129
|
+
```html
|
|
130
|
+
<form id="fetch-example" action="/url" method="POST" data-fetch>
|
|
131
|
+
...
|
|
132
|
+
</form>
|
|
133
|
+
|
|
134
|
+
<script>
|
|
135
|
+
document.querySelector("#fetch-example").addEventListener("fetch-example-submit", function(data) {
|
|
136
|
+
console.log("Recieved an event");
|
|
137
|
+
});
|
|
138
|
+
</script>
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
### Callbacks
|
|
142
|
+
|
|
143
|
+
Another way to call code after a submission is with the AJAX callback attributes.
|
|
144
|
+
|
|
145
|
+
- done
|
|
146
|
+
- fail
|
|
147
|
+
- always
|
|
148
|
+
- beforeSend
|
|
149
|
+
|
|
150
|
+
Pass the name of a JavaScript function to the attribute.
|
|
151
|
+
|
|
152
|
+
```html
|
|
153
|
+
<form action="/url" method="POST"
|
|
154
|
+
data-fetch
|
|
155
|
+
data-fetch-done="doneCallbackExample"
|
|
156
|
+
data-fetch-fail="failCallbackExample"
|
|
157
|
+
data-fetch-always="alwaysCallbackExample"
|
|
158
|
+
data-fetch-before-send="beforeSendCallbackExample">
|
|
159
|
+
...
|
|
160
|
+
</form>
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
Pass the return data to your done callback function by adding a data argument to your function.
|
|
164
|
+
|
|
165
|
+
```js
|
|
166
|
+
function doneCallbackExample(data) {
|
|
167
|
+
...
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function failCallbackExample(data) {
|
|
171
|
+
...
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function alwaysCallbackExample(data) {
|
|
175
|
+
...
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function beforeSendCallbackExample() {
|
|
179
|
+
...
|
|
180
|
+
}
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
### Disable Submit Button Duration
|
|
184
|
+
|
|
185
|
+
By default, the submission button for your form will be disabled for 1.5 seconds after submission to prevent multiple submissions.
|
|
186
|
+
|
|
187
|
+
You modify this disabled duration by setting `submitDisabledDuration` in the options object passed to the FetchDataForms class.
|
|
188
|
+
|
|
189
|
+
```js
|
|
190
|
+
new FetchDataForms({
|
|
191
|
+
submitDisabledDuration: 3000
|
|
192
|
+
});
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
Or you may disable it by setting the value to 0.
|
|
196
|
+
|
|
197
|
+
### Multiple Submit Buttons
|
|
198
|
+
|
|
199
|
+
You may add multiple submit buttons to your form.
|
|
200
|
+
|
|
201
|
+
Adding a name and value to your buttons will allow you see which submitter was pressed from the backend.
|
|
202
|
+
|
|
203
|
+
Only the submitter element name and value will be submitted.
|
|
204
|
+
|
|
205
|
+
Just like the browser default, if you press enter in your form, the first submit element will be the one that submits the form.
|
|
206
|
+
|
|
207
|
+
### Development
|
|
208
|
+
|
|
209
|
+
#### Compiling
|
|
210
|
+
|
|
211
|
+
I've run into issues compiling this with babel, and moved to swc. Which I also had issues compiling locally.
|
|
212
|
+
|
|
213
|
+
It does work in the playground though, so it's probably an issue with my node environment.
|
|
214
|
+
|
|
215
|
+
I'm not going to fix that right now. So if `npx swc` doesn't work, then manually paste the .swcrc json config here.
|
|
216
|
+
|
|
217
|
+
https://swc.rs/playground
|
|
218
|
+
|
|
219
|
+
And then copy and paste over the dist file.
|
package/index.js
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
const server = require('server');
|
|
2
|
+
const { get, post } = server.router;
|
|
3
|
+
const cors = [
|
|
4
|
+
ctx => header("Access-Control-Allow-Origin", "*"),
|
|
5
|
+
ctx => header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"),
|
|
6
|
+
ctx => header("Access-Control-Allow-Methods", "GET, PUT, PATCH, POST, DELETE, HEAD"),
|
|
7
|
+
ctx => ctx.method.toLowerCase() === 'options' ? 200 : false,
|
|
8
|
+
];
|
|
9
|
+
|
|
10
|
+
const { header, render, redirect } = server.reply;
|
|
11
|
+
|
|
12
|
+
const port = 3002;
|
|
13
|
+
|
|
14
|
+
// Launch server with options and a couple of routes
|
|
15
|
+
server({ port: port, security: false, views: './public' }, cors, [
|
|
16
|
+
get('/', () => render('./index.html')),
|
|
17
|
+
get('/db.json', () => render('./db.json')),
|
|
18
|
+
get('/db2.json', () => render('./db2.json')),
|
|
19
|
+
get('/test/get', ctx => {
|
|
20
|
+
console.log(ctx);
|
|
21
|
+
return ctx.query;
|
|
22
|
+
return 'ok';
|
|
23
|
+
}),
|
|
24
|
+
post('/test/post', ctx => {
|
|
25
|
+
console.log(ctx);
|
|
26
|
+
return {...ctx.data, ...ctx.files};
|
|
27
|
+
return 'ok';
|
|
28
|
+
}),
|
|
29
|
+
]).then(async app => {
|
|
30
|
+
console.log(`Serving on: http://localhost:${port}`);
|
|
31
|
+
});
|
package/package.json
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@stegopop/fetch-data-forms",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Instantly turn an HTML form element into an asynchronous Fetch request by adding an attribute.",
|
|
5
|
+
"main": "dist/fetch-data-forms.min.js",
|
|
6
|
+
"scripts": {
|
|
7
|
+
"js": "babel public/src/FetchDataForms.js --out-file dist/fetch-data-forms.js",
|
|
8
|
+
"watch": "npm run js -- --watch",
|
|
9
|
+
"minify": "uglifyjs --compress --ie --comments --output dist/fetch-data-forms.min.js -- dist/fetch-data-forms.js",
|
|
10
|
+
"serve": "npx http-server -p 3001 --cors -c-1",
|
|
11
|
+
"test-api-server": "json-server --watch public/db.json",
|
|
12
|
+
"nothing-server": "node index.js",
|
|
13
|
+
"prep-release": "npm run js && npm run minify"
|
|
14
|
+
},
|
|
15
|
+
"author": "Nick Adams",
|
|
16
|
+
"license": "MIT",
|
|
17
|
+
"repository": {
|
|
18
|
+
"type": "git",
|
|
19
|
+
"url": "https://github.com/nickolasjadams/fetch-data-forms"
|
|
20
|
+
},
|
|
21
|
+
"keywords": [
|
|
22
|
+
"fetch",
|
|
23
|
+
"form",
|
|
24
|
+
"instant",
|
|
25
|
+
"browser",
|
|
26
|
+
"front-end"
|
|
27
|
+
],
|
|
28
|
+
"devDependencies": {
|
|
29
|
+
"@babel/cli": "^7.24.5",
|
|
30
|
+
"@babel/core": "^7.24.5",
|
|
31
|
+
"@babel/node": "^7.23.9",
|
|
32
|
+
"@babel/polyfill": "^7.12.1",
|
|
33
|
+
"@babel/preset-env": "^7.24.5",
|
|
34
|
+
"@swc/cli": "^0.3.12",
|
|
35
|
+
"@swc/core": "^1.5.24",
|
|
36
|
+
"browserslist": "^4.23.0",
|
|
37
|
+
"http-server": "^14.1.1",
|
|
38
|
+
"json-server": "^0.17.3",
|
|
39
|
+
"server": "^1.0.38"
|
|
40
|
+
},
|
|
41
|
+
"dependencies": {
|
|
42
|
+
"tty": "^1.0.1",
|
|
43
|
+
"uglify-js": "^3.17.4"
|
|
44
|
+
}
|
|
45
|
+
}
|
package/public/db2.json
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
{
|
|
2
|
+
"success": false,
|
|
3
|
+
"errors": {
|
|
4
|
+
"hey": {
|
|
5
|
+
"messages": [
|
|
6
|
+
"This is the 'hey' error message.",
|
|
7
|
+
"There could be a second thing wrong."
|
|
8
|
+
]
|
|
9
|
+
},
|
|
10
|
+
"world": {
|
|
11
|
+
"messages": [
|
|
12
|
+
"This is the 'world' error message.",
|
|
13
|
+
"There could be a second thing wrong."
|
|
14
|
+
]
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* FetchDataForms.js
|
|
3
|
+
*
|
|
4
|
+
* Instantly turn html form elements into asynchronous fetch forms by adding an attribute.
|
|
5
|
+
*
|
|
6
|
+
* @author Nick Adams
|
|
7
|
+
* @see {@link https://github.com/nickolasjadams/fetch-data-forms|Repository}
|
|
8
|
+
* @license MIT
|
|
9
|
+
* @version 1.0.0
|
|
10
|
+
*/function _array_like_to_array(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function _array_with_holes(e){if(Array.isArray(e))return e}function asyncGeneratorStep(e,t,r,n,a,o,i){try{var c=e[o](i),s=c.value}catch(e){r(e);return}c.done?t(s):Promise.resolve(s).then(n,a)}function _async_to_generator(e){return function(){var t=this,r=arguments;return new Promise(function(n,a){var o=e.apply(t,r);function i(e){asyncGeneratorStep(o,n,a,i,c,"next",e)}function c(e){asyncGeneratorStep(o,n,a,i,c,"throw",e)}i(void 0)})}}function _class_call_check(e,t){if(!(e instanceof t))throw TypeError("Cannot call a class as a function")}function _defineProperties(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}function _create_class(e,t,r){return t&&_defineProperties(e.prototype,t),r&&_defineProperties(e,r),e}function _define_property(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function _iterable_to_array_limit(e,t){var r,n,a=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=a){var o=[],i=!0,c=!1;try{for(a=a.call(e);!(i=(r=a.next()).done)&&(o.push(r.value),!t||o.length!==t);i=!0);}catch(e){c=!0,n=e}finally{try{i||null==a.return||a.return()}finally{if(c)throw n}}return o}}function _non_iterable_rest(){throw TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _object_spread(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{},n=Object.keys(r);"function"==typeof Object.getOwnPropertySymbols&&(n=n.concat(Object.getOwnPropertySymbols(r).filter(function(e){return Object.getOwnPropertyDescriptor(r,e).enumerable}))),n.forEach(function(t){_define_property(e,t,r[t])})}return e}function _sliced_to_array(e,t){return _array_with_holes(e)||_iterable_to_array_limit(e,t)||_unsupported_iterable_to_array(e,t)||_non_iterable_rest()}function _type_of(e){return e&&"undefined"!=typeof Symbol&&e.constructor===Symbol?"symbol":typeof e}function _unsupported_iterable_to_array(e,t){if(e){if("string"==typeof e)return _array_like_to_array(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if("Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r)return Array.from(r);if("Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return _array_like_to_array(e,t)}}function _ts_generator(e,t){var r,n,a,o,i={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return o={next:c(0),throw:c(1),return:c(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function c(o){return function(c){return function(o){if(r)throw TypeError("Generator is already executing.");for(;i;)try{if(r=1,n&&(a=2&o[0]?n.return:o[0]?n.throw||((a=n.return)&&a.call(n),0):n.next)&&!(a=a.call(n,o[1])).done)return a;switch(n=0,a&&(o=[2&o[0],a.value]),o[0]){case 0:case 1:a=o;break;case 4:return i.label++,{value:o[1],done:!1};case 5:i.label++,n=o[1],o=[0];continue;case 7:o=i.ops.pop(),i.trys.pop();continue;default:if(!(a=(a=i.trys).length>0&&a[a.length-1])&&(6===o[0]||2===o[0])){i=0;continue}if(3===o[0]&&(!a||o[1]>a[0]&&o[1]<a[3])){i.label=o[1];break}if(6===o[0]&&i.label<a[1]){i.label=a[1],a=o;break}if(a&&i.label<a[2]){i.label=a[2],i.ops.push(o);break}a[2]&&i.ops.pop(),i.trys.pop();continue}o=t.call(e,i)}catch(e){o=[6,e],n=0}finally{r=a=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,c])}}}var FetchDataForms=function(){"use strict";function e(t){_class_call_check(this,e),this.selector="form[data-fetch]",this.submitDisabledDuration=1500,this.recaptcha={version:"v3"},this.onDone="",this.onFail="",this.onAlways="",this.onBeforeSend="",t&&(t.selector&&(this.selector=t.selector),t.submitDisabledDuration&&(this.submitDisabledDuration=t.submitDisabledDuration),t.recaptcha&&(this.recaptcha=_object_spread({},this.recaptcha,t.recaptcha),parseInt(this.recaptcha.version)?this.recaptcha.version="v"+this.recaptcha.version:this.recaptcha.version=this.recaptcha.version.toLowerCase(),"v3"!==this.recaptcha.version&&console.warn("Only reCAPTCHA v3 is supported at this time."),this.recaptcha.siteKey||console.warn("reCAPTCHA siteKey must be set."))),this.forms=document.querySelectorAll(this.selector),this.addFormEventListeners()}return _create_class(e,[{key:"addFormEventListeners",value:function(){var e=this;this.forms.forEach(function(t){t.addEventListener("submit",function(t){var r,n,a,o;t.preventDefault(),r=(o=_sliced_to_array(e.prepFormData(this,t),3))[0],n=o[1],a=o[2],""===r.dataset.fetchRecaptcha?void 0===window.grecaptcha?console.warn("reCAPTCHA objects couldn't be found. Have the scripts been loaded?"):window.grecaptcha.ready(function(){window.grecaptcha.execute(e.recaptcha.siteKey,{action:"submit"}).then(function(t){n.recaptcha_token=t,e.sendXhrRequest(r,n,a)})}):e.sendXhrRequest(r,n,a)},!1)})}},{key:"prepFormData",value:function(e,t){this.onDone=window[e.getAttribute("data-fetch-done")],this.onFail=window[e.getAttribute("data-fetch-fail")],this.onAlways=window[e.getAttribute("data-fetch-always")],this.onBeforeSend=window[e.getAttribute("data-fetch-before-send")];var r=t.submitter,n=new FormData(e,r);r&&(r.disabled="disabled");var a={},o=!0,i=!1,c=void 0;try{for(var s,l=n[Symbol.iterator]();!(o=(s=l.next()).done);o=!0){var u=_sliced_to_array(s.value,2),f=u[0];u[1];var h=document.querySelectorAll("[name='"+f+"']");if(h.length>1){var y="INPUT"===h[0].tagName&&"submit"===h[0].type||"BUTTON"===h[0].tagName&&"button"!==h[0].type,d="INPUT"===h[0].tagName&&"radio"===h[0].type;y?a[f]=n.get(f):d?a[f]=n.get(f):a[f]=n.getAll(f)}else{var p="SELECT"===h[0].tagName&&h[0].attributes.multiple,_="INPUT"===h[0].tagName&&"file"===h[0].type&&h[0].attributes.multiple;p||_?a[f]=n.getAll(f):a[f]=n.get(f)}}}catch(e){i=!0,c=e}finally{try{o||null==l.return||l.return()}finally{if(i)throw c}}var b=new FormData;return Object.entries(a).forEach(function(e){var t=_sliced_to_array(e,2),r=t[0],n=t[1];Array.isArray(n)?n.forEach(function(e){b.append(r,e)}):b.append(r,n)}),[e,b,r]}},{key:"sendXhrRequest",value:function(e,t,r){var n,a=this,o={method:e.method};if("GET"===e.method.toUpperCase()){var i=new URLSearchParams,c=!0,s=!1,l=void 0;try{for(var u,f=t.entries()[Symbol.iterator]();!(c=(u=f.next()).done);c=!0){var h=u.value;i.append(h[0],h[1])}}catch(e){s=!0,l=e}finally{try{c||null==f.return||f.return()}finally{if(s)throw l}}e.action+=(e.action.includes("?")?"&":"?")+i.toString()}else o.body=t;r&&(setTimeout(function(){r.removeAttribute("disabled")},a.submitDisabledDuration),"function"==typeof a.onBeforeSend&&a.onBeforeSend()),fetch(e.action,o).then((n=_async_to_generator(function(t){var r,n,o,i,c,s;return _ts_generator(this,function(l){switch(l.label){case 0:if(!t.ok)return[3,2];return[4,t.json()];case 1:return r=l.sent(),e.reset(),document.querySelectorAll("[data-fetch-errors]").forEach(function(e){e.innerHTML=""}),"function"==typeof a.onDone&&a.onDone(r),e.id&&(o=e.id.replace(/([a-z])([A-Z])/g,"$1-$2").replace(/[\s_]+/g,"-").toLowerCase(),e.dispatchEvent(new CustomEvent(o+"-submit",{detail:r}))),i=r.errors||(null===(n=r.responseJSON)||void 0===n?void 0:n.errors),e.querySelectorAll("[data-fetch-errors]").forEach(function(e){e.innerHTML=""}),i&&Object.entries(i).forEach(function(t){var r=_sliced_to_array(t,2),n=r[0],a=r[1].messages,o=e.querySelector('[data-fetch-errors="'.concat(n,'"]'));o&&a.forEach(function(e){o.insertAdjacentHTML("afterbegin","<div>".concat(e,"</div>"))})}),"function"==typeof a.onFail&&a.onFail(r),[3,4];case 2:return[4,t.json()];case 3:s=(r=l.sent()).errors||(null===(c=r.responseJSON)||void 0===c?void 0:c.errors),e.querySelectorAll("[data-fetch-errors]").forEach(function(e){e.innerHTML=""}),s&&Object.entries(s).forEach(function(t){var r=_sliced_to_array(t,2),n=r[0],a=r[1].messages,o=e.querySelector('[data-fetch-errors="'.concat(n,'"]'));o&&a.forEach(function(e){o.insertAdjacentHTML("afterbegin","<div>".concat(e,"</div>"))})}),"function"==typeof a.onFail&&a.onFail(r),l.label=4;case 4:return[2,r]}})}),function(e){return n.apply(this,arguments)})).then(function(e){"function"==typeof a.onAlways&&a.onAlways(e)}).catch(function(e){"function"==typeof a.onFail&&a.onFail(e)})}},{key:"printFormData",value:function(e){var t=!0,r=!1,n=void 0;try{for(var a,o=e.entries()[Symbol.iterator]();!(t=(a=o.next()).done);t=!0){var i=a.value;"object"===_type_of(i[1])?(console.log(i[0]),console.log(i[1]),console.log(JSON.stringify(i[1],null,4))):console.log(i[0]+", "+i[1])}}catch(e){r=!0,n=e}finally{try{t||null==o.return||o.return()}finally{if(r)throw n}}}}]),e}();
|
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* FetchDataForms.js
|
|
3
|
+
*
|
|
4
|
+
* Instantly turn html form elements into asynchronous fetch forms by adding an attribute.
|
|
5
|
+
*
|
|
6
|
+
* @author Nick Adams
|
|
7
|
+
* @see {@link https://github.com/nickolasjadams/fetch-data-forms|Repository}
|
|
8
|
+
* @license MIT
|
|
9
|
+
* @version 1.0.0
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
class FetchDataForms {
|
|
13
|
+
|
|
14
|
+
constructor(options) {
|
|
15
|
+
this.selector = "form[data-fetch]";
|
|
16
|
+
this.submitDisabledDuration = 1500;
|
|
17
|
+
this.recaptcha = {
|
|
18
|
+
version: "v3"
|
|
19
|
+
};
|
|
20
|
+
this.onDone = "";
|
|
21
|
+
this.onFail = "";
|
|
22
|
+
this.onAlways = "";
|
|
23
|
+
this.onBeforeSend = "";
|
|
24
|
+
if (options) {
|
|
25
|
+
if (options.selector) {
|
|
26
|
+
this.selector = options.selector;
|
|
27
|
+
}
|
|
28
|
+
if (options.submitDisabledDuration) {
|
|
29
|
+
this.submitDisabledDuration = options.submitDisabledDuration;
|
|
30
|
+
}
|
|
31
|
+
if (options.recaptcha) {
|
|
32
|
+
this.recaptcha = { ...this.recaptcha, ...options.recaptcha };
|
|
33
|
+
if (parseInt(this.recaptcha.version)) {
|
|
34
|
+
this.recaptcha.version = "v" + this.recaptcha.version;
|
|
35
|
+
} else {
|
|
36
|
+
this.recaptcha.version = this.recaptcha.version.toLowerCase();
|
|
37
|
+
}
|
|
38
|
+
if (this.recaptcha.version !== "v3") {
|
|
39
|
+
console.warn("Only reCAPTCHA v3 is supported at this time.");
|
|
40
|
+
}
|
|
41
|
+
if (!this.recaptcha.siteKey) {
|
|
42
|
+
console.warn("reCAPTCHA siteKey must be set.")
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
this.forms = document.querySelectorAll(this.selector);
|
|
48
|
+
this.addFormEventListeners();
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
addFormEventListeners() {
|
|
52
|
+
let _this = this;
|
|
53
|
+
this.forms.forEach(function (form) {
|
|
54
|
+
form.addEventListener("submit", function(e) {
|
|
55
|
+
e.preventDefault();
|
|
56
|
+
|
|
57
|
+
let form, data, submitter;
|
|
58
|
+
[form, data, submitter] = _this.prepFormData(this, e);
|
|
59
|
+
|
|
60
|
+
// console.log(data);
|
|
61
|
+
|
|
62
|
+
if (form.dataset['fetchRecaptcha'] === '') {
|
|
63
|
+
if (typeof window['grecaptcha'] === "undefined") {
|
|
64
|
+
console.warn("reCAPTCHA objects couldn't be found. Have the scripts been loaded?");
|
|
65
|
+
} else {
|
|
66
|
+
window['grecaptcha'].ready(function() {
|
|
67
|
+
window['grecaptcha'].execute(_this.recaptcha.siteKey, {action: 'submit'}).then(function(token) {
|
|
68
|
+
data['recaptcha_token'] = token;
|
|
69
|
+
_this.sendXhrRequest(form, data, submitter);
|
|
70
|
+
});
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
} else {
|
|
74
|
+
_this.sendXhrRequest(form, data, submitter);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
}, false)
|
|
78
|
+
})
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
prepFormData(form, submissionEvent) {
|
|
82
|
+
this.onDone = window[form.getAttribute('data-fetch-done')];
|
|
83
|
+
this.onFail = window[form.getAttribute('data-fetch-fail')];
|
|
84
|
+
this.onAlways = window[form.getAttribute('data-fetch-always')];
|
|
85
|
+
this.onBeforeSend = window[form.getAttribute('data-fetch-before-send')];
|
|
86
|
+
let submitter = submissionEvent.submitter;
|
|
87
|
+
let formData = new FormData(form, submitter);
|
|
88
|
+
if (submitter) {
|
|
89
|
+
submitter.disabled = "disabled";
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
let data = {};
|
|
93
|
+
for (const [key, value] of formData) {
|
|
94
|
+
let formElements = document.querySelectorAll("[name='" + key + "']");
|
|
95
|
+
if (formElements.length > 1) { // multiple elements with the same 'name' attribute
|
|
96
|
+
let isSubmissionElement = (formElements[0].tagName === "INPUT" && formElements[0].type === "submit") || (formElements[0].tagName === "BUTTON" && formElements[0].type !== "button");
|
|
97
|
+
let isRadioElement = formElements[0].tagName === "INPUT" && formElements[0].type === "radio";
|
|
98
|
+
if (isSubmissionElement) { // Make scalar because only one element can submit the form
|
|
99
|
+
data[key] = formData.get(key)
|
|
100
|
+
} else if (isRadioElement) { // Make scalar because only one item is selected
|
|
101
|
+
data[key] = formData.get(key)
|
|
102
|
+
} else { // Make an array because this is assumed to be checkboxes
|
|
103
|
+
data[key] = formData.getAll(key)
|
|
104
|
+
}
|
|
105
|
+
} else {
|
|
106
|
+
let isMultipleSelect = formElements[0].tagName === "SELECT" && formElements[0].attributes["multiple"]
|
|
107
|
+
let isMultipleFiles = formElements[0].tagName === "INPUT" && formElements[0].type === "file" && formElements[0].attributes["multiple"]
|
|
108
|
+
if (isMultipleSelect || isMultipleFiles) { // Make an array because multiple values are assumed available
|
|
109
|
+
data[key] = formData.getAll(key)
|
|
110
|
+
} else {
|
|
111
|
+
data[key] = formData.get(key)
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
let rData = new FormData();
|
|
116
|
+
Object.entries(data).forEach(([key, value]) => {
|
|
117
|
+
|
|
118
|
+
// arrays
|
|
119
|
+
if (Array.isArray(value)) {
|
|
120
|
+
// console.log("An array was submitted with this request.")
|
|
121
|
+
value.forEach(item => {
|
|
122
|
+
rData.append(key, item);
|
|
123
|
+
// console.log(item);
|
|
124
|
+
})
|
|
125
|
+
} else {
|
|
126
|
+
// everything else
|
|
127
|
+
rData.append(key, value);
|
|
128
|
+
// console.log(value);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// this.printFormData(rData);
|
|
132
|
+
});
|
|
133
|
+
return [ form, rData, submitter ];
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
sendXhrRequest(form, data, submitter) {
|
|
137
|
+
let _this = this;
|
|
138
|
+
// console.table(data);
|
|
139
|
+
|
|
140
|
+
let fetchOptions = {
|
|
141
|
+
method: form.method
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
if (form.method.toUpperCase() === "GET") {
|
|
145
|
+
const params = new URLSearchParams();
|
|
146
|
+
for (const pair of data.entries()) {
|
|
147
|
+
params.append(pair[0], pair[1]);
|
|
148
|
+
}
|
|
149
|
+
form.action += (form.action.includes('?') ? '&' : '?') + params.toString();
|
|
150
|
+
} else { // POST
|
|
151
|
+
fetchOptions.body = data;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
if (submitter) {
|
|
155
|
+
setTimeout(() => {
|
|
156
|
+
submitter.removeAttribute("disabled");
|
|
157
|
+
}, _this.submitDisabledDuration);
|
|
158
|
+
if (typeof _this.onBeforeSend === "function") _this.onBeforeSend();
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
fetch(form.action, fetchOptions)
|
|
162
|
+
.then(async response => {
|
|
163
|
+
let responseData;
|
|
164
|
+
if (response.ok) {
|
|
165
|
+
// console.log("OK")
|
|
166
|
+
responseData = await response.json();
|
|
167
|
+
form.reset();
|
|
168
|
+
document.querySelectorAll("[data-fetch-errors]").forEach(element => {
|
|
169
|
+
element.innerHTML = "";
|
|
170
|
+
});
|
|
171
|
+
if (typeof _this.onDone === "function") _this.onDone(responseData);
|
|
172
|
+
if (form.id) {
|
|
173
|
+
let id = form.id.replace(/([a-z])([A-Z])/g, "$1-$2").replace(/[\s_]+/g, '-').toLowerCase();
|
|
174
|
+
form.dispatchEvent(new CustomEvent(id + "-submit", { detail: responseData }));
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
let errors = responseData.errors || responseData.responseJSON?.errors;
|
|
178
|
+
form.querySelectorAll("[data-fetch-errors]").forEach(errorElement => {
|
|
179
|
+
errorElement.innerHTML = "";
|
|
180
|
+
});
|
|
181
|
+
if (errors) {
|
|
182
|
+
Object.entries(errors).forEach(([key, value]) => {
|
|
183
|
+
let messages = value['messages'];
|
|
184
|
+
let errorElement = form.querySelector(`[data-fetch-errors="${key}"]`);
|
|
185
|
+
if (errorElement) {
|
|
186
|
+
messages.forEach(message => {
|
|
187
|
+
errorElement.insertAdjacentHTML("afterbegin", `<div>${message}</div>`);
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
});
|
|
191
|
+
}
|
|
192
|
+
if (typeof _this.onFail === "function") _this.onFail(responseData);
|
|
193
|
+
} else {
|
|
194
|
+
responseData = await response.json();
|
|
195
|
+
let errors = responseData.errors || responseData.responseJSON?.errors;
|
|
196
|
+
form.querySelectorAll("[data-fetch-errors]").forEach(errorElement => {
|
|
197
|
+
errorElement.innerHTML = "";
|
|
198
|
+
});
|
|
199
|
+
if (errors) {
|
|
200
|
+
Object.entries(errors).forEach(([key, value]) => {
|
|
201
|
+
let messages = value['messages'];
|
|
202
|
+
let errorElement = form.querySelector(`[data-fetch-errors="${key}"]`);
|
|
203
|
+
if (errorElement) {
|
|
204
|
+
messages.forEach(message => {
|
|
205
|
+
errorElement.insertAdjacentHTML("afterbegin", `<div>${message}</div>`);
|
|
206
|
+
});
|
|
207
|
+
}
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
if (typeof _this.onFail === "function") _this.onFail(responseData);
|
|
211
|
+
}
|
|
212
|
+
return responseData;
|
|
213
|
+
})
|
|
214
|
+
.then(data => {
|
|
215
|
+
// console.log(data);
|
|
216
|
+
if (typeof _this.onAlways === "function") _this.onAlways(data);
|
|
217
|
+
})
|
|
218
|
+
.catch(error => {
|
|
219
|
+
if (typeof _this.onFail === "function") _this.onFail(error);
|
|
220
|
+
});
|
|
221
|
+
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
printFormData(formData) {
|
|
225
|
+
for (var pair of formData.entries()) {
|
|
226
|
+
if (typeof(pair[1]) === "object") {
|
|
227
|
+
console.log(pair[0]);
|
|
228
|
+
console.log(pair[1])
|
|
229
|
+
console.log(JSON.stringify(pair[1], null, 4))
|
|
230
|
+
} else {
|
|
231
|
+
console.log(pair[0]+ ', ' + pair[1]);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
}
|
package/spack.config.js
ADDED