File: //var/www/innodrive/src/js/modules/forms.js
/* eslint-disable */
// import Spinner from './spinner';
// import ModalMessage from './modal-message';
import { $$, pll } from '@utils';
import axios from 'axios';
import { clearCart } from './catalog';
import { reachGoal} from './yandexCounter';
import { clearAllBodyScrollLocks } from 'body-scroll-lock';
const HAS_ERROR_CLASS = 'has-error';
class Form {
constructor (form) {
this.form = form;
this.container = form.parentElement;
this.responseBlock = this.container.querySelector('div.modal__response');
this.responseText = this.container.querySelector('div.modal__response p');
this.fileFieldSet = form.querySelector('.contacts-form__fieldset--file');
this.spinner = document.querySelector('.spinner').spinner;
this.closeButton = this.responseBlock.querySelector('.button-link');
this.order = this.container.querySelector('.modal-order');
this.selfEmail = this.container.querySelector('#cartSelfEmail');
this.send = this.send.bind(this);
this.validate = this.validate.bind(this);
this.onFormChange = this.onFormChange.bind(this);
this.onSubmit = this.onSubmit.bind(this);
}
showSuccessResponse (msg, shouldCartBeCleared) {
if (this.selfEmail && this.selfEmail.value === '0') {
this.form.reset();
}
if (this.closeButton) {
this.form.classList.add('js-hidden');
}
if (this.order) {
this.order.classList.add('js-hidden');
}
if (msg) {
this.responseText.textContent = msg;
} else {
this.responseText.textContent = 'Спасибо, Ваша заявка отправлена.';
}
if (shouldCartBeCleared) {
clearCart();
}
this.responseBlock.classList.remove('js-hidden');
}
showErrorResponse (msg) {
if (msg) {
this.responseText.textContent = msg;
} else {
this.responseText.textContent = 'Server error, please try again later';
}
this.form.classList.add('contains-error');
this.responseBlock.classList.remove('js-hidden');
}
validate (onInvalid, onValid) {
let errors = 0;
[...this.form.querySelectorAll('.required:not(:disabled)')].forEach((item) => {
let data = null;
if (item.getAttribute('type') === 'checkbox') {
data = item.checked ? item.value : '';
} else {
data = item.value;
}
let error = false;
if (data === '') {
error = true;
} else {
if (item.classList.contains('f-phone')) {
if (!data.match(/^[+\s\(\)-\d]{5,18}$/)) error = true;
} else if (item.classList.contains('f-mail')) {
if (!data.match(/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/)) error = true;
} else if (item.classList.contains('f-date')) {
if (!data.match(/^[\d]{2}[\/.]{1}[\d]{2}[\/.]{1}[\d]{4}$/)) error = true;
} else if (item.classList.contains('f-time')) {
if (!data.match(/^[\d]{1,2}[:.]{1}[\d]{1,2}$/)) error = true;
}
}
if (error) {
errors++;
if (item.getAttribute('type') === 'checkbox') {
item.parentElement.classList.add(HAS_ERROR_CLASS);
} else {
item.classList.add(HAS_ERROR_CLASS);
}
} else {
if (item.getAttribute('type') === 'checkbox') {
item.parentElement.classList.remove(HAS_ERROR_CLASS);
} else {
item.classList.remove(HAS_ERROR_CLASS);
}
}
});
[...this.form.querySelectorAll('[type="file"]')].forEach((item) => {
let error = false;
console.log(item.files);
if (item.files.length > 0) {
console.log('?');
if(item.getAttribute('data-max-file-size')) {
const allowedMaxFileSize = item.getAttribute('data-max-file-size');
console.log(item.files[0].size, Number(allowedMaxFileSize));
if(item.files[0].size > Number(allowedMaxFileSize) ) {
error = true;
}
}
}
if (error) {
errors++;
item.parentNode.classList.add(HAS_ERROR_CLASS);
}
else {
item.parentNode.classList.remove(HAS_ERROR_CLASS);
}
});
const submitButton = this.form.querySelector('[type="submit"]');
if (errors) {
onInvalid && onInvalid();
} else {
onValid && onValid();
}
return errors === 0;
}
send () {
this.spinner.run();
this.form.classList.add('js-progress');
const formData = new FormData(this.form);
const url = new URL(window.location);
const utmSource = localStorage.getItem('utm_source');
const utmMedium = localStorage.getItem('utm_medium');
const utmTerm = localStorage.getItem('utm_term');
const utmContent = localStorage.getItem('utm_content');
const referer = url.host + url.pathname
if(utmSource) {
formData.append('utm_source', utmSource)
}
if(utmMedium) {
formData.append('utm_medium', utmMedium)
}
if(utmTerm) {
formData.append('utm_term', utmTerm)
}
if(utmContent) {
formData.append('utm_content', utmContent)
}
formData.append('referer', referer);
this.disableForm();
this.form.classList.remove('contains-error');
this.responseBlock.classList.add('js-hidden');
axios
.post(
'/wp-json/message/send', formData, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
)
.then((res) => {
this.form.classList.remove('js-progress');
this.enableForm();
this.spinner.stop();
if (res.data.status === 'ok') {
if (formData.get('selfEmail') == '1') {
reachGoal('SendSaveOrder');
} else {
if (formData.get('withcart') == '1') {
reachGoal('SendBuyOrder');
} else {
if (window.location.pathname == '/en/contacts/' || window.location.pathname == '/contacts/') {
reachGoal('MailContact');
} else {
reachGoal('CallBackPhone');
}
}
}
this.showSuccessResponse(pll(res.data.response), res.data && res.data.cart_clear);
if (this.form) {
this.form.reset();
}
} else {
this.showErrorResponse(pll(res.data.response));
}
})
.catch((err) => {
this.spinner.stop();
this.enableForm();
this.form.classList.add('contains-error');
this.responseText.textContent = pll('404. Bad connection');
this.responseBlock.classList.remove('js-hidden');
throw err;
})
}
enableForm () {
[...this.form.elements].forEach((element) => {
element.removeAttribute('disabled');
});
}
disableForm () {
[...this.form.elements].forEach((element) => {
element.setAttribute('disabled', true);
});
}
onFormChange () {
this.form.classList.remove('contains-error');
this.responseBlock.classList.add('js-hidden');
}
onSubmit (e) {
e.preventDefault();
e.stopPropagation();
const onInvalid = () => {
this.form.classList.add('contains-error');
this.form.querySelector('.has-error').focus();
this.responseText.textContent = pll('Please, fill highlighted fields');
this.responseBlock.classList.remove('js-hidden');
};
const isValid = this.validate(onInvalid);
if (isValid) {
this.send();
} else {
onInvalid();
}
return false;
}
bind () {
this.form.addEventListener('change', this.onFormChange);
this.form.addEventListener('submit', this.onSubmit);
if (this.closeButton) {
this.closeButton.addEventListener('click', () => {
if (this.closeButton.closest('.modal')) {
this.closeButton.closest('.modal').classList.remove('js-shown');
}
this.responseBlock.classList.add('js-hidden');
clearAllBodyScrollLocks();
setTimeout(() => {
this.form.classList.remove('js-hidden');
if (this.order) {
this.order.classList.remove('js-hidden');
}
}, 400);
});
}
if (this.fileFieldSet) {
const fileField = this.fileFieldSet.querySelector('input[type="file"]');
const fileName = this.fileFieldSet.querySelector('span span');
const addButton = this.fileFieldSet.querySelector('label');
const removeFileToggle = this.fileFieldSet.querySelector('span svg');
const InitialText = {
FILENAME: fileName.textContent
};
const handlerFileChange = (evt) => {
fileName.textContent = evt.target.files[0].name;
addButton.classList.add('js-loaded');
fileName.parentElement.classList.add('js-loaded');
};
const handlerFileRemove = () => {
fileName.textContent = InitialText.FILENAME;
fileField.value = '';
addButton.classList.remove('js-loaded');
fileName.parentElement.classList.remove('js-loaded');
};
fileField.addEventListener('change', handlerFileChange);
removeFileToggle.addEventListener('click', handlerFileRemove);
}
}
}
export default () => {
[...$$('.js-mailer')].forEach((formElement) => {
const form = new Form(formElement);
form.bind();
});
};