| 1 |
/** |
| 2 |
* Keep the Free Shipping Bar in sync after block-theme mini-cart and AJAX cart updates. |
| 3 |
*/ |
| 4 |
(function () { |
| 5 |
"use strict"; |
| 6 |
|
| 7 |
const cfg = window.kingAddonsFsb || {}; |
| 8 |
let timer = 0; |
| 9 |
|
| 10 |
const miniCartHost = () => |
| 11 |
document.querySelector( |
| 12 |
".wp-block-woocommerce-filled-mini-cart-contents-block, .wc-block-mini-cart__items" |
| 13 |
); |
| 14 |
|
| 15 |
const applyHtml = (html) => { |
| 16 |
const existing = document.querySelectorAll(".king-addons-fsb"); |
| 17 |
|
| 18 |
if (!html) { |
| 19 |
existing.forEach((el) => el.remove()); |
| 20 |
return; |
| 21 |
} |
| 22 |
|
| 23 |
const tmp = document.createElement("div"); |
| 24 |
tmp.innerHTML = html; |
| 25 |
const next = tmp.firstElementChild; |
| 26 |
if (!(next instanceof HTMLElement)) { |
| 27 |
return; |
| 28 |
} |
| 29 |
|
| 30 |
if (existing.length) { |
| 31 |
existing.forEach((el, i) => { |
| 32 |
el.replaceWith(i === 0 ? next : next.cloneNode(true)); |
| 33 |
}); |
| 34 |
return; |
| 35 |
} |
| 36 |
|
| 37 |
const host = miniCartHost(); |
| 38 |
if (host) { |
| 39 |
host.insertAdjacentElement("afterbegin", next); |
| 40 |
} |
| 41 |
}; |
| 42 |
|
| 43 |
const refresh = () => { |
| 44 |
if (!cfg.ajaxUrl) { |
| 45 |
return; |
| 46 |
} |
| 47 |
|
| 48 |
const body = new URLSearchParams(); |
| 49 |
body.append("action", "king_addons_fsb_markup"); |
| 50 |
if (cfg.nonce) { |
| 51 |
body.append("nonce", cfg.nonce); |
| 52 |
} |
| 53 |
|
| 54 |
fetch(cfg.ajaxUrl, { |
| 55 |
method: "POST", |
| 56 |
headers: { "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8" }, |
| 57 |
body: body.toString(), |
| 58 |
credentials: "same-origin", |
| 59 |
}) |
| 60 |
.then((res) => res.json()) |
| 61 |
.then((res) => { |
| 62 |
if (!res || !res.success) { |
| 63 |
return; |
| 64 |
} |
| 65 |
applyHtml((res.data && res.data.html) || ""); |
| 66 |
}) |
| 67 |
.catch(() => {}); |
| 68 |
}; |
| 69 |
|
| 70 |
const schedule = () => { |
| 71 |
window.clearTimeout(timer); |
| 72 |
timer = window.setTimeout(refresh, 250); |
| 73 |
}; |
| 74 |
|
| 75 |
document.addEventListener("added_to_cart", schedule); |
| 76 |
document.addEventListener("removed_from_cart", schedule); |
| 77 |
document.body.addEventListener("wc_fragments_refreshed", schedule); |
| 78 |
document.body.addEventListener("wc-blocks_added_to_cart", schedule); |
| 79 |
document.body.addEventListener("wc-blocks_removed_from_cart", schedule); |
| 80 |
|
| 81 |
document.addEventListener("click", (event) => { |
| 82 |
const target = event.target; |
| 83 |
if (!(target instanceof Element)) { |
| 84 |
return; |
| 85 |
} |
| 86 |
if ( |
| 87 |
target.closest(".wc-block-components-quantity-selector") || |
| 88 |
target.closest(".wc-block-cart-item__remove-link") || |
| 89 |
target.closest(".wc-block-mini-cart__button") |
| 90 |
) { |
| 91 |
schedule(); |
| 92 |
} |
| 93 |
}); |
| 94 |
})(); |
| 95 |
|