@stegopop/fetch-data-forms 1.0.0 → 1.0.4

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/README.md CHANGED
@@ -32,13 +32,13 @@ Just add the `data-fetch` attribute to any form you'd like to convert.
32
32
  With NPM
33
33
 
34
34
  ```markdown
35
- npm install @stegopop/data-fetch-forms
35
+ npm install @stegopop/fetch-data-forms
36
36
  ```
37
37
 
38
38
  With a CDN
39
39
 
40
40
  ```html
41
- <script src="https://cdn.jsdelivr.net/npm/@stegopop/data-fetch-forms"></script>
41
+ <script src="https://cdn.jsdelivr.net/npm/@stegopop/fetch-data-forms"></script>
42
42
  ```
43
43
 
44
44
  ## Options
@@ -0,0 +1,320 @@
1
+ "use strict";
2
+
3
+ function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
4
+ function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; }
5
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
6
+ function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
7
+ function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
8
+ function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
9
+ function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
10
+ function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
11
+ function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
12
+ function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
13
+ function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
14
+ function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
15
+ function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
16
+ function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
17
+ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
18
+ function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
19
+ function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
20
+ function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
21
+ function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
22
+ /**
23
+ * FetchDataForms.js
24
+ *
25
+ * Instantly turn html form elements into asynchronous fetch forms by adding an attribute.
26
+ *
27
+ * @author Nick Adams
28
+ * @see {@link https://github.com/nickolasjadams/fetch-data-forms|Repository}
29
+ * @license MIT
30
+ * @version 1.0.0
31
+ */
32
+ var FetchDataForms = /*#__PURE__*/function () {
33
+ function FetchDataForms(options) {
34
+ _classCallCheck(this, FetchDataForms);
35
+ this.selector = "form[data-fetch]";
36
+ this.submitDisabledDuration = 1500;
37
+ this.recaptcha = {
38
+ version: "v3"
39
+ };
40
+ this.onDone = "";
41
+ this.onFail = "";
42
+ this.onAlways = "";
43
+ this.onBeforeSend = "";
44
+ if (options) {
45
+ if (options.selector) {
46
+ this.selector = options.selector;
47
+ }
48
+ if (options.submitDisabledDuration) {
49
+ this.submitDisabledDuration = options.submitDisabledDuration;
50
+ }
51
+ if (options.recaptcha) {
52
+ this.recaptcha = _objectSpread(_objectSpread({}, this.recaptcha), options.recaptcha);
53
+ if (parseInt(this.recaptcha.version)) {
54
+ this.recaptcha.version = "v" + this.recaptcha.version;
55
+ } else {
56
+ this.recaptcha.version = this.recaptcha.version.toLowerCase();
57
+ }
58
+ if (this.recaptcha.version !== "v3") {
59
+ console.warn("Only reCAPTCHA v3 is supported at this time.");
60
+ }
61
+ if (!this.recaptcha.siteKey) {
62
+ console.warn("reCAPTCHA siteKey must be set.");
63
+ }
64
+ }
65
+ }
66
+ this.forms = document.querySelectorAll(this.selector);
67
+ this.addFormEventListeners();
68
+ }
69
+ return _createClass(FetchDataForms, [{
70
+ key: "addFormEventListeners",
71
+ value: function addFormEventListeners() {
72
+ var _this = this;
73
+ this.forms.forEach(function (form) {
74
+ form.addEventListener("submit", function (e) {
75
+ e.preventDefault();
76
+ var form, data, submitter;
77
+ // console.log(data);
78
+ var _this$prepFormData = _this.prepFormData(this, e);
79
+ var _this$prepFormData2 = _slicedToArray(_this$prepFormData, 3);
80
+ form = _this$prepFormData2[0];
81
+ data = _this$prepFormData2[1];
82
+ submitter = _this$prepFormData2[2];
83
+ if (form.dataset['fetchRecaptcha'] === '') {
84
+ if (typeof window['grecaptcha'] === "undefined") {
85
+ console.warn("reCAPTCHA objects couldn't be found. Have the scripts been loaded?");
86
+ } else {
87
+ window['grecaptcha'].ready(function () {
88
+ window['grecaptcha'].execute(_this.recaptcha.siteKey, {
89
+ action: 'submit'
90
+ }).then(function (token) {
91
+ data['recaptcha_token'] = token;
92
+ _this.sendXhrRequest(form, data, submitter);
93
+ });
94
+ });
95
+ }
96
+ } else {
97
+ _this.sendXhrRequest(form, data, submitter);
98
+ }
99
+ }, false);
100
+ });
101
+ }
102
+ }, {
103
+ key: "prepFormData",
104
+ value: function prepFormData(form, submissionEvent) {
105
+ this.onDone = window[form.getAttribute('data-fetch-done')];
106
+ this.onFail = window[form.getAttribute('data-fetch-fail')];
107
+ this.onAlways = window[form.getAttribute('data-fetch-always')];
108
+ this.onBeforeSend = window[form.getAttribute('data-fetch-before-send')];
109
+ var submitter = submissionEvent.submitter;
110
+ var formData = new FormData(form, submitter);
111
+ if (submitter) {
112
+ submitter.disabled = "disabled";
113
+ }
114
+ var data = {};
115
+ var _iterator = _createForOfIteratorHelper(formData),
116
+ _step;
117
+ try {
118
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
119
+ var _step$value = _slicedToArray(_step.value, 2),
120
+ key = _step$value[0],
121
+ value = _step$value[1];
122
+ var formElements = document.querySelectorAll("[name='" + key + "']");
123
+ if (formElements.length > 1) {
124
+ // multiple elements with the same 'name' attribute
125
+ var isSubmissionElement = formElements[0].tagName === "INPUT" && formElements[0].type === "submit" || formElements[0].tagName === "BUTTON" && formElements[0].type !== "button";
126
+ var isRadioElement = formElements[0].tagName === "INPUT" && formElements[0].type === "radio";
127
+ if (isSubmissionElement) {
128
+ // Make scalar because only one element can submit the form
129
+ data[key] = formData.get(key);
130
+ } else if (isRadioElement) {
131
+ // Make scalar because only one item is selected
132
+ data[key] = formData.get(key);
133
+ } else {
134
+ // Make an array because this is assumed to be checkboxes
135
+ data[key] = formData.getAll(key);
136
+ }
137
+ } else {
138
+ var isMultipleSelect = formElements[0].tagName === "SELECT" && formElements[0].attributes["multiple"];
139
+ var isMultipleFiles = formElements[0].tagName === "INPUT" && formElements[0].type === "file" && formElements[0].attributes["multiple"];
140
+ if (isMultipleSelect || isMultipleFiles) {
141
+ // Make an array because multiple values are assumed available
142
+ data[key] = formData.getAll(key);
143
+ } else {
144
+ data[key] = formData.get(key);
145
+ }
146
+ }
147
+ }
148
+ } catch (err) {
149
+ _iterator.e(err);
150
+ } finally {
151
+ _iterator.f();
152
+ }
153
+ var rData = new FormData();
154
+ Object.entries(data).forEach(function (_ref) {
155
+ var _ref2 = _slicedToArray(_ref, 2),
156
+ key = _ref2[0],
157
+ value = _ref2[1];
158
+ // arrays
159
+ if (Array.isArray(value)) {
160
+ // console.log("An array was submitted with this request.")
161
+ value.forEach(function (item) {
162
+ rData.append(key, item);
163
+ // console.log(item);
164
+ });
165
+ } else {
166
+ // everything else
167
+ rData.append(key, value);
168
+ // console.log(value);
169
+ }
170
+
171
+ // this.printFormData(rData);
172
+ });
173
+ return [form, rData, submitter];
174
+ }
175
+ }, {
176
+ key: "sendXhrRequest",
177
+ value: function sendXhrRequest(form, data, submitter) {
178
+ var _this = this;
179
+ // console.table(data);
180
+
181
+ var fetchOptions = {
182
+ method: form.method
183
+ };
184
+ if (form.method.toUpperCase() === "GET") {
185
+ var params = new URLSearchParams();
186
+ var _iterator2 = _createForOfIteratorHelper(data.entries()),
187
+ _step2;
188
+ try {
189
+ for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
190
+ var pair = _step2.value;
191
+ params.append(pair[0], pair[1]);
192
+ }
193
+ } catch (err) {
194
+ _iterator2.e(err);
195
+ } finally {
196
+ _iterator2.f();
197
+ }
198
+ form.action += (form.action.includes('?') ? '&' : '?') + params.toString();
199
+ } else {
200
+ // POST
201
+ fetchOptions.body = data;
202
+ }
203
+ if (submitter) {
204
+ setTimeout(function () {
205
+ submitter.removeAttribute("disabled");
206
+ }, _this.submitDisabledDuration);
207
+ if (typeof _this.onBeforeSend === "function") _this.onBeforeSend();
208
+ }
209
+ fetch(form.action, fetchOptions).then( /*#__PURE__*/function () {
210
+ var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(response) {
211
+ var responseData, _responseData$respons, id, errors, _responseData$respons2, _errors;
212
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
213
+ while (1) switch (_context.prev = _context.next) {
214
+ case 0:
215
+ if (!response.ok) {
216
+ _context.next = 14;
217
+ break;
218
+ }
219
+ _context.next = 3;
220
+ return response.json();
221
+ case 3:
222
+ responseData = _context.sent;
223
+ form.reset();
224
+ document.querySelectorAll("[data-fetch-errors]").forEach(function (element) {
225
+ element.innerHTML = "";
226
+ });
227
+ if (typeof _this.onDone === "function") _this.onDone(responseData);
228
+ if (form.id) {
229
+ id = form.id.replace(/([a-z])([A-Z])/g, "$1-$2").replace(/[\s_]+/g, '-').toLowerCase();
230
+ form.dispatchEvent(new CustomEvent(id + "-submit", {
231
+ detail: responseData
232
+ }));
233
+ }
234
+ errors = responseData.errors || ((_responseData$respons = responseData.responseJSON) === null || _responseData$respons === void 0 ? void 0 : _responseData$respons.errors);
235
+ form.querySelectorAll("[data-fetch-errors]").forEach(function (errorElement) {
236
+ errorElement.innerHTML = "";
237
+ });
238
+ if (errors) {
239
+ Object.entries(errors).forEach(function (_ref4) {
240
+ var _ref5 = _slicedToArray(_ref4, 2),
241
+ key = _ref5[0],
242
+ value = _ref5[1];
243
+ var messages = value['messages'];
244
+ var errorElement = form.querySelector("[data-fetch-errors=\"".concat(key, "\"]"));
245
+ if (errorElement) {
246
+ messages.forEach(function (message) {
247
+ errorElement.insertAdjacentHTML("afterbegin", "<div>".concat(message, "</div>"));
248
+ });
249
+ }
250
+ });
251
+ }
252
+ if (typeof _this.onFail === "function") _this.onFail(responseData);
253
+ _context.next = 21;
254
+ break;
255
+ case 14:
256
+ _context.next = 16;
257
+ return response.json();
258
+ case 16:
259
+ responseData = _context.sent;
260
+ _errors = responseData.errors || ((_responseData$respons2 = responseData.responseJSON) === null || _responseData$respons2 === void 0 ? void 0 : _responseData$respons2.errors);
261
+ form.querySelectorAll("[data-fetch-errors]").forEach(function (errorElement) {
262
+ errorElement.innerHTML = "";
263
+ });
264
+ if (_errors) {
265
+ Object.entries(_errors).forEach(function (_ref6) {
266
+ var _ref7 = _slicedToArray(_ref6, 2),
267
+ key = _ref7[0],
268
+ value = _ref7[1];
269
+ var messages = value['messages'];
270
+ var errorElement = form.querySelector("[data-fetch-errors=\"".concat(key, "\"]"));
271
+ if (errorElement) {
272
+ messages.forEach(function (message) {
273
+ errorElement.insertAdjacentHTML("afterbegin", "<div>".concat(message, "</div>"));
274
+ });
275
+ }
276
+ });
277
+ }
278
+ if (typeof _this.onFail === "function") _this.onFail(responseData);
279
+ case 21:
280
+ return _context.abrupt("return", responseData);
281
+ case 22:
282
+ case "end":
283
+ return _context.stop();
284
+ }
285
+ }, _callee);
286
+ }));
287
+ return function (_x) {
288
+ return _ref3.apply(this, arguments);
289
+ };
290
+ }()).then(function (data) {
291
+ // console.log(data);
292
+ if (typeof _this.onAlways === "function") _this.onAlways(data);
293
+ }).catch(function (error) {
294
+ if (typeof _this.onFail === "function") _this.onFail(error);
295
+ });
296
+ }
297
+ }, {
298
+ key: "printFormData",
299
+ value: function printFormData(formData) {
300
+ var _iterator3 = _createForOfIteratorHelper(formData.entries()),
301
+ _step3;
302
+ try {
303
+ for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
304
+ var pair = _step3.value;
305
+ if (_typeof(pair[1]) === "object") {
306
+ console.log(pair[0]);
307
+ console.log(pair[1]);
308
+ console.log(JSON.stringify(pair[1], null, 4));
309
+ } else {
310
+ console.log(pair[0] + ', ' + pair[1]);
311
+ }
312
+ }
313
+ } catch (err) {
314
+ _iterator3.e(err);
315
+ } finally {
316
+ _iterator3.f();
317
+ }
318
+ }
319
+ }]);
320
+ }();
@@ -0,0 +1,11 @@
1
+ "use strict";function _typeof(o){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o})(o)}function _regeneratorRuntime(){_regeneratorRuntime=function _regeneratorRuntime(){return e};var t,e={},r=Object.prototype,n=r.hasOwnProperty,o=Object.defineProperty||function(t,e,r){t[e]=r.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",c=i.asyncIterator||"@@asyncIterator",u=i.toStringTag||"@@toStringTag";function define(t,e,r){return Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{define({},"")}catch(t){define=function define(t,e,r){return t[e]=r}}function wrap(t,e,r,n){e=e&&e.prototype instanceof Generator?e:Generator,e=Object.create(e.prototype),n=new Context(n||[]);return o(e,"_invoke",{value:makeInvokeMethod(t,r,n)}),e}function tryCatch(t,e,r){try{return{type:"normal",arg:t.call(e,r)}}catch(t){return{type:"throw",arg:t}}}e.wrap=wrap;var h="suspendedStart",l="suspendedYield",f="executing",s="completed",y={};function Generator(){}function GeneratorFunction(){}function GeneratorFunctionPrototype(){}var i={},d=(define(i,a,function(){return this}),Object.getPrototypeOf),d=d&&d(d(values([]))),g=(d&&d!==r&&n.call(d,a)&&(i=d),GeneratorFunctionPrototype.prototype=Generator.prototype=Object.create(i));function defineIteratorMethods(t){["next","throw","return"].forEach(function(e){define(t,e,function(t){return this._invoke(e,t)})})}function AsyncIterator(t,e){function invoke(r,o,i,a){var u,r=tryCatch(t[r],t,o);if("throw"!==r.type)return(o=(u=r.arg).value)&&"object"==_typeof(o)&&n.call(o,"__await")?e.resolve(o.__await).then(function(t){invoke("next",t,i,a)},function(t){invoke("throw",t,i,a)}):e.resolve(o).then(function(t){u.value=t,i(u)},function(t){return invoke("throw",t,i,a)});a(r.arg)}var r;o(this,"_invoke",{value:function(t,n){function callInvokeWithMethodAndArg(){return new e(function(e,r){invoke(t,n,e,r)})}return r=r?r.then(callInvokeWithMethodAndArg,callInvokeWithMethodAndArg):callInvokeWithMethodAndArg()}})}function makeInvokeMethod(e,r,n){var o=h;return function(i,a){if(o===f)throw Error("Generator is already running");if(o===s){if("throw"===i)throw a;return{value:t,done:!0}}for(n.method=i,n.arg=a;;){var c=n.delegate;if(c){c=function maybeInvokeDelegate(e,r){var n=r.method,o=e.iterator[n];if(o===t)return r.delegate=null,"throw"===n&&e.iterator["return"]&&(r.method="return",r.arg=t,maybeInvokeDelegate(e,r),"throw"===r.method)||"return"!==n&&(r.method="throw",r.arg=new TypeError("The iterator does not provide a '"+n+"' method")),y;n=tryCatch(o,e.iterator,r.arg);if("throw"===n.type)return r.method="throw",r.arg=n.arg,r.delegate=null,y;o=n.arg;return o?o.done?(r[e.resultName]=o.value,r.next=e.nextLoc,"return"!==r.method&&(r.method="next",r.arg=t),r.delegate=null,y):o:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,y)}(c,n);if(c){if(c===y)continue;return c}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(o===h)throw o=s,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);o=f;c=tryCatch(e,r,n);if("normal"===c.type){if(o=n.done?s:l,c.arg===y)continue;return{value:c.arg,done:n.done}}"throw"===c.type&&(o=s,n.method="throw",n.arg=c.arg)}}}function pushTryEntry(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function resetTryEntry(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function Context(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(pushTryEntry,this),this.reset(!0)}function values(e){if(e||""===e){var o,r=e[a];if(r)return r.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length))return o=-1,(r=function next(){for(;++o<e.length;)if(n.call(e,o))return next.value=e[o],next.done=!1,next;return next.value=t,next.done=!0,next}).next=r}throw new TypeError(_typeof(e)+" is not iterable")}return o(g,"constructor",{value:GeneratorFunction.prototype=GeneratorFunctionPrototype,configurable:!0}),o(GeneratorFunctionPrototype,"constructor",{value:GeneratorFunction,configurable:!0}),GeneratorFunction.displayName=define(GeneratorFunctionPrototype,u,"GeneratorFunction"),e.isGeneratorFunction=function(t){t="function"==typeof t&&t.constructor;return!!t&&(t===GeneratorFunction||"GeneratorFunction"===(t.displayName||t.name))},e.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,GeneratorFunctionPrototype):(t.__proto__=GeneratorFunctionPrototype,define(t,u,"GeneratorFunction")),t.prototype=Object.create(g),t},e.awrap=function(t){return{__await:t}},defineIteratorMethods(AsyncIterator.prototype),define(AsyncIterator.prototype,c,function(){return this}),e.AsyncIterator=AsyncIterator,e["async"]=function(t,r,n,o,i){void 0===i&&(i=Promise);var a=new AsyncIterator(wrap(t,r,n,o),i);return e.isGeneratorFunction(r)?a:a.next().then(function(t){return t.done?t.value:a.next()})},defineIteratorMethods(g),define(g,u,"Generator"),define(g,a,function(){return this}),define(g,"toString",function(){return"[object Generator]"}),e.keys=function(t){var n,e=Object(t),r=[];for(n in e)r.push(n);return r.reverse(),function next(){for(;r.length;){var t=r.pop();if(t in e)return next.value=t,next.done=!1,next}return next.done=!0,next}},e.values=values,Context.prototype={constructor:Context,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=t,this.done=!1,this.delegate=null,this.method="next",this.arg=t,this.tryEntries.forEach(resetTryEntry),!e)for(var r in this)"t"===r.charAt(0)&&n.call(this,r)&&!isNaN(+r.slice(1))&&(this[r]=t)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var r=this;function handle(n,o){return a.type="throw",a.arg=e,r.next=n,o&&(r.method="next",r.arg=t),!!o}for(var o=this.tryEntries.length-1;0<=o;--o){var i=this.tryEntries[o],a=i.completion;if("root"===i.tryLoc)return handle("end");if(i.tryLoc<=this.prev){var c=n.call(i,"catchLoc"),u=n.call(i,"finallyLoc");if(c&&u){if(this.prev<i.catchLoc)return handle(i.catchLoc,!0);if(this.prev<i.finallyLoc)return handle(i.finallyLoc)}else if(c){if(this.prev<i.catchLoc)return handle(i.catchLoc,!0)}else{if(!u)throw Error("try statement without catch or finally");if(this.prev<i.finallyLoc)return handle(i.finallyLoc)}}}},abrupt:function(t,e){for(var r=this.tryEntries.length-1;0<=r;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev<o.finallyLoc){var i=o;break}}var a=(i=i&&("break"===t||"continue"===t)&&i.tryLoc<=e&&e<=i.finallyLoc?null:i)?i.completion:{};return a.type=t,a.arg=e,i?(this.method="next",this.next=i.finallyLoc,y):this.complete(a)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),y},finish:function(t){for(var e=this.tryEntries.length-1;0<=e;--e){var r=this.tryEntries[e];if(r.finallyLoc===t)return this.complete(r.completion,r.afterLoc),resetTryEntry(r),y}},"catch":function(t){for(var e=this.tryEntries.length-1;0<=e;--e){var n,o,r=this.tryEntries[e];if(r.tryLoc===t)return"throw"===(n=r.completion).type&&(o=n.arg,resetTryEntry(r)),o}throw Error("illegal catch attempt")},delegateYield:function(e,r,n){return this.delegate={iterator:values(e),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=t),y}},e}function asyncGeneratorStep(gen,resolve,reject,_next,_throw,key,arg){try{var info=gen[key](arg),value=info.value}catch(error){return void reject(error)}info.done?resolve(value):Promise.resolve(value).then(_next,_throw)}function _asyncToGenerator(fn){return function(){var self=this,args=arguments;return new Promise(function(resolve,reject){var gen=fn.apply(self,args);function _next(value){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"next",value)}function _throw(err){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"throw",err)}_next(undefined)})}}function _createForOfIteratorHelper(o,allowArrayLike){var normalCompletion,didErr,err,i,F,it="undefined"!=typeof Symbol&&o[Symbol.iterator]||o["@@iterator"];if(it)return didErr=!(normalCompletion=!0),{s:function(){it=it.call(o)},n:function(){var step=it.next();return normalCompletion=step.done,step},e:function(_e2){didErr=!0,err=_e2},f:function(){try{normalCompletion||null==it["return"]||it["return"]()}finally{if(didErr)throw err}}};if(Array.isArray(o)||(it=_unsupportedIterableToArray(o))||allowArrayLike&&o&&"number"==typeof o.length)return it&&(o=it),i=0,{s:F=function F(){},n:function(){return i>=o.length?{done:!0}:{done:!1,value:o[i++]}},e:function(_e){throw _e},f:F};throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _slicedToArray(arr,i){return _arrayWithHoles(arr)||_iterableToArrayLimit(arr,i)||_unsupportedIterableToArray(arr,i)||_nonIterableRest()}function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _unsupportedIterableToArray(o,minLen){var n;if(o)return"string"==typeof o?_arrayLikeToArray(o,minLen):"Map"===(n="Object"===(n=Object.prototype.toString.call(o).slice(8,-1))&&o.constructor?o.constructor.name:n)||"Set"===n?Array.from(o):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray(o,minLen):void 0}function _arrayLikeToArray(arr,len){(null==len||len>arr.length)&&(len=arr.length);for(var i=0,arr2=new Array(len);i<len;i++)arr2[i]=arr[i];return arr2}function _iterableToArrayLimit(r,l){var t=null==r?null:"undefined"!=typeof Symbol&&r[Symbol.iterator]||r["@@iterator"];if(null!=t){var e,n,i,u,a=[],f=!0,o=!1;try{if(i=(t=t.call(r)).next,0===l){if(Object(t)!==t)return;f=!1}else for(;!(f=(e=i.call(t)).done)&&(a.push(e.value),a.length!==l);f=!0);}catch(r){o=!0,n=r}finally{try{if(!f&&null!=t["return"]&&(u=t["return"](),Object(u)!==u))return}finally{if(o)throw n}}return a}}function _arrayWithHoles(arr){if(Array.isArray(arr))return arr}function ownKeys(e,r){var o,t=Object.keys(e);return Object.getOwnPropertySymbols&&(o=Object.getOwnPropertySymbols(e),r&&(o=o.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable})),t.push.apply(t,o)),t}function _objectSpread(e){for(var r=1;r<arguments.length;r++){var t=null!=arguments[r]?arguments[r]:{};r%2?ownKeys(Object(t),!0).forEach(function(r){_defineProperty(e,r,t[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):ownKeys(Object(t)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(t,r))})}return e}function _defineProperty(obj,key,value){return(key=_toPropertyKey(key))in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,_toPropertyKey(descriptor.key),descriptor)}}function _createClass(Constructor,protoProps,staticProps){return protoProps&&_defineProperties(Constructor.prototype,protoProps),staticProps&&_defineProperties(Constructor,staticProps),Object.defineProperty(Constructor,"prototype",{writable:!1}),Constructor}function _toPropertyKey(t){t=_toPrimitive(t,"string");return"symbol"==_typeof(t)?t:t+""}function _toPrimitive(t,r){if("object"!=_typeof(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0===e)return("string"===r?String:Number)(t);t=e.call(t,r||"default");if("object"!=_typeof(t))return t;throw new TypeError("@@toPrimitive must return a primitive value.")}
2
+ /**
3
+ * FetchDataForms.js
4
+ *
5
+ * Instantly turn html form elements into asynchronous fetch forms by adding an attribute.
6
+ *
7
+ * @author Nick Adams
8
+ * @see {@link https://github.com/nickolasjadams/fetch-data-forms|Repository}
9
+ * @license MIT
10
+ * @version 1.0.0
11
+ */var FetchDataForms=function(){return _createClass(function FetchDataForms(options){_classCallCheck(this,FetchDataForms),this.selector="form[data-fetch]",this.submitDisabledDuration=1500,this.recaptcha={version:"v3"},this.onDone="",this.onFail="",this.onAlways="",this.onBeforeSend="",options&&(options.selector&&(this.selector=options.selector),options.submitDisabledDuration&&(this.submitDisabledDuration=options.submitDisabledDuration),options.recaptcha)&&(this.recaptcha=_objectSpread(_objectSpread({},this.recaptcha),options.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()},[{key:"addFormEventListeners",value:function(){var _this=this;this.forms.forEach(function(form){form.addEventListener("submit",function(e){e.preventDefault();var e=_slicedToArray(_this.prepFormData(this,e),3),form=e[0],data=e[1],submitter=e[2];""===form.dataset.fetchRecaptcha?"undefined"==typeof window.grecaptcha?console.warn("reCAPTCHA objects couldn't be found. Have the scripts been loaded?"):window.grecaptcha.ready(function(){window.grecaptcha.execute(_this.recaptcha.siteKey,{action:"submit"}).then(function(token){data.recaptcha_token=token,_this.sendXhrRequest(form,data,submitter)})}):_this.sendXhrRequest(form,data,submitter)},!1)})}},{key:"prepFormData",value:function(form,submissionEvent){this.onDone=window[form.getAttribute("data-fetch-done")],this.onFail=window[form.getAttribute("data-fetch-fail")],this.onAlways=window[form.getAttribute("data-fetch-always")],this.onBeforeSend=window[form.getAttribute("data-fetch-before-send")];var _step,submissionEvent=submissionEvent.submitter,formData=new FormData(form,submissionEvent),data=(submissionEvent&&(submissionEvent.disabled="disabled"),{}),_iterator=_createForOfIteratorHelper(formData);try{for(_iterator.s();!(_step=_iterator.n()).done;){var isSubmissionElement,isRadioElement,isMultipleSelect,isMultipleFiles,_step$value=_slicedToArray(_step.value,2),key=_step$value[0],formElements=(_step$value[1],document.querySelectorAll("[name='"+key+"']"));1<formElements.length?(isSubmissionElement="INPUT"===formElements[0].tagName&&"submit"===formElements[0].type||"BUTTON"===formElements[0].tagName&&"button"!==formElements[0].type,isRadioElement="INPUT"===formElements[0].tagName&&"radio"===formElements[0].type,data[key]=isSubmissionElement||isRadioElement?formData.get(key):formData.getAll(key)):(isMultipleSelect="SELECT"===formElements[0].tagName&&formElements[0].attributes.multiple,isMultipleFiles="INPUT"===formElements[0].tagName&&"file"===formElements[0].type&&formElements[0].attributes.multiple,data[key]=isMultipleSelect||isMultipleFiles?formData.getAll(key):formData.get(key))}}catch(err){_iterator.e(err)}finally{_iterator.f()}var rData=new FormData;return Object.entries(data).forEach(function(_ref){var _ref=_slicedToArray(_ref,2),key=_ref[0],_ref=_ref[1];Array.isArray(_ref)?_ref.forEach(function(item){rData.append(key,item)}):rData.append(key,_ref)}),[form,rData,submissionEvent]}},{key:"sendXhrRequest",value:function(form,data,submitter){var _this=this,fetchOptions={method:form.method};if("GET"===form.method.toUpperCase()){var _step2,params=new URLSearchParams,_iterator2=_createForOfIteratorHelper(data.entries());try{for(_iterator2.s();!(_step2=_iterator2.n()).done;){var pair=_step2.value;params.append(pair[0],pair[1])}}catch(err){_iterator2.e(err)}finally{_iterator2.f()}form.action+=(form.action.includes("?")?"&":"?")+params.toString()}else fetchOptions.body=data;submitter&&(setTimeout(function(){submitter.removeAttribute("disabled")},_this.submitDisabledDuration),"function"==typeof _this.onBeforeSend)&&_this.onBeforeSend(),fetch(form.action,fetchOptions).then(function(){var _ref3=_asyncToGenerator(_regeneratorRuntime().mark(function _callee(response){var responseData,id,errors,_errors;return _regeneratorRuntime().wrap(function(_context){for(;;)switch(_context.prev=_context.next){case 0:if(response.ok)return _context.next=3,response.json();_context.next=14;break;case 3:responseData=_context.sent,form.reset(),document.querySelectorAll("[data-fetch-errors]").forEach(function(element){element.innerHTML=""}),"function"==typeof _this.onDone&&_this.onDone(responseData),form.id&&(id=form.id.replace(/([a-z])([A-Z])/g,"$1-$2").replace(/[\s_]+/g,"-").toLowerCase(),form.dispatchEvent(new CustomEvent(id+"-submit",{detail:responseData}))),errors=responseData.errors||(null==(id=responseData.responseJSON)?void 0:id.errors),form.querySelectorAll("[data-fetch-errors]").forEach(function(errorElement){errorElement.innerHTML=""}),errors&&Object.entries(errors).forEach(function(_ref4){var _ref4=_slicedToArray(_ref4,2),key=_ref4[0],_ref4=_ref4[1].messages,errorElement=form.querySelector('[data-fetch-errors="'.concat(key,'"]'));errorElement&&_ref4.forEach(function(message){errorElement.insertAdjacentHTML("afterbegin","<div>".concat(message,"</div>"))})}),"function"==typeof _this.onFail&&_this.onFail(responseData),_context.next=21;break;case 14:return _context.next=16,response.json();case 16:responseData=_context.sent,_errors=responseData.errors||(null==(errors=responseData.responseJSON)?void 0:errors.errors),form.querySelectorAll("[data-fetch-errors]").forEach(function(errorElement){errorElement.innerHTML=""}),_errors&&Object.entries(_errors).forEach(function(_ref6){var _ref6=_slicedToArray(_ref6,2),key=_ref6[0],_ref6=_ref6[1].messages,errorElement=form.querySelector('[data-fetch-errors="'.concat(key,'"]'));errorElement&&_ref6.forEach(function(message){errorElement.insertAdjacentHTML("afterbegin","<div>".concat(message,"</div>"))})}),"function"==typeof _this.onFail&&_this.onFail(responseData);case 21:return _context.abrupt("return",responseData);case 22:case"end":return _context.stop()}},_callee)}));return function(_x){return _ref3.apply(this,arguments)}}()).then(function(data){"function"==typeof _this.onAlways&&_this.onAlways(data)})["catch"](function(error){"function"==typeof _this.onFail&&_this.onFail(error)})}},{key:"printFormData",value:function(formData){var _step3,_iterator3=_createForOfIteratorHelper(formData.entries());try{for(_iterator3.s();!(_step3=_iterator3.n()).done;){var pair=_step3.value;"object"===_typeof(pair[1])?(console.log(pair[0]),console.log(pair[1]),console.log(JSON.stringify(pair[1],null,4))):console.log(pair[0]+", "+pair[1])}}catch(err){_iterator3.e(err)}finally{_iterator3.f()}}}])}();
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@stegopop/fetch-data-forms",
3
- "version": "1.0.0",
3
+ "version": "1.0.4",
4
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",
5
+ "main": "public/dist/fetch-data-forms.min.js",
6
6
  "scripts": {
7
7
  "js": "babel public/src/FetchDataForms.js --out-file dist/fetch-data-forms.js",
8
8
  "watch": "npm run js -- --watch",