Loading...
`;
return loader;
}
function addAjaxLoader(button, loader) {
button.setAttribute('data-label', button.getAttribute('aria-label'));
button.removeAttribute('aria-label');
button.prepend(loader);
button.classList.add('relative', '[&>:not(.loader)]:invisible');
button.disabled = true;
}
function removeAjaxLoader(button, loader) {
button.setAttribute('aria-label', button.getAttribute('data-label'));
button.removeAttribute('data-label');
loader.remove();
button.classList.remove('[&>:not(.loader)]:invisible');
button.disabled = false;
}
async function addAjaxCartForm(form, extraDelay = 500) {
if (!form) return;
event.preventDefault();
if (!form.reportValidity()) {
return form.submit();
}
const formData = new FormData(form);
const button = form.querySelector('button:not([type=button], [type=reset])')
? form.querySelector('button:not([type=button], [type=reset])')
: document.getElementById('product-addtocart-button');
const loader = createAjaxLoader(button);
const formUenc = hyva.getUenc();
const postUrl = event.target.action.replace('%25uenc%25', formUenc);
let bodyUrl = new URLSearchParams(formData);
bodyUrl.append("uenc", formUenc);
addAjaxLoader(button, loader);
try {
const response = await fetch(postUrl, {
method: 'POST',
body: bodyUrl.toString(),
mode: "cors",
credentials: "include",
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
'X-Requested-With': 'XMLHttpRequest'
}
});
if (!response.ok) {
return form.submit();
}
if (response.redirected) {
return window.location.href = response.url;
}
const responseData = await response.json();
if (responseData.backUrl) {
return window.location.href = data.backUrl;
}
window.dispatchEvent(new CustomEvent("reload-customer-section-data"));
const productFormData = {
productId: formData.get("product"),
options: {}
}
for (const formEntry of formData.entries()) {
if (!formEntry[0].startsWith('super_attribute')) continue;
const formEntryOption = { [formEntry[0].match(/\[(\d+)\]/)[1]]: formEntry[1] };
productFormData.options = { ...productFormData.options, ...formEntryOption };
}
window.dispatchEvent(new CustomEvent('open-ajax-cart', { detail: productFormData }));
} catch (err) {
console.warn(err);
window.dispatchEvent(new CustomEvent('product-addtocart-error'));
if (typeof window.dispatchMessages === "undefined") return;
window.dispatchMessages([{
text:'Kilo\u0020problema\u0020\u012Ftraukiant\u0020j\u016Bs\u0173\u0020prek\u0119\u0020\u012F\u0020krep\u0161el\u012F.',
type: 'error'
}], 5000);
} finally {
setTimeout(() => removeAjaxLoader(button, loader), extraDelay);
}
}
function removeAjaxCartForm(form) {
removeEventListener('submit', form);
}
document.addEventListener('submit', function(event) {
if (!event.target.matches('#product_addtocart_form, .product_addtocart_form')) return;
addAjaxCartForm(event.target, 500);
});