// DetoxBuy storefront AJAX layer. // // The storefront forms (sign-in, register, address book, password reset, cart // quantity, coupon, review, logout) all posted and reloaded the whole page. On a // phone that meant a visible flash on every keystroke-level action and a lost // scroll position. // // This module submits those forms in the background and applies the answer: // // - {ok:true, message} → show the message, refresh the affected view // - {ok:false, error} → show the error inline, keep the form filled // - {navigate:true, redirect} → the visitor must move (sign-in, checkout) // // Progressive enhancement: without JavaScript the forms post normally and the // server still redirects with the same flash messages. (function () { "use strict"; var $ = function (s, r) { return (r || document).querySelector(s); }; var $$ = function (s, r) { return Array.prototype.slice.call((r || document).querySelectorAll(s)); }; var AJAX_HEADER = "X-Storefront-Ajax"; function csrfToken() { var m = document.querySelector('meta[name="csrf-token"]'); return m ? m.getAttribute("content") : ""; } // --- feedback ------------------------------------------------------------ // The storefront renders flash messages inside .flash-stack when the page is // reloaded; the AJAX path uses the same look so the visitor sees one consistent // component either way. function showMessage(kind, text) { if (!text) return; var host = $(".flash-stack"); if (!host) { host = document.createElement("div"); host.className = "flash-stack"; var anchor = $("main") || document.body; anchor.insertBefore(host, anchor.firstChild); } var el = document.createElement("div"); el.className = "flash flash-" + (kind === "err" ? "err" : "ok"); el.setAttribute("role", kind === "err" ? "alert" : "status"); el.textContent = text; host.appendChild(el); if (kind !== "err") { setTimeout(function () { el.style.transition = "opacity .4s"; el.style.opacity = "0"; setTimeout(function () { el.remove(); }, 450); }, 4500); } else { el.addEventListener("click", function () { el.remove(); }); } } function setBusy(form, busy) { var btn = form.querySelector('button[type="submit"], button:not([type])'); if (!btn) return; if (busy) { btn.dataset.label = btn.innerHTML; btn.disabled = true; btn.classList.add("is-busy"); btn.innerHTML = ''; } else { btn.disabled = false; btn.classList.remove("is-busy"); if (btn.dataset.label) btn.innerHTML = btn.dataset.label; } } // --- cart counter -------------------------------------------------------- // Adding to cart from a card has to update the header count immediately; a // silent save would look like nothing happened. function refreshCartCount() { fetch("/api/sepet", { headers: { "Accept": "application/json" }, credentials: "same-origin" }) .then(function (r) { return r.ok ? r.json() : null; }) .then(function (d) { if (!d || typeof d.count !== "number") return; $$("[data-cart-count]").forEach(function (el) { el.textContent = d.count; el.classList.toggle("is-empty", d.count === 0); }); }) .catch(function () {}); } // --- content refresh ----------------------------------------------------- // refreshRegion re-fetches the current page and swaps one region. The cart page // and the account area each declare a container; without one we fall back to a // full navigation, which is still correct, just slower. async function refreshRegion(selector) { if (!selector) return false; try { var res = await fetch(window.location.href, { headers: { "Accept": "text/html" }, credentials: "same-origin" }); if (!res.ok) return false; var doc = new DOMParser().parseFromString(await res.text(), "text/html"); var fresh = doc.querySelector(selector); var current = $(selector); if (!fresh || !current) return false; current.replaceWith(fresh); return true; } catch (e) { return false; } } // --- submission ---------------------------------------------------------- async function submitForm(form, submitter) { var action = form.getAttribute("action") || window.location.pathname; if (submitter && submitter.getAttribute("formaction")) { action = submitter.getAttribute("formaction"); } var fd = new FormData(form); if (submitter && submitter.name) fd.append(submitter.name, submitter.value); setBusy(form, true); var headers = { "Accept": "application/json", "X-Requested-With": "fetch", "X-CSRF-Token": csrfToken() }; headers[AJAX_HEADER] = "1"; var response; try { response = await fetch(action, { method: "POST", body: fd, credentials: "same-origin", headers: headers }); } catch (e) { setBusy(form, false); showMessage("err", "Bağlantı kurulamadı. Lütfen tekrar deneyin."); return; } setBusy(form, false); var data = null; var ct = response.headers.get("Content-Type") || ""; if (ct.indexOf("application/json") >= 0) { try { data = await response.json(); } catch (e) { data = null; } } if (!data) { if (response.status === 403) { showMessage("err", "Oturum doğrulaması başarısız. Sayfayı yenileyip tekrar deneyin."); return; } // The server rendered a page (validation re-render or an error page). var html = await response.text(); if (html) { document.open(); document.write(html); document.close(); return; } showMessage("err", "Beklenmeyen bir yanıt alındı."); return; } if (data.navigate && data.redirect) { // Sign-in, checkout and order confirmation are real navigations. if (data.message) { try { sessionStorage.setItem("db_flash", JSON.stringify({ kind: "ok", text: data.message })); } catch (e) {} } window.location.href = data.redirect; return; } if (data.error) { showMessage("err", data.error); return; } if (data.message) showMessage("ok", data.message); // The form knows which region it invalidates; the templates set data-refresh. var region = form.getAttribute("data-refresh"); if (region) { await refreshRegion(region); } // Adding to cart always refreshes the header count. if (/\/(sepet|cart)\//.test(action) || form.classList.contains("pcard-add-form") || form.classList.contains("add-form") || form.classList.contains("hcard-form") || form.classList.contains("cd-cross-form") || form.classList.contains("qv-form") || form.classList.contains("msc-form")) { refreshCartCount(); } if (form.hasAttribute("data-reset-on-success")) form.reset(); } // --- wiring -------------------------------------------------------------- document.addEventListener("submit", function (e) { var form = e.target; if (!(form instanceof HTMLFormElement)) return; if (form.dataset.ajax === "off") return; if ((form.getAttribute("method") || "get").toLowerCase() !== "post") return; // Logout is a POST that must really navigate. if (form.hasAttribute("data-navigate")) return; // Forms that already speak JSON (contact, question, stock notify) have their // own handlers in store.js; leave them alone. if (form.hasAttribute("data-contact-form") || form.hasAttribute("data-qa-form") || form.hasAttribute("data-stock-form") || form.hasAttribute("data-newsletter")) return; if (form.hasAttribute("data-confirm")) { if (!window.confirm(form.getAttribute("data-confirm"))) { e.preventDefault(); return; } } e.preventDefault(); submitForm(form, e.submitter || null); }); // A message stored by the previous navigation (see data.navigate above) is // shown once, so a sign-in confirmation survives the redirect without a query // parameter. try { var pending = sessionStorage.getItem("db_flash"); if (pending) { sessionStorage.removeItem("db_flash"); var parsed = JSON.parse(pending); showMessage(parsed.kind || "ok", parsed.text); } } catch (e) {} })();