form-father 0.0.6 → 0.0.8
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/FormFather.min.js +1 -1
- package/README.md +9 -0
- package/index.d.ts +10 -0
- package/index.js +21 -4
- package/index.js.map +1 -1
- package/package.json +1 -1
- package/types/index.d.ts +10 -0
package/FormFather.min.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var FormFather=function(){"use strict";function t(t,e,r,n){return new(r||(r=Promise))((function(o,s){function i(t){try{c(n.next(t))}catch(t){s(t)}}function l(t){try{c(n.throw(t))}catch(t){s(t)}}function c(t){var e;t.done?o(t.value):(e=t.value,e instanceof r?e:new r((function(t){t(e)}))).then(i,l)}c((n=n.apply(t,e||[])).next())}))}function e(t){const e="FORM"===t.tagName?Array.from(t.elements):Array.from(t.querySelectorAll("input, select, textarea, button")),r=new FormData;return e.forEach((t=>{if(!(t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement||t instanceof HTMLButtonElement))return;if(!t.name||t.hasAttribute("data-no-serialize"))return;const{name:e,type:n}=t;if("file"===n)if("true"===t.getAttribute("multiple")){const n=t.files;if(n)for(let t=0;t<n.length;t++)r.append(`${e}[${t}]`,n[t])}else{const n=t.files;n&&n[0]&&r.append(e,n[0])}else{let o;if("tel"===n)o=t.value.split(/[\s()-]/).join("").replace(/^8/,"+7");else if("checkbox"===n||"radio"===n){if(!t.checked)return;o=t.value}else if("date"===n){const e=t.getAttribute("data-date-format");o=e?function(t,e){const r=new Date(t),n=t=>t.toString().padStart(2,"0"),o=n(r.getDate()),s=n(r.getMonth()+1),i=r.getFullYear().toString();return e.replace("dd",o).replace("mm",s).replace("yyyy",i)}(t.value,e):t.value}else o=t.value;r.append(e,o)}})),r}"function"==typeof SuppressedError&&SuppressedError;return class{constructor(t,e){this.$submit=null,this.waitResponse=!1,this.inputs=null,this.$licensesCheckbox=null,this.$el=t,this.options=e;this.config=Object.assign({},{onSubmit:()=>{},onResponse:()=>{},onResponseSuccess:()=>{},onResponseUnsuccess:()=>{},customTypeError:null,loaderColor:"#fff",showLoaderButton:!0,scrollToFirstErroredInput:!0,logging:!1},this.options),this.$el?(this.$submit=this.$el.querySelector('input[type="submit"], button[type="submit"]'),this.isCorrectArguments()&&this.initialization()):console.warn("Empty $el")}initialization(){this.inputs=this.$el.querySelectorAll(".input"),this.$licensesCheckbox=this.$el.querySelector('input[data-input-name="user-consent"]'),this.$licensesCheckbox&&(this.$licensesCheckbox.checked?this.enableSubmit():this.disableSubmit(),this.$licensesCheckbox.addEventListener("change",(()=>{this.$licensesCheckbox.checked?this.enableSubmit():this.disableSubmit()})));const r=e=>t(this,void 0,void 0,(function*(){return fetch(this.$el.getAttribute("action")||"",{method:"POST",body:e})})),n=()=>t(this,void 0,void 0,(function*(){var t,n,o,s,i,l,c,a;if(!this.waitResponse){const u=e(this.$el);if(!0===this.config.showLoaderButton&&this.showLoader(),null===(n=(t=this.config).onSubmit)||void 0===n||n.call(t,this),this.waitResponse=!0,this.config.logging)for(const t of u.keys())console.log(u.get(t));const h=yield r(u),d=yield h.json();if(this.waitResponse=!1,!0===this.config.showLoaderButton&&this.hideLoader(),null===(s=(o=this.config).onResponse)||void 0===s||s.call(o,d,this),200===h.status)if(function(t){if(Object.prototype.hasOwnProperty.call(t,"redirect-url")&&(window.location.href=t["redirect-url"]),Object.prototype.hasOwnProperty.call(t,"reload")&&!0===t.reload&&window.location.reload(),Object.prototype.hasOwnProperty.call(t,"error-toast")){const e=document.querySelector('[data-toast-name="formErrorToast"]');if(e){const r=e.querySelector(".toast__text");r&&(r.textContent=t["error-toast"],window.Toast.showToast("formErrorToast",{removeAfterClose:!1}))}}}(d),!0===d.success)null===(l=(i=this.config).onResponseSuccess)||void 0===l||l.call(i,d,this);else if(null===(a=(c=this.config).onResponseUnsuccess)||void 0===a||a.call(c,d,this),!0===d.error&&(d["error-msg"]&&this.showErrorForm(d["error-msg"]),d.errors)){const t=[];d.errors.forEach((e=>{const r=this.$el.querySelector(`input[name="${e.name}"]`);r?(t.push(r),this.showError(r,e["error-msg"])):console.warn(`Не найдено поле с именем: ${e.name}, для вывода ошибки: ${e["error-msg"]}`)})),!0===this.config.scrollToFirstErroredInput&&this.scrollToFirstErroredInput(t)}}}));this.$el.addEventListener("submit",(t=>{t.preventDefault(),this.checkInputs()&&(!this.$licensesCheckbox||this.$licensesCheckbox&&this.$licensesCheckbox.checked)&&n()}))}showError(t,e){(function(t,e){if(null==t)return null;let r=t;for(;r;){if(r.matches(e))return r;r=r.parentElement}return null})(t,"input-primary").showError(e)}showLoader(){var t;const e=`\n\t\t\t<svg height="38" viewBox="0 0 38 38" width="38" xmlns="http://www.w3.org/2000/svg">\n\t\t\t\t<defs>\n\t\t\t\t<linearGradient id="a" x1="8.042%" x2="65.682%" y1="0%" y2="23.865%">\n\t\t\t\t\t<stop offset="0%" stop-color="${this.config.loaderColor}" stop-opacity="0"/>\n\t\t\t\t\t<stop offset="63.146%" stop-color="${this.config.loaderColor}" stop-opacity=".631"/>\n\t\t\t\t\t<stop offset="100%" stop-color="${this.config.loaderColor}"/>\n\t\t\t\t</linearGradient>\n\t\t\t\t</defs>\n\t\t\t\t<g fill-rule="evenodd" fill="none">\n\t\t\t\t<g transform="translate(1 1)">\n\t\t\t\t\t<path d="M36 18c0-9.94-8.06-18-18-18" id="Oval-2" stroke-width="5" stroke="url(#a)"></path>\n\t\t\t\t\t<circle cx="36" cy="18" fill="${this.config.loaderColor}" r="1"></circle>\n\t\t\t\t</g>\n\t\t\t\t</g>\n\t\t\t</svg>\n\t\t`,r=document.createElement("span");r.innerHTML=e,r.className="button__loader",null===(t=this.$submit)||void 0===t||t.insertAdjacentElement("afterbegin",r),requestAnimationFrame((()=>{r.setAttribute("data-showed","")}))}hideLoader(){var t,e;null===(t=this.$submit)||void 0===t||t.classList.remove("button--loading");const r=null===(e=this.$submit)||void 0===e?void 0:e.querySelector(".button__loader");r&&(r.classList.remove("active"),r.removeAttribute("data-showed"),setTimeout((()=>{r.remove()}),250))}hideError(t){const e=t.parentElement;e&&e.classList.contains("input__wrapper")&&(e.getAttribute("data-type-error"),e.classList.remove("input__wrapper--error"))}scrollToFirstErroredInput(t){if(t.length>0){const e=Array.from(this.$el.querySelectorAll("input"));let r=null,n=1/0;t.forEach((t=>{const o=e.findIndex((e=>e===t));o<n&&(n=o,r=t)})),r&&(document.documentElement.setAttribute("data-now-scrolling",""),r.scrollIntoView({behavior:"smooth",block:"center",inline:"center"}),setTimeout((()=>{document.documentElement.removeAttribute("data-now-scrolling")}),800))}}checkInputs(){var t;let e=!0;const r={},n=[];if(null===(t=this.inputs)||void 0===t||t.forEach((t=>{var o;const s=t,i=s.getAttribute("data-check-type")||s.getAttribute("type")||"";if((null===(o=this.config.customTypeError)||void 0===o?void 0:o.name)!==i||"TEXTAREA"===s.tagName&&!this.config.customTypeError)if(s.value.length>0){if("email"===i&&(l=s.value,/^(([^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*)|(".+"))@(([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{2,})$/iu.test(l)||(this.showError(s,"Неверный формат"),n.push(s),e=!1)),"tel"===i){const t=this.config.validatePhone||(t=>function(t){const e=[];return Array.from(t).forEach((t=>{(Number(t)||0===Number(t))&&e.push(t)})),!(e.length<11||e.length<12&&"+"===t[1])}(t.value));t(s)||(this.showError(s,"Неверный формат"),n.push(s),e=!1)}if("url"===i&&(function(t){const e=/^https?:\/\//i.test(t)?t:`http://${t}`;try{return new URL(e),!0}catch(t){return!1}}(s.value)||(this.showError(s,"Неверный формат"),n.push(s),e=!1)),"text"===i&&"not-numbers"===s.getAttribute("data-check-type")&&/[0-9]/.test(s.value)&&(this.showError(s,"Неверный формат"),n.push(s),e=!1),"radio"===i){const t=s.getAttribute("name")||"";r[t]||(r[t]={}),r[t][Object.keys(r[t]).length]=s}}else s.hasAttribute("required")&&(this.showError(s,"Пустое значение"),n.push(s),e=!1);var l})),Object.keys(r).length>0)for(const t in r){const e=r[t];let n=!1,o=null;for(const t in e){const r=e[t];if(r.hasAttribute("required")&&(n=!0),r.checked){if(null!==o)return!1;o=r}}if(null===o&&n)return this.showErrorForm("Необходимо указать оценку"),!1}return!0===this.config.scrollToFirstErroredInput&&this.scrollToFirstErroredInput(n),e}disableSubmit(){var t;null===(t=this.$submit)||void 0===t||t.setAttribute("disabled","")}enableSubmit(){var t;null===(t=this.$submit)||void 0===t||t.removeAttribute("disabled")}clearInputs(){var t;null===(t=this.inputs)||void 0===t||t.forEach((t=>{var e;const r=t;"radio"===r.type?r.checked=!1:(r.value="",null===(e=r.parentElement)||void 0===e||e.classList.remove("filled"),r.dispatchEvent(new Event("input")))}))}showErrorForm(t){var e;const r=this.$el.querySelectorAll(".input__wrapper"),n=r[r.length-1];let o=this.$el.querySelector(".error-block-under-input__wrapper");o&&n.nextElementSibling===o?(o.classList.add("error-block-under-input--warning"),o.querySelector(".error-block-under-input__icon").innerHTML="\x3c!-- SVG content --\x3e",o.querySelector(".error-block-under-input__main-text").textContent=t):(o=document.createElement("div"),o.className="error-block-under-input__wrapper",o.innerHTML=`\n <div class="error-block-under-input error-block-under-input--warning">\n <div class="error-block-under-input__icon-wrapper">\n <span class="error-block-under-input__icon">\n \x3c!-- SVG content --\x3e\n </span>\n <span class="error-block-under-input__icon error-block-under-input__icon--animated" style="display:none;"></span>\n </div>\n <p class="error-block-under-input__text">\n <span class="error-block-under-input__main-text">${t}</span>\n <span class="error-block-under-input__secondary-text"></span>\n </p>\n </div>`,n.insertAdjacentElement("afterend",o)),this.$el.addEventListener("input",(()=>{this.hideErrorForm()}),{passive:!0,once:!0}),null===(e=o.querySelector(".error-block-under-input"))||void 0===e||e.classList.remove("error-block-under-input--success");const s=o.querySelector(".error-block-under-input__secondary-text");s&&(s.textContent="");const i=parseFloat(o.style.height)||0,l=parseFloat(window.getComputedStyle(o).paddingTop)||0;i!==o.querySelector(".error-block-under-input").scrollHeight+16&&(o.style.height=`${i}px`,o.style.opacity="0",o.style.paddingTop=`${l}px`)}hideErrorForm(){const t=this.$el.querySelectorAll(".input__wrapper"),e=t[t.length-1].nextElementSibling;e&&e.classList.contains("error-block-under-input__wrapper")}isCorrectArguments(){return"FORM"!==this.$el.tagName?(console.warn("$el не является тегом form"),!1):!!this.$submit||(console.warn("В форме нет кнопки с типом submit"),!1)}}}();
|
|
1
|
+
var FormFather=function(){"use strict";function t(t,e,r,n){return new(r||(r=Promise))((function(o,s){function i(t){try{c(n.next(t))}catch(t){s(t)}}function l(t){try{c(n.throw(t))}catch(t){s(t)}}function c(t){var e;t.done?o(t.value):(e=t.value,e instanceof r?e:new r((function(t){t(e)}))).then(i,l)}c((n=n.apply(t,e||[])).next())}))}function e(t){const e="FORM"===t.tagName?Array.from(t.elements):Array.from(t.querySelectorAll("input, select, textarea, button")),r=new FormData;return e.forEach((t=>{if(!(t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement||t instanceof HTMLButtonElement))return;if(!t.name||t.hasAttribute("data-no-serialize"))return;const{name:e,type:n}=t;if("file"===n)if("true"===t.getAttribute("multiple")){const n=t.files;if(n)for(let t=0;t<n.length;t++)r.append(`${e}[${t}]`,n[t])}else{const n=t.files;n&&n[0]&&r.append(e,n[0])}else{let o;if("tel"===n)o=t.value.split(/[\s()-]/).join("").replace(/^8/,"+7");else if("checkbox"===n||"radio"===n){if(!t.checked)return;o=t.value}else if("date"===n){const e=t.getAttribute("data-date-format");o=e?function(t,e){const r=new Date(t),n=t=>t.toString().padStart(2,"0"),o=n(r.getDate()),s=n(r.getMonth()+1),i=r.getFullYear().toString();return e.replace("dd",o).replace("mm",s).replace("yyyy",i)}(t.value,e):t.value}else o=t.value;r.append(e,o)}})),r}"function"==typeof SuppressedError&&SuppressedError;class r{constructor(t,e){this.$submit=null,this.waitResponse=!1,this.inputs=null,this.$licensesCheckbox=null,this.$el=t,this.options=e;this.config=Object.assign({},{onSubmit:()=>{},onResponse:()=>{},onResponseSuccess:()=>{},onResponseUnsuccess:()=>{},customTypeError:null,loaderColor:"#fff",showLoaderButton:!0,scrollToFirstErroredInput:!0,logging:!1},r.defaultParams,e),this.$el?(this.$submit=this.$el.querySelector('input[type="submit"], button[type="submit"]'),this.isCorrectArguments()&&this.initialization()):console.warn("Empty $el")}getOptions(){return this.options}static setDefaultParams(t){this.defaultParams=Object.assign(Object.assign({},this.defaultParams),t)}initialization(){this.inputs=this.$el.querySelectorAll(".input"),this.$licensesCheckbox=this.$el.querySelector('input[data-input-name="user-consent"]'),this.$licensesCheckbox&&(this.$licensesCheckbox.checked?this.enableSubmit():this.disableSubmit(),this.$licensesCheckbox.addEventListener("change",(()=>{this.$licensesCheckbox.checked?this.enableSubmit():this.disableSubmit()})));const r=e=>t(this,void 0,void 0,(function*(){return fetch(this.$el.getAttribute("action")||"",{method:"POST",body:e})})),n=()=>t(this,void 0,void 0,(function*(){var t,n,o,s,i,l,c,a;if(!this.waitResponse){const u=e(this.$el);if(!0===this.config.showLoaderButton&&this.showLoader(),null===(n=(t=this.config).onSubmit)||void 0===n||n.call(t,this),this.waitResponse=!0,this.config.logging)for(const t of u.keys())console.log(u.get(t));const h=yield r(u),d=yield h.json();if(this.waitResponse=!1,!0===this.config.showLoaderButton&&this.hideLoader(),null===(s=(o=this.config).onResponse)||void 0===s||s.call(o,d,this),200===h.status)if(function(t){if(Object.prototype.hasOwnProperty.call(t,"redirect-url")&&(window.location.href=t["redirect-url"]),Object.prototype.hasOwnProperty.call(t,"reload")&&!0===t.reload&&window.location.reload(),Object.prototype.hasOwnProperty.call(t,"error-toast")){const e=document.querySelector('[data-toast-name="formErrorToast"]');if(e){const r=e.querySelector(".toast__text");r&&(r.textContent=t["error-toast"],window.Toast.showToast("formErrorToast",{removeAfterClose:!1}))}}}(d),!0===d.success)null===(l=(i=this.config).onResponseSuccess)||void 0===l||l.call(i,d,this);else if(null===(a=(c=this.config).onResponseUnsuccess)||void 0===a||a.call(c,d,this),!0===d.error&&(d["error-msg"]&&this.showErrorForm(d["error-msg"]),d.errors)){const t=[];d.errors.forEach((e=>{const r=this.$el.querySelector(`input[name="${e.name}"]`);r?(t.push(r),this.showError(r,e["error-msg"])):console.warn(`Не найдено поле с именем: ${e.name}, для вывода ошибки: ${e["error-msg"]}`)})),!0===this.config.scrollToFirstErroredInput&&this.scrollToFirstErroredInput(t)}}}));this.$el.addEventListener("submit",(t=>{t.preventDefault(),this.checkInputs()&&(!this.$licensesCheckbox||this.$licensesCheckbox&&this.$licensesCheckbox.checked)&&n()}))}showError(t,e){(function(t,e){if(null==t)return null;let r=t;for(;r;){if(r.matches(e))return r;r=r.parentElement}return null})(t,"input-primary").showError(e)}showLoader(){var t;const e=`\n\t\t\t<svg height="38" viewBox="0 0 38 38" width="38" xmlns="http://www.w3.org/2000/svg">\n\t\t\t\t<defs>\n\t\t\t\t<linearGradient id="a" x1="8.042%" x2="65.682%" y1="0%" y2="23.865%">\n\t\t\t\t\t<stop offset="0%" stop-color="${this.config.loaderColor}" stop-opacity="0"/>\n\t\t\t\t\t<stop offset="63.146%" stop-color="${this.config.loaderColor}" stop-opacity=".631"/>\n\t\t\t\t\t<stop offset="100%" stop-color="${this.config.loaderColor}"/>\n\t\t\t\t</linearGradient>\n\t\t\t\t</defs>\n\t\t\t\t<g fill-rule="evenodd" fill="none">\n\t\t\t\t<g transform="translate(1 1)">\n\t\t\t\t\t<path d="M36 18c0-9.94-8.06-18-18-18" id="Oval-2" stroke-width="5" stroke="url(#a)"></path>\n\t\t\t\t\t<circle cx="36" cy="18" fill="${this.config.loaderColor}" r="1"></circle>\n\t\t\t\t</g>\n\t\t\t\t</g>\n\t\t\t</svg>\n\t\t`,r=document.createElement("span");r.innerHTML=e,r.className="button__loader",null===(t=this.$submit)||void 0===t||t.insertAdjacentElement("afterbegin",r),requestAnimationFrame((()=>{r.setAttribute("data-showed","")}))}hideLoader(){var t,e;null===(t=this.$submit)||void 0===t||t.classList.remove("button--loading");const r=null===(e=this.$submit)||void 0===e?void 0:e.querySelector(".button__loader");r&&(r.classList.remove("active"),r.removeAttribute("data-showed"),setTimeout((()=>{r.remove()}),250))}hideError(t){const e=t.parentElement;e&&e.classList.contains("input__wrapper")&&(e.getAttribute("data-type-error"),e.classList.remove("input__wrapper--error"))}scrollToFirstErroredInput(t){if(t.length>0){const e=Array.from(this.$el.querySelectorAll("input"));let r=null,n=1/0;if(t.forEach((t=>{const o=e.findIndex((e=>e===t));o<n&&(n=o,r=t)})),r){const t=r.getBoundingClientRect(),e=window.pageYOffset||document.documentElement.scrollTop,n=t.top+e-window.innerHeight/2;document.documentElement.setAttribute("data-now-scrolling",""),window.scrollTo({top:n,behavior:"smooth"}),setTimeout((()=>{document.documentElement.removeAttribute("data-now-scrolling")}),800)}}}checkInputs(){var t;let e=!0;const r={},n=[];if(null===(t=this.inputs)||void 0===t||t.forEach((t=>{var o;const s=t,i=s.getAttribute("data-check-type")||s.getAttribute("type")||"";if((null===(o=this.config.customTypeError)||void 0===o?void 0:o.name)!==i||"TEXTAREA"===s.tagName&&!this.config.customTypeError)if(s.value.length>0){if("email"===i&&(l=s.value,/^(([^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*)|(".+"))@(([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{2,})$/iu.test(l)||(this.showError(s,"Неверный формат"),n.push(s),e=!1)),"tel"===i){const t=this.config.validatePhone||(t=>function(t){const e=[];return Array.from(t).forEach((t=>{(Number(t)||0===Number(t))&&e.push(t)})),!(e.length<11||e.length<12&&"+"===t[1])}(t.value));t(s)||(this.showError(s,"Неверный формат"),n.push(s),e=!1)}if("url"===i&&(function(t){const e=/^https?:\/\//i.test(t)?t:`http://${t}`;try{return new URL(e),!0}catch(t){return!1}}(s.value)||(this.showError(s,"Неверный формат"),n.push(s),e=!1)),"text"===i&&"not-numbers"===s.getAttribute("data-check-type")&&/[0-9]/.test(s.value)&&(this.showError(s,"Неверный формат"),n.push(s),e=!1),"radio"===i){const t=s.getAttribute("name")||"";r[t]||(r[t]={}),r[t][Object.keys(r[t]).length]=s}}else s.hasAttribute("required")&&(this.showError(s,"Пустое значение"),n.push(s),e=!1);var l})),Object.keys(r).length>0)for(const t in r){const e=r[t];let n=!1,o=null;for(const t in e){const r=e[t];if(r.hasAttribute("required")&&(n=!0),r.checked){if(null!==o)return!1;o=r}}if(null===o&&n)return this.showErrorForm("Необходимо указать оценку"),!1}return!0===this.config.scrollToFirstErroredInput&&this.scrollToFirstErroredInput(n),e}disableSubmit(){var t;null===(t=this.$submit)||void 0===t||t.setAttribute("disabled","")}enableSubmit(){var t;null===(t=this.$submit)||void 0===t||t.removeAttribute("disabled")}clearInputs(){var t;null===(t=this.inputs)||void 0===t||t.forEach((t=>{var e;const r=t;"radio"===r.type?r.checked=!1:(r.value="",null===(e=r.parentElement)||void 0===e||e.classList.remove("filled"),r.dispatchEvent(new Event("input")))}))}showErrorForm(t){var e;const r=this.$el.querySelectorAll(".input__wrapper"),n=r[r.length-1];let o=this.$el.querySelector(".error-block-under-input__wrapper");o&&n.nextElementSibling===o?(o.classList.add("error-block-under-input--warning"),o.querySelector(".error-block-under-input__icon").innerHTML="\x3c!-- SVG content --\x3e",o.querySelector(".error-block-under-input__main-text").textContent=t):(o=document.createElement("div"),o.className="error-block-under-input__wrapper",o.innerHTML=`\n <div class="error-block-under-input error-block-under-input--warning">\n <div class="error-block-under-input__icon-wrapper">\n <span class="error-block-under-input__icon">\n \x3c!-- SVG content --\x3e\n </span>\n <span class="error-block-under-input__icon error-block-under-input__icon--animated" style="display:none;"></span>\n </div>\n <p class="error-block-under-input__text">\n <span class="error-block-under-input__main-text">${t}</span>\n <span class="error-block-under-input__secondary-text"></span>\n </p>\n </div>`,n.insertAdjacentElement("afterend",o)),this.$el.addEventListener("input",(()=>{this.hideErrorForm()}),{passive:!0,once:!0}),null===(e=o.querySelector(".error-block-under-input"))||void 0===e||e.classList.remove("error-block-under-input--success");const s=o.querySelector(".error-block-under-input__secondary-text");s&&(s.textContent="");const i=parseFloat(o.style.height)||0,l=parseFloat(window.getComputedStyle(o).paddingTop)||0;i!==o.querySelector(".error-block-under-input").scrollHeight+16&&(o.style.height=`${i}px`,o.style.opacity="0",o.style.paddingTop=`${l}px`)}hideErrorForm(){const t=this.$el.querySelectorAll(".input__wrapper"),e=t[t.length-1].nextElementSibling;e&&e.classList.contains("error-block-under-input__wrapper")}isCorrectArguments(){return"FORM"!==this.$el.tagName?(console.warn("$el не является тегом form"),!1):!!this.$submit||(console.warn("В форме нет кнопки с типом submit"),!1)}}return r.defaultParams={},r}();
|
|
2
2
|
//# sourceMappingURL=FormFather.min.js.map
|
package/README.md
CHANGED
|
@@ -19,6 +19,12 @@ npm install form-father
|
|
|
19
19
|
```javascript
|
|
20
20
|
import Form from 'form-father';
|
|
21
21
|
|
|
22
|
+
Form.setDefaultParams({
|
|
23
|
+
showLoaderButton: false,
|
|
24
|
+
scrollToFirstErroredInput: false,
|
|
25
|
+
logging: true,
|
|
26
|
+
});
|
|
27
|
+
|
|
22
28
|
const formElement = document.querySelector('#myForm');
|
|
23
29
|
const options = {
|
|
24
30
|
onSubmit: formInstance => {
|
|
@@ -44,6 +50,7 @@ const form = new Form(formElement, options);
|
|
|
44
50
|
- **customTypeError**: Кастомный тип ошибки.
|
|
45
51
|
- **loaderColor**: Цвет лоадера в кнопке отправки.
|
|
46
52
|
- **logging**: Нужно ли выводить данные в консоль. По умолчанию `false`.
|
|
53
|
+
- **setDefaultParams(params)**: Метод setDefaultParams используется для установки значений по умолчанию для всех экземпляров формы. Эти параметры можно переопределить при инициализации конкретной формы.
|
|
47
54
|
|
|
48
55
|
## Методы
|
|
49
56
|
|
|
@@ -61,3 +68,5 @@ const form = new Form(formElement, options);
|
|
|
61
68
|
- **blockScrollBody()**: Блокирует прокрутку страницы.
|
|
62
69
|
- **unblockScrollBody()**: Разблокирует прокрутку страницы.
|
|
63
70
|
- **parseCommonResponseProperties(responseBody)**: Обрабатывает общие свойства ответа сервера.
|
|
71
|
+
|
|
72
|
+
© 2024 Poliklot
|
package/index.d.ts
CHANGED
|
@@ -53,6 +53,7 @@ declare class Form {
|
|
|
53
53
|
private waitResponse;
|
|
54
54
|
private inputs;
|
|
55
55
|
private $licensesCheckbox;
|
|
56
|
+
private static defaultParams;
|
|
56
57
|
/**
|
|
57
58
|
* Создать форму.
|
|
58
59
|
*
|
|
@@ -60,6 +61,15 @@ declare class Form {
|
|
|
60
61
|
* @param {Object} options - Параметры формы.
|
|
61
62
|
*/
|
|
62
63
|
constructor($el: HTMLElement, options: FormOptions);
|
|
64
|
+
getOptions(): FormOptions;
|
|
65
|
+
/**
|
|
66
|
+
* Обновляет параметры по умолчанию для настроек формы.
|
|
67
|
+
* Метод объединяет переданные параметры с уже существующими параметрами по умолчанию.
|
|
68
|
+
*
|
|
69
|
+
* @param {Partial<FormOptions>} params - Объект, содержащий новые значения параметров.
|
|
70
|
+
* Можно передать только те свойства, которые необходимо обновить; остальные сохранятся без изменений.
|
|
71
|
+
*/
|
|
72
|
+
static setDefaultParams(params: Partial<FormOptions>): void;
|
|
63
73
|
private initialization;
|
|
64
74
|
/**
|
|
65
75
|
* Показывает ошибку для поля ввода.
|
package/index.js
CHANGED
|
@@ -238,7 +238,8 @@ class Form {
|
|
|
238
238
|
scrollToFirstErroredInput: true,
|
|
239
239
|
logging: false,
|
|
240
240
|
};
|
|
241
|
-
|
|
241
|
+
/* Слияние параметров: глобальные параметры → пользовательские параметры */
|
|
242
|
+
this.config = Object.assign({}, defaultConfig, Form.defaultParams, options);
|
|
242
243
|
if (this.$el) {
|
|
243
244
|
this.$submit = this.$el.querySelector('input[type="submit"], button[type="submit"]');
|
|
244
245
|
if (this.isCorrectArguments())
|
|
@@ -248,6 +249,19 @@ class Form {
|
|
|
248
249
|
console.warn('Empty $el');
|
|
249
250
|
}
|
|
250
251
|
}
|
|
252
|
+
getOptions() {
|
|
253
|
+
return this.options;
|
|
254
|
+
}
|
|
255
|
+
/**
|
|
256
|
+
* Обновляет параметры по умолчанию для настроек формы.
|
|
257
|
+
* Метод объединяет переданные параметры с уже существующими параметрами по умолчанию.
|
|
258
|
+
*
|
|
259
|
+
* @param {Partial<FormOptions>} params - Объект, содержащий новые значения параметров.
|
|
260
|
+
* Можно передать только те свойства, которые необходимо обновить; остальные сохранятся без изменений.
|
|
261
|
+
*/
|
|
262
|
+
static setDefaultParams(params) {
|
|
263
|
+
this.defaultParams = Object.assign(Object.assign({}, this.defaultParams), params);
|
|
264
|
+
}
|
|
251
265
|
initialization() {
|
|
252
266
|
this.inputs = this.$el.querySelectorAll('.input');
|
|
253
267
|
this.$licensesCheckbox = this.$el.querySelector('input[data-input-name="user-consent"]');
|
|
@@ -406,11 +420,13 @@ class Form {
|
|
|
406
420
|
}
|
|
407
421
|
});
|
|
408
422
|
if ($firstInputOnForm) {
|
|
423
|
+
const rect = $firstInputOnForm.getBoundingClientRect();
|
|
424
|
+
const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
|
|
425
|
+
const scrollTargetY = rect.top + scrollTop - (window.innerHeight / 2);
|
|
409
426
|
document.documentElement.setAttribute('data-now-scrolling', '');
|
|
410
|
-
|
|
427
|
+
window.scrollTo({
|
|
428
|
+
top: scrollTargetY,
|
|
411
429
|
behavior: 'smooth',
|
|
412
|
-
block: 'center',
|
|
413
|
-
inline: 'center',
|
|
414
430
|
});
|
|
415
431
|
setTimeout(() => {
|
|
416
432
|
document.documentElement.removeAttribute('data-now-scrolling');
|
|
@@ -610,6 +626,7 @@ class Form {
|
|
|
610
626
|
return true;
|
|
611
627
|
}
|
|
612
628
|
}
|
|
629
|
+
Form.defaultParams = {};
|
|
613
630
|
|
|
614
631
|
export { Form as default };
|
|
615
632
|
//# sourceMappingURL=index.js.map
|
package/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
package/package.json
CHANGED
package/types/index.d.ts
CHANGED
|
@@ -53,6 +53,7 @@ export default class Form {
|
|
|
53
53
|
private waitResponse;
|
|
54
54
|
private inputs;
|
|
55
55
|
private $licensesCheckbox;
|
|
56
|
+
private static defaultParams;
|
|
56
57
|
/**
|
|
57
58
|
* Создать форму.
|
|
58
59
|
*
|
|
@@ -60,6 +61,15 @@ export default class Form {
|
|
|
60
61
|
* @param {Object} options - Параметры формы.
|
|
61
62
|
*/
|
|
62
63
|
constructor($el: HTMLElement, options: FormOptions);
|
|
64
|
+
getOptions(): FormOptions;
|
|
65
|
+
/**
|
|
66
|
+
* Обновляет параметры по умолчанию для настроек формы.
|
|
67
|
+
* Метод объединяет переданные параметры с уже существующими параметрами по умолчанию.
|
|
68
|
+
*
|
|
69
|
+
* @param {Partial<FormOptions>} params - Объект, содержащий новые значения параметров.
|
|
70
|
+
* Можно передать только те свойства, которые необходимо обновить; остальные сохранятся без изменений.
|
|
71
|
+
*/
|
|
72
|
+
static setDefaultParams(params: Partial<FormOptions>): void;
|
|
63
73
|
private initialization;
|
|
64
74
|
/**
|
|
65
75
|
* Показывает ошибку для поля ввода.
|