@automattic/newspack-blocks 4.16.0-alpha.1 → 4.16.0-alpha.2
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/CHANGELOG.md +2 -14
- package/dist/modal.asset.php +1 -1
- package/dist/modal.js +1 -1
- package/dist/modalCheckout.asset.php +1 -1
- package/dist/modalCheckout.js +1 -1
- package/includes/class-modal-checkout.php +4 -4
- package/includes/modal-checkout/class-checkout-data.php +62 -19
- package/newspack-blocks.php +2 -2
- package/package.json +1 -1
- package/src/blocks/checkout-button/view.php +0 -5
- package/src/modal-checkout/analytics/ga4/opened.js +4 -0
- package/src/modal-checkout/analytics/ga4/utils/index.js +12 -0
- package/vendor/composer/installed.php +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,21 +1,9 @@
|
|
|
1
|
-
# [4.16.0-alpha.
|
|
1
|
+
# [4.16.0-alpha.2](https://github.com/Automattic/newspack-blocks/compare/v4.16.0-alpha.1...v4.16.0-alpha.2) (2025-09-29)
|
|
2
2
|
|
|
3
3
|
|
|
4
4
|
### Bug Fixes
|
|
5
5
|
|
|
6
|
-
*
|
|
7
|
-
* clarify NRH dependency for Campaign ID sidebar attribute ([#2214](https://github.com/Automattic/newspack-blocks/issues/2214)) ([a25087c](https://github.com/Automattic/newspack-blocks/commit/a25087c7c85b32d06caeb80589627f2312046347))
|
|
8
|
-
* input hardening ([12a87f1](https://github.com/Automattic/newspack-blocks/commit/12a87f1b03c6c2f762aa9a65e8d14b0ae437953b))
|
|
9
|
-
* update download URL for db.php ([#2208](https://github.com/Automattic/newspack-blocks/issues/2208)) ([d334f82](https://github.com/Automattic/newspack-blocks/commit/d334f8275ade2c1a8b5d53d9ca44bb44db5d28e8))
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
### Features
|
|
13
|
-
|
|
14
|
-
* better error messages for limited products ([#2202](https://github.com/Automattic/newspack-blocks/issues/2202)) ([5572d62](https://github.com/Automattic/newspack-blocks/commit/5572d623d5cdfc04be9dc4f317d512797d248dfd))
|
|
15
|
-
* **checkout-button:** grouped product support ([#2201](https://github.com/Automattic/newspack-blocks/issues/2201)) ([f053be1](https://github.com/Automattic/newspack-blocks/commit/f053be1d730a99289f6f8b981e3604095033775c))
|
|
16
|
-
* **modal-checkout:** switch subscription support ([#2204](https://github.com/Automattic/newspack-blocks/issues/2204)) ([6906e23](https://github.com/Automattic/newspack-blocks/commit/6906e234dfa23e3ce0dcfd92cb337f63d1b239e1))
|
|
17
|
-
* replace buttongroup with togglegroupcontrol ([#2197](https://github.com/Automattic/newspack-blocks/issues/2197)) ([26920db](https://github.com/Automattic/newspack-blocks/commit/26920db7295d41eb62ce0835e1250576aab2e919))
|
|
18
|
-
* support for iframe auto-resizing ([541af11](https://github.com/Automattic/newspack-blocks/commit/541af116a128dc4fe43281fd717308349f5dfdf8))
|
|
6
|
+
* ga4 events for tiered modal ([#2218](https://github.com/Automattic/newspack-blocks/issues/2218)) ([74cf571](https://github.com/Automattic/newspack-blocks/commit/74cf571dbeb5e963f817f9f3cb02ecd117f9ab50))
|
|
19
7
|
|
|
20
8
|
## [4.15.3](https://github.com/Automattic/newspack-blocks/compare/v4.15.2...v4.15.3) (2025-09-25)
|
|
21
9
|
|
package/dist/modal.asset.php
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
<?php return array('dependencies' => array(), 'version' => '
|
|
1
|
+
<?php return array('dependencies' => array(), 'version' => '6a7e9b7a6a6607f5833e');
|
package/dist/modal.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
(()=>{"use strict";function e(e,t=!1){const n=e.querySelectorAll('button, [href], input:not([type="hidden"]), select, textarea, [tabindex]:not([tabindex="-1"])');if(0===n.length)return!1;const o=n?.[0];let c;o.focus(),t?(document.addEventListener("keydown",(function(e){if(("Tab"===e.key||9===e.keyCode)&&e.shiftKey&&document.activeElement===o){const n=t.contentWindow.document,o=n.getElementById("customer_details"),a=n.getElementById("after_customer_details"),r=n.getElementById("checkout-after-success");null!==r?c=r:null!==o.offsetParent?c=n.getElementById("checkout_continue"):null!==a.offsetParent&&(c=n.getElementById("checkout_back")),c.focus(),e.preventDefault()}})),document.getElementById("newspack-a11y-last-element").addEventListener("focus",(()=>{o.focus()}))):(c=n[n.length-1],document.addEventListener("keydown",(function(e){("Tab"===e.key||9===e.keyCode)&&(e.shiftKey?document.activeElement===o&&(c.focus(),e.preventDefault()):document.activeElement===c&&(o.focus(),e.preventDefault()))})))}const t=(e,t={})=>({...t,action:e}),n=["action","action_type","amount","currency","product_id","product_type","variation_id","price_summary","newspack_popup_id","gate_post_id","recurrence","referrer"],o=(e,t="np_modal_checkout_interaction")=>{if("function"==typeof window.gtag&&e){const o={};for(const t of n)e[t]&&(o[t]=e[t].toString());window.gtag("event",t,o)}},c=e=>{if("function"!=typeof window.gtag)return;let n="opened";const{amount:c="",is_variable:a="",price:r="",variation_id:s=""}=e,i={...e};(c||r)&&(i.amount=c||r),a&&!s&&(n="opened_variations");const l=t(n,i);o(l)};function a(e,t=null){const n=document.createElement("input");return n.type="hidden",n.name=e,t&&(n.value=t),n}function r(e){e.requestSubmit(e.querySelector('button[type="submit"]'))}function s(e){const t="string"==typeof e?document.getElementById(e):e;if(!t)return console.warn("No container found for checkout data"),{};let n={};if("FORM"===t.tagName){const e=new FormData(t);n=Object.fromEntries(e)}const o=t.dataset.checkout;if(!o)return console.warn("No checkout data found"),n;try{n={...n,...JSON.parse(o)}}catch(e){console.warn("Error parsing checkout data")}const c=new URL(t.ownerDocument.defaultView.location.href);return c.searchParams.get("action_type")&&(n.action_type=c.searchParams.get("action_type")),n.memberships_content_gate&&(n.gate_post_id=n.memberships_content_gate,delete n.memberships_content_gate),n}const i=e=>{if("function"!=typeof window.gtag)return;e=e||s("newspack_modal_checkout");const n=t("dismissed",e);o(n)},l=newspackBlocksModal.newspack_class_prefix,d="newspack_modal_checkout_iframe",u="newspack_modal_checkout_container",m=`${l}__modal`,p="newspack-blocks__modal-variation";let _=!1,h=newspackBlocksModal.labels.checkout_modal_title;const w=e=>{e.overlayId&&window.newspackReaderActivation?.overlays&&window.newspackReaderActivation?.overlays.remove(e.overlayId),e.setAttribute("data-state","closed"),document.body.style.overflow="auto"};window.onpageshow=e=>{e.persisted&&(document.querySelectorAll(".modal-processing").forEach((e=>e.classList.remove("modal-processing"))),document.querySelectorAll(".non-modal-checkout-loading").forEach((e=>e.classList.remove("non-modal-checkout-loading"))),document.querySelectorAll(`.${m}-container`).forEach((e=>w(e))))};const k=new CustomEvent("checkout-closed");var y;window.newspackRAS=window.newspackRAS||[],y=()=>{const t=document.querySelector("#newspack_modal_checkout");if(!t)return;const n=t.querySelector(`.${m}__content`),o=a("modal_checkout","1"),y=n.querySelector(`.${l}__spinner`);let f=document.querySelector(".newspack-reader__account-link")?.[0];const v="600px",g=document.createElement("iframe");g.name=d,g.style.height=v,g.style.visibility="hidden";const b=e=>{L.observe(e),"none"!==y.style.display&&(y.style.display="none"),"visible"!==g.style.visibility&&(g.style.visibility="visible"),g._ready=!0};!function(e,t,n){e._ready=!1,e._readyTimer&&clearTimeout(e._readyTimer);let o=!1,c="";function a(){o||(o=!0,clearTimeout(e._readyTimer),t.call(this))}function r(){"complete"===this.readyState&&a.call(this)}function s(){e._ready=!1,n&&n(),e._readyTimer&&clearTimeout(e._readyTimer);const t=e.contentDocument||e.contentWindow?.document;t&&(t.removeEventListener("DOMContentLoaded",a),t.removeEventListener("readystatechange",r))}function i(){if(e._ready)return void s();const t=e.contentDocument||e.contentWindow?.document;t&&0!==t.URL.indexOf("about:")?"complete"===t?.readyState?a.call(t):(t.addEventListener("DOMContentLoaded",a),t.addEventListener("readystatechange",r)):e._readyTimer=setTimeout(i,10)}e._observer||(e._observer=new MutationObserver((e=>{e.forEach((e=>{"attributes"===e.type&&"src"===e.attributeName&&(o=!1,s(),i())}))})),e._observer.observe(e,{attributes:!0})),e._locationObserver||(e._locationObserver=setInterval((function(){const t=e.contentDocument||e.contentWindow?.document;t&&t.URL!==c&&(c=t.URL,o=!1,s(),i())}),50)),i()}(g,(function(){const n=g.contentWindow?.location;if(window.newspackReaderActivation&&n?.href?.includes("order-received")){const e=window.newspackReaderActivation,t=new Proxy(new URLSearchParams(n.search),{get:(e,t)=>e.get(t)});t.email&&(e.setReaderEmail(t.email),e.setAuthenticated(!0))}const o=g?.contentDocument?.querySelector(`#${u}`);if(!o)return;const c=o.querySelector("#modal-checkout-product-details"),a=s(c);!function(e,t){e.checkoutReady?t():e.addEventListener("checkout-ready",t)}(o,(()=>{const e=c?.querySelector("strong");e&&(e.textContent=a.price_summary),C(),B(h),g.contentWindow?.newspackBlocksModalCheckout?.checkout_nonce&&(t.checkout_nonce=g.contentWindow.newspackBlocksModalCheckout.checkout_nonce),b(o)})),function(e,t){e.checkoutComplete?t():e.addEventListener("checkout-complete",t)}(o,(()=>{window.newspackRAS.push(["checkout_completed",a]),window?.newspackReaderActivation?.refreshNewslettersSignupModal&&window?.newspackReaderActivation?.getReader()?.email&&window.newspackReaderActivation.refreshNewslettersSignupModal(window.newspackReaderActivation.getReader().email),C("small"),B(newspackBlocksModal.labels.thankyou_modal_title),b(o),e(t.querySelector(`.${m}`))}))}),(()=>{y.style.display="flex"}));const S=e=>new Promise(((t,n)=>{const o=new URLSearchParams(e);o.append("action","modal_checkout_request"),fetch(newspackBlocksModal.ajax_url+"?"+o.toString()).then((e=>{e.ok||n(e),e.json().then((e=>{t(e.url)})).catch(n)})).catch(n)})),E=()=>"undefined"!=typeof newspack_ras_config&&!newspack_ras_config?.is_logged_in&&!window?.newspackReaderActivation?.getReader?.()?.authenticated&&newspackBlocksModal?.is_registration_required&&window?.newspackReaderActivation?.openAuthModal,A=t=>{const n=!newspackBlocksModal.has_unsupported_payment_gateway;n||t.preventDefault();const o=t.target;o.classList.add("modal-processing");const u=s(o);if(u.newspack_donate){const e=u.donation_frequency,t=[...o.querySelectorAll(`.donation-tier__${e}, .donation-frequency__${e}`)],n=u.donation_tier_index;let c,a;n?(c=t[n],a=u[`donation_value_${e}`]):(c=t[0],u[`donation_value_${e}_untiered`]?a=u[`donation_value_${e}_untiered`]:(a=u[`donation_value_${e}`],"other"===a&&(a=u[`donation_value_${e}_other`])));const r=s(c);for(const e in r)u[e]=r[e];u.amount=a,u.price_summary=u.summary_template.replace("{{PRICE}}",function(e,t="USD"){return parseFloat(e).toLocaleString(document.documentElement.lang,{style:"currency",currency:t,currencyDisplay:"narrowSymbol"})}(u.amount,u.currency))}u&&Object.keys(u).forEach((e=>{0===o.querySelectorAll('input[name="'+e+'"]').length&&o.prepend(a(e,u[e]))})),u.variation_id||(f=t.submitter);const m=document.querySelectorAll(`.${p}`);if(m.forEach((e=>{(E()||n)&&w(e)})),u.is_grouped||u.is_variable&&!u.variation_id){const n=[...m].find((e=>e.dataset.productId===u.product_id));if(n)return n.querySelectorAll(`form[target="${d}"]`).forEach((e=>{["after_success_behavior","after_success_url","after_success_button_label"].forEach((t=>{0===e.querySelectorAll('input[name="'+t+'"]').length&&e.prepend(a(t,u[t]))}));const t=e.dataset.checkout;if(t){const n=JSON.parse(t);Object.keys(n).forEach((t=>{0===e.querySelectorAll('input[name="'+t+'"]').length&&e.prepend(a(t,n[t]))}))}})),t.preventDefault(),o.classList.remove("modal-processing"),M(n),e(n,!1),_||c(u),void document.getElementById("newspack_modal_checkout").setAttribute("data-checkout",JSON.stringify(u))}if(n||E())if(o.classList.remove("modal-processing"),_||c(u),_=!0,E()){t.preventDefault();const e=u.price_summary,o=e?`<div class="order-details-summary ${l}__box ${l}__box--text-center"><p><strong>${e}</strong></p></div>`:"",c=S(u);c.then((e=>{window.newspackReaderActivation?.setPendingCheckout?.(e)})),window.newspackReaderActivation.openAuthModal({title:newspackBlocksModal.labels.auth_modal_title,onSuccess:(e,t)=>{c.then((e=>{t?.registered&&n&&(e+=`&${newspackBlocksModal.checkout_registration_flag}=1`),n?r(q(e)):S(u).then(window.location.href=e)})).catch((e=>{console.warn("Unable to generate cart:",e),R()}))},onError:()=>{R()},onDismiss:()=>{i(u),_=!1,document.getElementById("newspack_modal_checkout").removeAttribute("data-checkout")},skipSuccess:!0,skipNewslettersSignup:!0,labels:{signin:{title:newspackBlocksModal.labels.signin_modal_title},register:{title:newspackBlocksModal.labels.register_modal_title}},content:o,trigger:t.submitter,closeOnSuccess:n})}else $(),document.getElementById("newspack_modal_checkout").setAttribute("data-checkout",JSON.stringify(u));else S(u).then((e=>{window.location.href=e})),(!u.is_variable||u.variation_id)&&o.querySelectorAll("button[type=submit]:focus").forEach((e=>{e.classList.add("non-modal-checkout-loading");const t=e.innerHTML;e.innerHTML="<span>"+t+"</span>"}))},q=e=>{const t=document.createElement("form");t.method="POST",t.action=e,t.target=d,t.style.display="none";const n=document.createElement("button");return n.setAttribute("type","submit"),t.appendChild(n),document.body.appendChild(t),t.addEventListener("submit",A),t},L=new ResizeObserver((e=>{if(!e||!e.length)return;if(!g.contentDocument)return;const o=e[0].contentRect;if(o){const e=.01*Math.max(document.documentElement.clientHeight,window.innerHeight||0)*90-(t.querySelector(`.${m}__header`)?.offsetHeight||0),c=o.top+o.bottom,a=Math.min(c,e);if(0===a)return void(g.style.visibility="hidden");n.style.height=a+"px",g.style.height=a+"px"}})),R=()=>{const e=g?.contentDocument?.querySelector(`#${u}`),o=e?.querySelector('input[name="after_success_url"]'),c=e?.querySelector('input[name="after_success_behavior"]'),a=document?.querySelector(".newspack-newsletters-signup-modal");e?.checkoutComplete||(async()=>{const e=new FormData;newspackBlocksModal.has_unsupported_payment_gateway||e.append("modal_checkout","1"),e.append("action","abandon_modal_checkout"),e.append("_wpnonce",t.checkout_nonce),t.checkout_nonce=null;try{await fetch(newspackBlocksModal.ajax_url,{method:"POST",body:e})}catch(e){console.warn("Unable to empty cart:",e)}})();const r=!(g.contentDocument&&o&&c&&e?.checkoutComplete);if((r||a)&&(y.style.display="flex",g&&n.contains(g)&&(g._ready=!1,g.src="about:blank",g.style.height=v,g.style.visibility="hidden",n.style.height=v,n.removeChild(g)),L&&L.disconnect(),document.querySelectorAll(`.${m}-container`).forEach((e=>w(e))),f&&f.focus(),document.dispatchEvent(k)),e?.checkoutComplete){const e=()=>{if(o&&c){const e=o.getAttribute("value"),t=c.getAttribute("value");"custom"===t?window.location.href=e:"referrer"===t&&window.history.back()}window?.newspackReaderActivation?.setPendingCheckout?.(),_=!1};window?.newspackReaderActivation?.openNewslettersSignupModal?window.newspackReaderActivation.openNewslettersSignupModal({onSuccess:e,onError:e,closeOnSuccess:r}):e(),r&&(h=newspackBlocksModal.labels.checkout_modal_title,C(),B(h))}else window?.newspackReaderActivation?.setPendingCheckout?.(),i(),_=!1,document.getElementById("newspack_modal_checkout").removeAttribute("data-checkout");document.removeEventListener("keydown",D)},$=o=>{o&&(g.src=o),y.style.display="flex",M(t),n.appendChild(g),t.addEventListener("click",(e=>{e.target===t&&R()})),e(t,g),document.addEventListener("keydown",D)},M=e=>{window.newspackReaderActivation?.overlays&&(e.overlayId=window.newspackReaderActivation?.overlays.add()),e.setAttribute("data-state","open"),document.body.style.overflow="hidden"},B=e=>{const n=t.querySelector(`.${m}__header h2`);n&&(n.innerText=e)},C=(e="default")=>{const n=t.querySelector(`.${m}`);n&&("small"===e?n.classList.add(`${m}--small`):n.classList.remove(`${m}--small`))};t.querySelectorAll(`.${m}__close`).forEach((e=>{e.addEventListener("click",(e=>{e.preventDefault(),R()}))})),document.querySelectorAll(".newspack-blocks__modal-variation").forEach((e=>{e.addEventListener("click",(t=>{t.target===e&&R()})),e.querySelectorAll(`.${m}__close`).forEach((e=>{e.addEventListener("click",(e=>{e.preventDefault(),R()}))}))}));const D=e=>{"Escape"===e.key&&R()};document.querySelectorAll(".wpbnbd.wpbnbd--platform-wc, .wp-block-newspack-blocks-checkout-button, .newspack-blocks__modal-variation").forEach((e=>{e.querySelectorAll("form").forEach((e=>{newspackBlocksModal.has_unsupported_payment_gateway||e.prepend(o.cloneNode()),e.target=d,e.addEventListener("submit",A)}))})),(()=>{const e=new URLSearchParams(window.location.search);if(!e.has("checkout"))return;const t=e.get("type");if("donate"===t){const t=e.get("layout"),n=e.get("frequency"),o=e.get("amount"),c=e.get("other");t&&n&&o&&((e,t,n,o=null)=>{let c;document.querySelectorAll(".wpbnbd.wpbnbd--platform-wc form").forEach((a=>{const r=a.querySelector(`input[name="donation_frequency"][value="${t}"]`);if(r)if("tiered"===e){const e=document.querySelector(`button[data-frequency-slug="${t}"]`);if(!e)return;e.click();const o=a.querySelector(`button[type="submit"][name="donation_value_${t}"][value="${n}"]`);if(!o)return;o.click()}else{const s="untiered"===e?a.querySelector(`input[name="donation_value_${t}_untiered"]`):a.querySelector(`input[name="donation_value_${t}"][value="${n}"]`);if(r&&s){if(r.checked=!0,"untiered"===e)s.value=n;else if("other"===n){s.click();const e=a.querySelector(`input[name="donation_value_${t}_other"]`);e&&o&&(e.value=o)}else s.checked=!0;c=a}}})),c&&r(c)})(t,n,o,c)}else if("checkout_button"===t){const t=e.get("product_id"),n=e.get("variation_id");t&&((e,t=null)=>{let n;if(t&&t!==e){const o=[...document.querySelectorAll(`.${p}`)].find((t=>t.dataset.productId===e));o&&o.querySelectorAll(`form[target="${d}"]`).forEach((e=>{const o=JSON.parse(e.dataset.checkout);o?.variation_id===Number(t)&&(n=e)}))}else document.querySelectorAll(".wp-block-newspack-blocks-checkout-button").forEach((t=>{const o=t.querySelector("form");if(!o)return;const c=JSON.parse(o.dataset.checkout);c?.product_id===e&&(n=o)}));n&&r(n)})(t,n)}else{const e=window.newspackReaderActivation?.getPendingCheckout?.();e&&r(q(e))}window.history.replaceState(null,null,window.location.pathname)})(),window.newspackOpenModalCheckout=({url:e=null,title:t=null,actionType:n=null,afterSuccess:o={},onCheckoutComplete:c=null,onClose:a=null})=>{if(h=t||newspackBlocksModal.labels.checkout_modal_title,B(h),(e=new URL(e||newspackBlocksModal.checkout_url)).searchParams.has("my_account_checkout")&&e.searchParams.delete("my_account_checkout"),e.searchParams.has("modal_checkout")||e.searchParams.set("modal_checkout","1"),n&&e.searchParams.set("action_type",n),o?.url&&e.searchParams.set("after_success_url",o.url),(o?.behavior||o?.url)&&e.searchParams.set("after_success_behavior",o.behavior||"custom"),o?.buttonLabel&&e.searchParams.set("after_success_button_label",o.buttonLabel),c){const e=({detail:{action:e,data:t}})=>{"checkout_completed"===e&&c(t)};window.newspackRAS.push((t=>{t.on("activity",e);const n=()=>{t.off("activity",e),document.removeEventListener("checkout-closed",n)};document.addEventListener("checkout-closed",n)}))}if(a){const e=()=>{a(),document.removeEventListener("checkout-closed",e)};document.addEventListener("checkout-closed",e)}$(e.toString())},window.newspackCloseModalCheckout=R},"undefined"!=typeof document&&("complete"!==document.readyState&&"interactive"!==document.readyState?document.addEventListener("DOMContentLoaded",y):y())})();
|
|
1
|
+
(()=>{"use strict";function e(e,t=!1){const n=e.querySelectorAll('button, [href], input:not([type="hidden"]), select, textarea, [tabindex]:not([tabindex="-1"])');if(0===n.length)return!1;const o=n?.[0];let c;o.focus(),t?(document.addEventListener("keydown",(function(e){if(("Tab"===e.key||9===e.keyCode)&&e.shiftKey&&document.activeElement===o){const n=t.contentWindow.document,o=n.getElementById("customer_details"),a=n.getElementById("after_customer_details"),r=n.getElementById("checkout-after-success");null!==r?c=r:null!==o.offsetParent?c=n.getElementById("checkout_continue"):null!==a.offsetParent&&(c=n.getElementById("checkout_back")),c.focus(),e.preventDefault()}})),document.getElementById("newspack-a11y-last-element").addEventListener("focus",(()=>{o.focus()}))):(c=n[n.length-1],document.addEventListener("keydown",(function(e){("Tab"===e.key||9===e.keyCode)&&(e.shiftKey?document.activeElement===o&&(c.focus(),e.preventDefault()):document.activeElement===c&&(o.focus(),e.preventDefault()))})))}const t=(e,t={})=>({...t,action:e}),n=["action","action_type","amount","currency","product_id","product_type","variation_id","variation_ids","is_variable","is_grouped","child_ids","price_summary","newspack_popup_id","gate_post_id","recurrence","referrer"],o=(e,t="np_modal_checkout_interaction")=>{if("function"==typeof window.gtag&&e){const o={};for(const t of n)e[t]&&("boolean"==typeof e[t]?e[t]=e[t]?"yes":"no":"true"===e[t]?e[t]="yes":"false"===e[t]&&(e[t]="no"),o[t]=e[t].toString());window.gtag("event",t,o)}},c=e=>{if("function"!=typeof window.gtag)return;let n="opened";const{amount:c="",is_variable:a="",is_grouped:r="",price:s="",variation_id:i=""}=e,l={...e};(c||s)&&(l.amount=c||s),a&&!i&&(n="opened_variations"),r&&(n="opened_grouped");const d=t(n,l);o(d)};function a(e,t=null){const n=document.createElement("input");return n.type="hidden",n.name=e,t&&(n.value=t),n}function r(e){e.requestSubmit(e.querySelector('button[type="submit"]'))}function s(e){const t="string"==typeof e?document.getElementById(e):e;if(!t)return console.warn("No container found for checkout data"),{};let n={};if("FORM"===t.tagName){const e=new FormData(t);n=Object.fromEntries(e)}const o=t.dataset.checkout;if(!o)return console.warn("No checkout data found"),n;try{n={...n,...JSON.parse(o)}}catch(e){console.warn("Error parsing checkout data")}const c=new URL(t.ownerDocument.defaultView.location.href);return c.searchParams.get("action_type")&&(n.action_type=c.searchParams.get("action_type")),n.memberships_content_gate&&(n.gate_post_id=n.memberships_content_gate,delete n.memberships_content_gate),n}const i=e=>{if("function"!=typeof window.gtag)return;e=e||s("newspack_modal_checkout");const n=t("dismissed",e);o(n)},l=newspackBlocksModal.newspack_class_prefix,d="newspack_modal_checkout_iframe",u="newspack_modal_checkout_container",m=`${l}__modal`,p="newspack-blocks__modal-variation";let _=!1,h=newspackBlocksModal.labels.checkout_modal_title;const w=e=>{e.overlayId&&window.newspackReaderActivation?.overlays&&window.newspackReaderActivation?.overlays.remove(e.overlayId),e.setAttribute("data-state","closed"),document.body.style.overflow="auto"};window.onpageshow=e=>{e.persisted&&(document.querySelectorAll(".modal-processing").forEach((e=>e.classList.remove("modal-processing"))),document.querySelectorAll(".non-modal-checkout-loading").forEach((e=>e.classList.remove("non-modal-checkout-loading"))),document.querySelectorAll(`.${m}-container`).forEach((e=>w(e))))};const y=new CustomEvent("checkout-closed");var k;window.newspackRAS=window.newspackRAS||[],k=()=>{const t=document.querySelector("#newspack_modal_checkout");if(!t)return;const n=t.querySelector(`.${m}__content`),o=a("modal_checkout","1"),k=n.querySelector(`.${l}__spinner`);let f=document.querySelector(".newspack-reader__account-link")?.[0];const v="600px",g=document.createElement("iframe");g.name=d,g.style.height=v,g.style.visibility="hidden";const b=e=>{L.observe(e),"none"!==k.style.display&&(k.style.display="none"),"visible"!==g.style.visibility&&(g.style.visibility="visible"),g._ready=!0};!function(e,t,n){e._ready=!1,e._readyTimer&&clearTimeout(e._readyTimer);let o=!1,c="";function a(){o||(o=!0,clearTimeout(e._readyTimer),t.call(this))}function r(){"complete"===this.readyState&&a.call(this)}function s(){e._ready=!1,n&&n(),e._readyTimer&&clearTimeout(e._readyTimer);const t=e.contentDocument||e.contentWindow?.document;t&&(t.removeEventListener("DOMContentLoaded",a),t.removeEventListener("readystatechange",r))}function i(){if(e._ready)return void s();const t=e.contentDocument||e.contentWindow?.document;t&&0!==t.URL.indexOf("about:")?"complete"===t?.readyState?a.call(t):(t.addEventListener("DOMContentLoaded",a),t.addEventListener("readystatechange",r)):e._readyTimer=setTimeout(i,10)}e._observer||(e._observer=new MutationObserver((e=>{e.forEach((e=>{"attributes"===e.type&&"src"===e.attributeName&&(o=!1,s(),i())}))})),e._observer.observe(e,{attributes:!0})),e._locationObserver||(e._locationObserver=setInterval((function(){const t=e.contentDocument||e.contentWindow?.document;t&&t.URL!==c&&(c=t.URL,o=!1,s(),i())}),50)),i()}(g,(function(){const n=g.contentWindow?.location;if(window.newspackReaderActivation&&n?.href?.includes("order-received")){const e=window.newspackReaderActivation,t=new Proxy(new URLSearchParams(n.search),{get:(e,t)=>e.get(t)});t.email&&(e.setReaderEmail(t.email),e.setAuthenticated(!0))}const o=g?.contentDocument?.querySelector(`#${u}`);if(!o)return;const c=o.querySelector("#modal-checkout-product-details"),a=s(c);!function(e,t){e.checkoutReady?t():e.addEventListener("checkout-ready",t)}(o,(()=>{const e=c?.querySelector("strong");e&&(e.textContent=a.price_summary),C(),B(h),g.contentWindow?.newspackBlocksModalCheckout?.checkout_nonce&&(t.checkout_nonce=g.contentWindow.newspackBlocksModalCheckout.checkout_nonce),b(o)})),function(e,t){e.checkoutComplete?t():e.addEventListener("checkout-complete",t)}(o,(()=>{window.newspackRAS.push(["checkout_completed",a]),window?.newspackReaderActivation?.refreshNewslettersSignupModal&&window?.newspackReaderActivation?.getReader()?.email&&window.newspackReaderActivation.refreshNewslettersSignupModal(window.newspackReaderActivation.getReader().email),C("small"),B(newspackBlocksModal.labels.thankyou_modal_title),b(o),e(t.querySelector(`.${m}`))}))}),(()=>{k.style.display="flex"}));const S=e=>new Promise(((t,n)=>{const o=new URLSearchParams(e);o.append("action","modal_checkout_request"),fetch(newspackBlocksModal.ajax_url+"?"+o.toString()).then((e=>{e.ok||n(e),e.json().then((e=>{t(e.url)})).catch(n)})).catch(n)})),E=()=>"undefined"!=typeof newspack_ras_config&&!newspack_ras_config?.is_logged_in&&!window?.newspackReaderActivation?.getReader?.()?.authenticated&&newspackBlocksModal?.is_registration_required&&window?.newspackReaderActivation?.openAuthModal,A=t=>{const n=!newspackBlocksModal.has_unsupported_payment_gateway;n||t.preventDefault();const o=t.target;o.classList.add("modal-processing");const u=s(o);if(u.newspack_donate){const e=u.donation_frequency,t=[...o.querySelectorAll(`.donation-tier__${e}, .donation-frequency__${e}`)],n=u.donation_tier_index;let c,a;n?(c=t[n],a=u[`donation_value_${e}`]):(c=t[0],u[`donation_value_${e}_untiered`]?a=u[`donation_value_${e}_untiered`]:(a=u[`donation_value_${e}`],"other"===a&&(a=u[`donation_value_${e}_other`])));const r=s(c);for(const e in r)u[e]=r[e];u.amount=a,u.price_summary=u.summary_template.replace("{{PRICE}}",function(e,t="USD"){return parseFloat(e).toLocaleString(document.documentElement.lang,{style:"currency",currency:t,currencyDisplay:"narrowSymbol"})}(u.amount,u.currency))}u&&Object.keys(u).forEach((e=>{0===o.querySelectorAll('input[name="'+e+'"]').length&&o.prepend(a(e,u[e]))})),u.variation_id||(f=t.submitter);const m=document.querySelectorAll(`.${p}`);if(m.forEach((e=>{(E()||n)&&w(e)})),u.is_grouped||u.is_variable&&!u.variation_id){const n=[...m].find((e=>e.dataset.productId===u.product_id));if(n)return n.querySelectorAll(`form[target="${d}"]`).forEach((e=>{["after_success_behavior","after_success_url","after_success_button_label"].forEach((t=>{0===e.querySelectorAll('input[name="'+t+'"]').length&&e.prepend(a(t,u[t]))}));const t=e.dataset.checkout;if(t){const n=JSON.parse(t);Object.keys(n).forEach((t=>{0===e.querySelectorAll('input[name="'+t+'"]').length&&e.prepend(a(t,n[t]))}))}})),t.preventDefault(),o.classList.remove("modal-processing"),M(n),e(n,!1),_||c(u),void document.getElementById("newspack_modal_checkout").setAttribute("data-checkout",JSON.stringify(u))}if(n||E())if(o.classList.remove("modal-processing"),_||c(u),_=!0,E()){t.preventDefault();const e=u.price_summary,o=e?`<div class="order-details-summary ${l}__box ${l}__box--text-center"><p><strong>${e}</strong></p></div>`:"",c=S(u);c.then((e=>{window.newspackReaderActivation?.setPendingCheckout?.(e)})),window.newspackReaderActivation.openAuthModal({title:newspackBlocksModal.labels.auth_modal_title,onSuccess:(e,t)=>{c.then((e=>{t?.registered&&n&&(e+=`&${newspackBlocksModal.checkout_registration_flag}=1`),n?r(q(e)):S(u).then(window.location.href=e)})).catch((e=>{console.warn("Unable to generate cart:",e),R()}))},onError:()=>{R()},onDismiss:()=>{i(u),_=!1,document.getElementById("newspack_modal_checkout").removeAttribute("data-checkout")},skipSuccess:!0,skipNewslettersSignup:!0,labels:{signin:{title:newspackBlocksModal.labels.signin_modal_title},register:{title:newspackBlocksModal.labels.register_modal_title}},content:o,trigger:t.submitter,closeOnSuccess:n})}else $(),document.getElementById("newspack_modal_checkout").setAttribute("data-checkout",JSON.stringify(u));else S(u).then((e=>{window.location.href=e})),(!u.is_variable||u.variation_id)&&o.querySelectorAll("button[type=submit]:focus").forEach((e=>{e.classList.add("non-modal-checkout-loading");const t=e.innerHTML;e.innerHTML="<span>"+t+"</span>"}))},q=e=>{const t=document.createElement("form");t.method="POST",t.action=e,t.target=d,t.style.display="none";const n=document.createElement("button");return n.setAttribute("type","submit"),t.appendChild(n),document.body.appendChild(t),t.addEventListener("submit",A),t},L=new ResizeObserver((e=>{if(!e||!e.length)return;if(!g.contentDocument)return;const o=e[0].contentRect;if(o){const e=.01*Math.max(document.documentElement.clientHeight,window.innerHeight||0)*90-(t.querySelector(`.${m}__header`)?.offsetHeight||0),c=o.top+o.bottom,a=Math.min(c,e);if(0===a)return void(g.style.visibility="hidden");n.style.height=a+"px",g.style.height=a+"px"}})),R=()=>{const e=g?.contentDocument?.querySelector(`#${u}`),o=e?.querySelector('input[name="after_success_url"]'),c=e?.querySelector('input[name="after_success_behavior"]'),a=document?.querySelector(".newspack-newsletters-signup-modal");e?.checkoutComplete||(async()=>{const e=new FormData;newspackBlocksModal.has_unsupported_payment_gateway||e.append("modal_checkout","1"),e.append("action","abandon_modal_checkout"),e.append("_wpnonce",t.checkout_nonce),t.checkout_nonce=null;try{await fetch(newspackBlocksModal.ajax_url,{method:"POST",body:e})}catch(e){console.warn("Unable to empty cart:",e)}})();const r=!(g.contentDocument&&o&&c&&e?.checkoutComplete);if((r||a)&&(k.style.display="flex",g&&n.contains(g)&&(g._ready=!1,g.src="about:blank",g.style.height=v,g.style.visibility="hidden",n.style.height=v,n.removeChild(g)),L&&L.disconnect(),document.querySelectorAll(`.${m}-container`).forEach((e=>w(e))),f&&f.focus(),document.dispatchEvent(y)),e?.checkoutComplete){const e=()=>{if(o&&c){const e=o.getAttribute("value"),t=c.getAttribute("value");"custom"===t?window.location.href=e:"referrer"===t&&window.history.back()}window?.newspackReaderActivation?.setPendingCheckout?.(),_=!1};window?.newspackReaderActivation?.openNewslettersSignupModal?window.newspackReaderActivation.openNewslettersSignupModal({onSuccess:e,onError:e,closeOnSuccess:r}):e(),r&&(h=newspackBlocksModal.labels.checkout_modal_title,C(),B(h))}else window?.newspackReaderActivation?.setPendingCheckout?.(),i(),_=!1,document.getElementById("newspack_modal_checkout").removeAttribute("data-checkout");document.removeEventListener("keydown",D)},$=o=>{o&&(g.src=o),k.style.display="flex",M(t),n.appendChild(g),t.addEventListener("click",(e=>{e.target===t&&R()})),e(t,g),document.addEventListener("keydown",D)},M=e=>{window.newspackReaderActivation?.overlays&&(e.overlayId=window.newspackReaderActivation?.overlays.add()),e.setAttribute("data-state","open"),document.body.style.overflow="hidden"},B=e=>{const n=t.querySelector(`.${m}__header h2`);n&&(n.innerText=e)},C=(e="default")=>{const n=t.querySelector(`.${m}`);n&&("small"===e?n.classList.add(`${m}--small`):n.classList.remove(`${m}--small`))};t.querySelectorAll(`.${m}__close`).forEach((e=>{e.addEventListener("click",(e=>{e.preventDefault(),R()}))})),document.querySelectorAll(".newspack-blocks__modal-variation").forEach((e=>{e.addEventListener("click",(t=>{t.target===e&&R()})),e.querySelectorAll(`.${m}__close`).forEach((e=>{e.addEventListener("click",(e=>{e.preventDefault(),R()}))}))}));const D=e=>{"Escape"===e.key&&R()};document.querySelectorAll(".wpbnbd.wpbnbd--platform-wc, .wp-block-newspack-blocks-checkout-button, .newspack-blocks__modal-variation").forEach((e=>{e.querySelectorAll("form").forEach((e=>{newspackBlocksModal.has_unsupported_payment_gateway||e.prepend(o.cloneNode()),e.target=d,e.addEventListener("submit",A)}))})),(()=>{const e=new URLSearchParams(window.location.search);if(!e.has("checkout"))return;const t=e.get("type");if("donate"===t){const t=e.get("layout"),n=e.get("frequency"),o=e.get("amount"),c=e.get("other");t&&n&&o&&((e,t,n,o=null)=>{let c;document.querySelectorAll(".wpbnbd.wpbnbd--platform-wc form").forEach((a=>{const r=a.querySelector(`input[name="donation_frequency"][value="${t}"]`);if(r)if("tiered"===e){const e=document.querySelector(`button[data-frequency-slug="${t}"]`);if(!e)return;e.click();const o=a.querySelector(`button[type="submit"][name="donation_value_${t}"][value="${n}"]`);if(!o)return;o.click()}else{const s="untiered"===e?a.querySelector(`input[name="donation_value_${t}_untiered"]`):a.querySelector(`input[name="donation_value_${t}"][value="${n}"]`);if(r&&s){if(r.checked=!0,"untiered"===e)s.value=n;else if("other"===n){s.click();const e=a.querySelector(`input[name="donation_value_${t}_other"]`);e&&o&&(e.value=o)}else s.checked=!0;c=a}}})),c&&r(c)})(t,n,o,c)}else if("checkout_button"===t){const t=e.get("product_id"),n=e.get("variation_id");t&&((e,t=null)=>{let n;if(t&&t!==e){const o=[...document.querySelectorAll(`.${p}`)].find((t=>t.dataset.productId===e));o&&o.querySelectorAll(`form[target="${d}"]`).forEach((e=>{const o=JSON.parse(e.dataset.checkout);o?.variation_id===Number(t)&&(n=e)}))}else document.querySelectorAll(".wp-block-newspack-blocks-checkout-button").forEach((t=>{const o=t.querySelector("form");if(!o)return;const c=JSON.parse(o.dataset.checkout);c?.product_id===e&&(n=o)}));n&&r(n)})(t,n)}else{const e=window.newspackReaderActivation?.getPendingCheckout?.();e&&r(q(e))}window.history.replaceState(null,null,window.location.pathname)})(),window.newspackOpenModalCheckout=({url:e=null,title:t=null,actionType:n=null,afterSuccess:o={},onCheckoutComplete:c=null,onClose:a=null})=>{if(h=t||newspackBlocksModal.labels.checkout_modal_title,B(h),(e=new URL(e||newspackBlocksModal.checkout_url)).searchParams.has("my_account_checkout")&&e.searchParams.delete("my_account_checkout"),e.searchParams.has("modal_checkout")||e.searchParams.set("modal_checkout","1"),n&&e.searchParams.set("action_type",n),o?.url&&e.searchParams.set("after_success_url",o.url),(o?.behavior||o?.url)&&e.searchParams.set("after_success_behavior",o.behavior||"custom"),o?.buttonLabel&&e.searchParams.set("after_success_button_label",o.buttonLabel),c){const e=({detail:{action:e,data:t}})=>{"checkout_completed"===e&&c(t)};window.newspackRAS.push((t=>{t.on("activity",e);const n=()=>{t.off("activity",e),document.removeEventListener("checkout-closed",n)};document.addEventListener("checkout-closed",n)}))}if(a){const e=()=>{a(),document.removeEventListener("checkout-closed",e)};document.addEventListener("checkout-closed",e)}$(e.toString())},window.newspackCloseModalCheckout=R},"undefined"!=typeof document&&("complete"!==document.readyState&&"interactive"!==document.readyState?document.addEventListener("DOMContentLoaded",k):k())})();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
<?php return array('dependencies' => array(), 'version' => '
|
|
1
|
+
<?php return array('dependencies' => array(), 'version' => 'cd09bcde5a6631202487');
|
package/dist/modalCheckout.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
(()=>{"use strict";const e=(e,t={})=>({...t,action:e}),t=["action","action_type","amount","currency","product_id","product_type","variation_id","price_summary","newspack_popup_id","gate_post_id","recurrence","referrer"],o=(e,o="np_modal_checkout_interaction")=>{if("function"==typeof window.gtag&&e){const c={};for(const o of t)e[o]&&(c[o]=e[o].toString());window.gtag("event",o,c)}};function c(e){"undefined"!=typeof document&&"function"==typeof e&&("complete"!==document.readyState&&"interactive"!==document.readyState?document.addEventListener("DOMContentLoaded",e):e())}function n(e){const t="string"==typeof e?document.getElementById(e):e;if(!t)return console.warn("No container found for checkout data"),{};let o={};if("FORM"===t.tagName){const e=new FormData(t);o=Object.fromEntries(e)}const c=t.dataset.checkout;if(!c)return console.warn("No checkout data found"),o;try{o={...o,...JSON.parse(c)}}catch(e){console.warn("Error parsing checkout data")}const n=new URL(t.ownerDocument.defaultView.location.href);return n.searchParams.get("action_type")&&(o.action_type=n.searchParams.get("action_type")),o.memberships_content_gate&&(o.gate_post_id=o.memberships_content_gate,delete o.memberships_content_gate),o}const i=(t="continue")=>{if("function"!=typeof window.gtag)return;const{action_type:c,amount:i,currency:a,product_id:r,product_type:s,recurrence:d,referrer:u,variation_id:p="",gate_post_id:l="",newspack_popup_id:_=""}=n("modal-checkout-product-details"),m={action_type:c,amount:i,currency:a,product_id:r,product_type:s,recurrence:d,referrer:u};p&&(m.variation_id=p),l&&(m.gate_post_id=l),_&&(m.newspack_popup_id=_);const h=e(t,m);o(h)};var a;a=jQuery,c((()=>{if(!a)return void console.warn("jQuery is not available.");const t=newspackBlocksModalCheckout.newspack_class_prefix,r=new CustomEvent("checkout-ready"),s=new CustomEvent("checkout-complete");function d(){a(`.woocommerce-NoticeGroup-checkout, .${t}__inline-error, .woocommerce-error, .woocommerce-message, .wc-block-components-notice-banner, .woocommerce-notices-wrapper`).remove()}function u(t=!0){const i=document.querySelector("#newspack_modal_checkout_container");i.checkoutReady=!0,i.dispatchEvent(r),t&&c((function(){if("function"!=typeof window.gtag)return;const t=n("modal-checkout-product-details"),c=e("loaded",t);o(c)}))}if(newspackBlocksModalCheckout.is_checkout_complete){(()=>{if("function"!=typeof window.gtag)return;const t=n("modal-checkout-product-details"),c=e("form_submission_success",t);o(c)})();const l=document.querySelector("#newspack_modal_checkout_container");l&&(l.checkoutComplete=!0,l.dispatchEvent(s))}else{function _(){a("#wcpay-express-checkout-button-separator, #wc-stripe-payment-request-button-separator, #wc-stripe-express-checkout-button-separator").after('<div class="newspack-ui__word-divider">'+newspackBlocksModalCheckout.divider_text+"</div>");let c=[];const r=a("form.checkout");if(!r.length)return console.warn("Checkout form is not available"),void u();const s=a("form.modal_checkout_coupon"),l=a("form.modal_checkout_nyp"),_=a("#checkout_continue"),m=a("#customer_details"),h=a("#after_customer_details"),f=a(".newspack-wcsg--wrapper");function g(){const e=a('input[name="payment_method"]:checked').val();a(".wc_payment_method").removeClass("selected"),a(".wc_payment_method.payment_method_"+e).addClass("selected")}function k(){let e;if(a.ajax({url:newspackBlocksModalCheckout.ajax_url,method:"POST",async:!1,data:{action:"get_cart_total"},success:t=>{e=t}}),e)return e}if(a('input[name="payment_method"]').change(g),a(document).on("payment_method_selected",g),a(document).on("updated_checkout",g),g(),a(document).on("updated_checkout",(function(){a("#payment .wc_payment_methods").length?a("#after_customer_details > h3").show():a("#after_customer_details > h3").hide()})),a(document).on("updated_checkout",(function(){const e=a(".order-review-wrapper");if(!e.length)return;const t=e.find("table");t.is(".empty")?e.addClass("hidden"):(t.unblock(),e.removeClass("hidden"));const o=a("#after_customer_details").hasClass("transaction-details-expanded"),c=a(".payment_methods");if(c.length){const t=e.clone();o&&a('[id="order_review_heading"]',t).attr("aria-expanded","true"),a(".order-review-wrapper").remove(),c.after(t)}else o||e.find("#order_review_heading").trigger("click")})),a(document).on("click","#order_review_heading",(function(){a(this).attr("aria-expanded",(function(e,t){return"false"===t?"true":"false"})),a("#after_customer_details").toggleClass("transaction-details-expanded")})),a(document).on("updated_checkout",(function(){let e=newspackBlocksModalCheckout.labels.complete_button;if(e){if(a("#place_order").has(a("span.cart-price"))){const t=a("<div>"+e+"</div>");t.find(".cart-price").html(k,(function(){return this.childNodes})),e=t.html()}a("#place_order").html(e),a("#place_order_clone").html(e)}})),f.length){const e=f.find(".newspack-wcsg--gift-toggle input"),t=f.find(".newspack-wcsg--gift-email");e.on("change",(function(){e.is(":checked")?t.addClass("visible"):t.removeClass("visible")}))}function w(e){r.find(".input-text, select, input:checkbox").trigger("validate").trigger("blur");let o=!1;const c=[],n=e=>{const n=a("#"+e.data("id")+"_field");if(n?.length){o||(o=n);const c=n.find(".woocommerce-error");c.length&&c.remove(),n.addClass("woocommerce-invalid").removeClass("woocommerce-valid"),n.append(`<span class="${t}__inline-error">`+e.text()+"</span>"),e.remove()}else e.is("li")||(e=a("<li />").append(e)),c.push(e)};if(d(),0!==e.trimStart().indexOf("<")?n(a("<li />").append(e)):e.includes("<li")?a(e).find("li").each((function(){n(a(this))})):n(a(e)),c.length){o=!1;const e=a('<div class="woocommerce-NoticeGroup woocommerce-NoticeGroup-checkout"/>').append(a('<ul class="woocommerce-error" role="alert" />').append(c));r.prepend(e),e.get(0).scrollIntoView({behavior:"smooth"})}o?.length&&(window.scroll({top:o.offset().top-100,left:0,behavior:"smooth"}),o.find("input.input-text, select, input:checkbox").trigger("focus")),x(r),a(document.body).trigger("update_checkout"),a(document.body).trigger("checkout_error",[e])}function y(e){e.preventDefault(),e.stopImmediatePropagation(),v(),i("continue")}function b(e){const t=window.newspack_grecaptcha||{};if(d(),a("#checkout_details").remove(),e)r.attr("data-skip-recaptcha","1"),r.append('<input name="is_validation_only" type="hidden" value="1" />'),"v3"===t?.version&&t.destroy(r.get()),s.length&&s.hide(),l.length&&l.hide(),m.show(),h.hide(),m.find("input").first().focus(),c=function(e,t){const o=a._data(e,"events");return o?t?o[t]||[]:o:[]}(r[0],"submit").slice(0),c.forEach((e=>{r.off("submit",e.handler)})),r.on("submit",y);else{r.removeAttr("data-skip-recaptcha");const e=r.find('[name="is_validation_only"]');if(e.length&&e.remove(),t?.render){r.data("newspack-recaptcha","newspack_modal_checkout");const e=()=>{d(),r.get(0).scrollIntoView({behavior:"smooth"})},o=e=>w(e);t.render(r.get(),e,o),a(document).on("updated_checkout",(()=>t.render(r.get(),e,o))),a(document.body).on("checkout_error",(()=>t.render(r.get(),e,o)))}s.length&&s.show(),l.length&&l.show(),m.hide(),h.show(),function(){a("#checkout_details").remove();const e={};r.serializeArray().forEach((t=>{e[t.name]=t.value}));const t=`${newspackBlocksModalCheckout.newspack_class_prefix}__font--xs`,o=[];o.push('<div class="billing-details">'),o.push("<h3>"+newspackBlocksModalCheckout.labels.billing_details+"</h3>"),(e.billing_first_name||e.billing_last_name)&&o.push(`<p class="${t}">`+e.billing_first_name+" "+e.billing_last_name+"</p>"),e.billing_company&&o.push(`<p class="${t}">`+e.billing_company+"</p>");let c="";if((e.billing_address_1||e.billing_address_2)&&(c=`<p class="${t}">`,e.billing_address_1&&(c+=e.billing_address_1),e.billing_address_2&&(c+=" "+e.billing_address_2),c+="<br>",e.billing_city&&(c+=e.billing_city),e.billing_state&&(c+=", "+e.billing_state),e.billing_postcode&&(c+=" "+e.billing_postcode),c+="<br>",e.billing_country&&(c+=e.billing_country)),o.push(c),e.billing_email&&o.push(`<p class="${t}">`+e.billing_email+"</p>"),o.push("</div>"),e.hasOwnProperty("shipping_address_1")){o.push('<div class="shipping-details">'),o.push("<h3>"+newspackBlocksModalCheckout.labels.shipping_details+"</h3>");let n="";e.ship_to_different_address?(n=`<p class="${t}">`,e.shipping_address_1&&(n+=e.shipping_address_1),e.shipping_address_2&&(n+=" "+e.shipping_address_2),n+="<br>",e.shipping_city&&(n+=e.shipping_city),e.shipping_state&&(n+=", "+e.shipping_state),e.shipping_postcode&&(n+=" "+e.shipping_postcode),n+="<br>",e.shipping_country&&(n+=e.shipping_country)):n=c,o.push(n),o.push("</div>")}e.hasOwnProperty("newspack_wcsg_is_gift")&&e.hasOwnProperty("wcsg_gift_recipients_email")&&e.newspack_wcsg_is_gift&&e.wcsg_gift_recipients_email&&(o.push('<div class="gift-details">'),o.push("<h3>"+newspackBlocksModalCheckout.labels.gift_recipient+"</h3>"),o.push(`<p class="${t}">`+e.wcsg_gift_recipients_email+"</p>")),a(".order-details-summary").after('<div id="checkout_details">'+o.join("")+"</div>")}(),r.off("submit",y),c.forEach((e=>{r.on("submit",e.handler)})),p()}r.triggerHandler("editing_details",[e]),window.scroll({top:0,left:0,behavior:"smooth"})}function v(e=!1,o=(()=>{})){if(!C(r))return console.warn("Unable to block the form"),o(),!1;d();const c=r.find(".woocommerce-NoticeGroup.woocommerce-NoticeGroup-checkout");c.length&&c.remove();const n=["save_user_in_woopay"],s=r.serializeArray().filter((e=>!n.includes(e.name)));s.push({name:"woocommerce_checkout_update_totals",value:"1"}),a.ajax({type:"POST",url:wc_checkout_params.checkout_url,data:s,dataType:"html",success:c=>{let n;try{n=JSON.parse(c)}catch(e){n={messages:'<div class="woocommerce-error">'+wc_checkout_params.i18n_checkout_error+"</div>"}}e||!0!==n.reload?(x(r),n.messages?e||(n.messages?w(n.messages):w(`<div class="${t}__inline-error">`+wc_checkout_params.i18n_checkout_error+"</div>")):(b(!1),a._data(r[0],"events")?.click?.some((e=>"#checkout_back"===e.selector))||r.on("click","#checkout_back",(function(e){e.preventDefault(),b(!0),i("back")}))),o(n)):window.location.reload()},error:(t,c,n)=>{let i="";e||(i='<div class="woocommerce-error">'+(n||wc_checkout_params.i18n_checkout_error)+"</div>",w(i)),o({messages:i})}})}function C(e){return!e.is(".modal-processing")&&(e.find("button[type=submit]").each(((e,t)=>{a(t).attr("disabled",!0)})),e.addClass("modal-processing"),!0)}function x(e){return!!e.is(".modal-processing")&&(e.find("button[type=submit]").each(((e,t)=>{a(t).attr("disabled",!1)})),e.removeClass("modal-processing"),!0)}_.length?(b(!0),f.length?u():v(!0,u)):u(),s.length&&(s.on("submit",(function(e){if(e.preventDefault(),!C(s))return!1;const o={security:wc_checkout_params.apply_coupon_nonce,coupon_code:s.find('input[name="coupon_code"]').val()};a.ajax({type:"POST",url:wc_checkout_params.wc_ajax_url.toString().replace("%%endpoint%%","apply_coupon"),data:o,dataType:"html",success:e=>{if(d(),s.find(".result").remove(),e){const c=e.includes("error");s.append(`<p class="result ${t}__helper-text ${c?t+"__inline-error":""}">`+a(e).text()+"</p>"),c?(s.find('input[name="coupon_code"]').focus(),s.find('h3, input[name="coupon_code"]').addClass("newspack-ui__field-error")):(s.find('input[name="coupon_code"]').focus(),s.find('h3, input[name="coupon_code"]').removeClass("newspack-ui__field-error")),a(document.body).trigger("applied_coupon_in_checkout",[o.coupon_code]),a(document.body).trigger("update_checkout",{update_shipping_method:!1})}},complete:()=>{x(s)}})})),a(document.body).on("removed_coupon_in_checkout",(()=>{d(),s.find(".result").remove(),s.find('input[name="coupon_code"]').val("").focus()}))),l.length&&l.on("submit",(function(e){if(e.preventDefault(),!C(l))return!1;const o=l.find('input[name="price"]');o.attr("disabled",!0);const c={_ajax_nonce:newspackBlocksModalCheckout.nyp_nonce,action:"process_name_your_price_request",price:l.find('input[name="price"]').val(),product_id:l.find('input[name="product_id"]').val(),newspack_checkout_name_your_price:l.find('input[name="newspack_checkout_name_your_price"]').val()};a.ajax({type:"POST",url:newspackBlocksModalCheckout.ajax_url,data:c,success:({success:e,data:o})=>{d(),l.find(".result").remove(),l.append(`<p class="result ${t}__helper-text ${e?"":t+"__inline-error"}">`+o.message+"</p>"),e?l.find('h3, input[name="price"]').removeClass("newspack-ui__field-error"):(l.find('input[name="price"]').focus(),l.find('h3, input[name="price"]').addClass("newspack-ui__field-error")),a(document.body).trigger("update_checkout",{update_shipping_method:!1})},complete:()=>{x(l),o.attr("disabled",!1),o.focus()}})})),r.on("click","#place_order",(function(){(()=>{if("function"!=typeof window.gtag)return;const t=n("modal-checkout-product-details"),c=e("form_submission",t);o(c)})()}))}_()}function p(){const e=a("#newspack_subscription_terms_confirmation, #newspack_subscription_confirmation");if(e.length){const t=a("form.checkout"),o=t.find("button#place_order, button#place_order_clone");function c(){const t=e.is(":checked");o.each(((e,o)=>{a(o).attr("disabled",!t)}))}c(),e.on("change",c),t.on("submit",(function(t){if(!e.is(":checked"))return t.preventDefault(),t.stopPropagation(),!1}))}}a(document.body).on("updated_checkout payment_method_selected checkout_error",p),a(document).ready(p),a(document.body).on("checkout_error",(function(){const e=a(".woocommerce-NoticeGroup-checkout, .woocommerce-notices-wrapper");e.length&&e.each(((e,o)=>a(o).addClass(`${t}__notice ${t}__notice--error`)));const o=a("#checkout_error_back");o.length&&o.on("click",(e=>{e.preventDefault(),parent.newspackCloseModalCheckout()})),u(!1)})),document.addEventListener("keydown",(function(e){"Escape"===e.key&&parent.newspackCloseModalCheckout()})),newspackBlocksModalCheckout.is_error&&a(document.body).trigger("checkout_error")}))})();
|
|
1
|
+
(()=>{"use strict";const e=(e,t={})=>({...t,action:e}),t=["action","action_type","amount","currency","product_id","product_type","variation_id","variation_ids","is_variable","is_grouped","child_ids","price_summary","newspack_popup_id","gate_post_id","recurrence","referrer"],o=(e,o="np_modal_checkout_interaction")=>{if("function"==typeof window.gtag&&e){const n={};for(const o of t)e[o]&&("boolean"==typeof e[o]?e[o]=e[o]?"yes":"no":"true"===e[o]?e[o]="yes":"false"===e[o]&&(e[o]="no"),n[o]=e[o].toString());window.gtag("event",o,n)}};function n(e){"undefined"!=typeof document&&"function"==typeof e&&("complete"!==document.readyState&&"interactive"!==document.readyState?document.addEventListener("DOMContentLoaded",e):e())}function c(e){const t="string"==typeof e?document.getElementById(e):e;if(!t)return console.warn("No container found for checkout data"),{};let o={};if("FORM"===t.tagName){const e=new FormData(t);o=Object.fromEntries(e)}const n=t.dataset.checkout;if(!n)return console.warn("No checkout data found"),o;try{o={...o,...JSON.parse(n)}}catch(e){console.warn("Error parsing checkout data")}const c=new URL(t.ownerDocument.defaultView.location.href);return c.searchParams.get("action_type")&&(o.action_type=c.searchParams.get("action_type")),o.memberships_content_gate&&(o.gate_post_id=o.memberships_content_gate,delete o.memberships_content_gate),o}const i=(t="continue")=>{if("function"!=typeof window.gtag)return;const{action_type:n,amount:i,currency:a,product_id:r,product_type:s,recurrence:d,referrer:u,variation_id:p="",gate_post_id:l="",newspack_popup_id:_=""}=c("modal-checkout-product-details"),m={action_type:n,amount:i,currency:a,product_id:r,product_type:s,recurrence:d,referrer:u};p&&(m.variation_id=p),l&&(m.gate_post_id=l),_&&(m.newspack_popup_id=_);const h=e(t,m);o(h)};var a;a=jQuery,n((()=>{if(!a)return void console.warn("jQuery is not available.");const t=newspackBlocksModalCheckout.newspack_class_prefix,r=new CustomEvent("checkout-ready"),s=new CustomEvent("checkout-complete");function d(){a(`.woocommerce-NoticeGroup-checkout, .${t}__inline-error, .woocommerce-error, .woocommerce-message, .wc-block-components-notice-banner, .woocommerce-notices-wrapper`).remove()}function u(t=!0){const i=document.querySelector("#newspack_modal_checkout_container");i.checkoutReady=!0,i.dispatchEvent(r),t&&n((function(){if("function"!=typeof window.gtag)return;const t=c("modal-checkout-product-details"),n=e("loaded",t);o(n)}))}if(newspackBlocksModalCheckout.is_checkout_complete){(()=>{if("function"!=typeof window.gtag)return;const t=c("modal-checkout-product-details"),n=e("form_submission_success",t);o(n)})();const l=document.querySelector("#newspack_modal_checkout_container");l&&(l.checkoutComplete=!0,l.dispatchEvent(s))}else{function _(){a("#wcpay-express-checkout-button-separator, #wc-stripe-payment-request-button-separator, #wc-stripe-express-checkout-button-separator").after('<div class="newspack-ui__word-divider">'+newspackBlocksModalCheckout.divider_text+"</div>");let n=[];const r=a("form.checkout");if(!r.length)return console.warn("Checkout form is not available"),void u();const s=a("form.modal_checkout_coupon"),l=a("form.modal_checkout_nyp"),_=a("#checkout_continue"),m=a("#customer_details"),h=a("#after_customer_details"),f=a(".newspack-wcsg--wrapper");function g(){const e=a('input[name="payment_method"]:checked').val();a(".wc_payment_method").removeClass("selected"),a(".wc_payment_method.payment_method_"+e).addClass("selected")}function k(){let e;if(a.ajax({url:newspackBlocksModalCheckout.ajax_url,method:"POST",async:!1,data:{action:"get_cart_total"},success:t=>{e=t}}),e)return e}if(a('input[name="payment_method"]').change(g),a(document).on("payment_method_selected",g),a(document).on("updated_checkout",g),g(),a(document).on("updated_checkout",(function(){a("#payment .wc_payment_methods").length?a("#after_customer_details > h3").show():a("#after_customer_details > h3").hide()})),a(document).on("updated_checkout",(function(){const e=a(".order-review-wrapper");if(!e.length)return;const t=e.find("table");t.is(".empty")?e.addClass("hidden"):(t.unblock(),e.removeClass("hidden"));const o=a("#after_customer_details").hasClass("transaction-details-expanded"),n=a(".payment_methods");if(n.length){const t=e.clone();o&&a('[id="order_review_heading"]',t).attr("aria-expanded","true"),a(".order-review-wrapper").remove(),n.after(t)}else o||e.find("#order_review_heading").trigger("click")})),a(document).on("click","#order_review_heading",(function(){a(this).attr("aria-expanded",(function(e,t){return"false"===t?"true":"false"})),a("#after_customer_details").toggleClass("transaction-details-expanded")})),a(document).on("updated_checkout",(function(){let e=newspackBlocksModalCheckout.labels.complete_button;if(e){if(a("#place_order").has(a("span.cart-price"))){const t=a("<div>"+e+"</div>");t.find(".cart-price").html(k,(function(){return this.childNodes})),e=t.html()}a("#place_order").html(e),a("#place_order_clone").html(e)}})),f.length){const e=f.find(".newspack-wcsg--gift-toggle input"),t=f.find(".newspack-wcsg--gift-email");e.on("change",(function(){e.is(":checked")?t.addClass("visible"):t.removeClass("visible")}))}function w(e){r.find(".input-text, select, input:checkbox").trigger("validate").trigger("blur");let o=!1;const n=[],c=e=>{const c=a("#"+e.data("id")+"_field");if(c?.length){o||(o=c);const n=c.find(".woocommerce-error");n.length&&n.remove(),c.addClass("woocommerce-invalid").removeClass("woocommerce-valid"),c.append(`<span class="${t}__inline-error">`+e.text()+"</span>"),e.remove()}else e.is("li")||(e=a("<li />").append(e)),n.push(e)};if(d(),0!==e.trimStart().indexOf("<")?c(a("<li />").append(e)):e.includes("<li")?a(e).find("li").each((function(){c(a(this))})):c(a(e)),n.length){o=!1;const e=a('<div class="woocommerce-NoticeGroup woocommerce-NoticeGroup-checkout"/>').append(a('<ul class="woocommerce-error" role="alert" />').append(n));r.prepend(e),e.get(0).scrollIntoView({behavior:"smooth"})}o?.length&&(window.scroll({top:o.offset().top-100,left:0,behavior:"smooth"}),o.find("input.input-text, select, input:checkbox").trigger("focus")),x(r),a(document.body).trigger("update_checkout"),a(document.body).trigger("checkout_error",[e])}function y(e){e.preventDefault(),e.stopImmediatePropagation(),v(),i("continue")}function b(e){const t=window.newspack_grecaptcha||{};if(d(),a("#checkout_details").remove(),e)r.attr("data-skip-recaptcha","1"),r.append('<input name="is_validation_only" type="hidden" value="1" />'),"v3"===t?.version&&t.destroy(r.get()),s.length&&s.hide(),l.length&&l.hide(),m.show(),h.hide(),m.find("input").first().focus(),n=function(e,t){const o=a._data(e,"events");return o?t?o[t]||[]:o:[]}(r[0],"submit").slice(0),n.forEach((e=>{r.off("submit",e.handler)})),r.on("submit",y);else{r.removeAttr("data-skip-recaptcha");const e=r.find('[name="is_validation_only"]');if(e.length&&e.remove(),t?.render){r.data("newspack-recaptcha","newspack_modal_checkout");const e=()=>{d(),r.get(0).scrollIntoView({behavior:"smooth"})},o=e=>w(e);t.render(r.get(),e,o),a(document).on("updated_checkout",(()=>t.render(r.get(),e,o))),a(document.body).on("checkout_error",(()=>t.render(r.get(),e,o)))}s.length&&s.show(),l.length&&l.show(),m.hide(),h.show(),function(){a("#checkout_details").remove();const e={};r.serializeArray().forEach((t=>{e[t.name]=t.value}));const t=`${newspackBlocksModalCheckout.newspack_class_prefix}__font--xs`,o=[];o.push('<div class="billing-details">'),o.push("<h3>"+newspackBlocksModalCheckout.labels.billing_details+"</h3>"),(e.billing_first_name||e.billing_last_name)&&o.push(`<p class="${t}">`+e.billing_first_name+" "+e.billing_last_name+"</p>"),e.billing_company&&o.push(`<p class="${t}">`+e.billing_company+"</p>");let n="";if((e.billing_address_1||e.billing_address_2)&&(n=`<p class="${t}">`,e.billing_address_1&&(n+=e.billing_address_1),e.billing_address_2&&(n+=" "+e.billing_address_2),n+="<br>",e.billing_city&&(n+=e.billing_city),e.billing_state&&(n+=", "+e.billing_state),e.billing_postcode&&(n+=" "+e.billing_postcode),n+="<br>",e.billing_country&&(n+=e.billing_country)),o.push(n),e.billing_email&&o.push(`<p class="${t}">`+e.billing_email+"</p>"),o.push("</div>"),e.hasOwnProperty("shipping_address_1")){o.push('<div class="shipping-details">'),o.push("<h3>"+newspackBlocksModalCheckout.labels.shipping_details+"</h3>");let c="";e.ship_to_different_address?(c=`<p class="${t}">`,e.shipping_address_1&&(c+=e.shipping_address_1),e.shipping_address_2&&(c+=" "+e.shipping_address_2),c+="<br>",e.shipping_city&&(c+=e.shipping_city),e.shipping_state&&(c+=", "+e.shipping_state),e.shipping_postcode&&(c+=" "+e.shipping_postcode),c+="<br>",e.shipping_country&&(c+=e.shipping_country)):c=n,o.push(c),o.push("</div>")}e.hasOwnProperty("newspack_wcsg_is_gift")&&e.hasOwnProperty("wcsg_gift_recipients_email")&&e.newspack_wcsg_is_gift&&e.wcsg_gift_recipients_email&&(o.push('<div class="gift-details">'),o.push("<h3>"+newspackBlocksModalCheckout.labels.gift_recipient+"</h3>"),o.push(`<p class="${t}">`+e.wcsg_gift_recipients_email+"</p>")),a(".order-details-summary").after('<div id="checkout_details">'+o.join("")+"</div>")}(),r.off("submit",y),n.forEach((e=>{r.on("submit",e.handler)})),p()}r.triggerHandler("editing_details",[e]),window.scroll({top:0,left:0,behavior:"smooth"})}function v(e=!1,o=(()=>{})){if(!C(r))return console.warn("Unable to block the form"),o(),!1;d();const n=r.find(".woocommerce-NoticeGroup.woocommerce-NoticeGroup-checkout");n.length&&n.remove();const c=["save_user_in_woopay"],s=r.serializeArray().filter((e=>!c.includes(e.name)));s.push({name:"woocommerce_checkout_update_totals",value:"1"}),a.ajax({type:"POST",url:wc_checkout_params.checkout_url,data:s,dataType:"html",success:n=>{let c;try{c=JSON.parse(n)}catch(e){c={messages:'<div class="woocommerce-error">'+wc_checkout_params.i18n_checkout_error+"</div>"}}e||!0!==c.reload?(x(r),c.messages?e||(c.messages?w(c.messages):w(`<div class="${t}__inline-error">`+wc_checkout_params.i18n_checkout_error+"</div>")):(b(!1),a._data(r[0],"events")?.click?.some((e=>"#checkout_back"===e.selector))||r.on("click","#checkout_back",(function(e){e.preventDefault(),b(!0),i("back")}))),o(c)):window.location.reload()},error:(t,n,c)=>{let i="";e||(i='<div class="woocommerce-error">'+(c||wc_checkout_params.i18n_checkout_error)+"</div>",w(i)),o({messages:i})}})}function C(e){return!e.is(".modal-processing")&&(e.find("button[type=submit]").each(((e,t)=>{a(t).attr("disabled",!0)})),e.addClass("modal-processing"),!0)}function x(e){return!!e.is(".modal-processing")&&(e.find("button[type=submit]").each(((e,t)=>{a(t).attr("disabled",!1)})),e.removeClass("modal-processing"),!0)}_.length?(b(!0),f.length?u():v(!0,u)):u(),s.length&&(s.on("submit",(function(e){if(e.preventDefault(),!C(s))return!1;const o={security:wc_checkout_params.apply_coupon_nonce,coupon_code:s.find('input[name="coupon_code"]').val()};a.ajax({type:"POST",url:wc_checkout_params.wc_ajax_url.toString().replace("%%endpoint%%","apply_coupon"),data:o,dataType:"html",success:e=>{if(d(),s.find(".result").remove(),e){const n=e.includes("error");s.append(`<p class="result ${t}__helper-text ${n?t+"__inline-error":""}">`+a(e).text()+"</p>"),n?(s.find('input[name="coupon_code"]').focus(),s.find('h3, input[name="coupon_code"]').addClass("newspack-ui__field-error")):(s.find('input[name="coupon_code"]').focus(),s.find('h3, input[name="coupon_code"]').removeClass("newspack-ui__field-error")),a(document.body).trigger("applied_coupon_in_checkout",[o.coupon_code]),a(document.body).trigger("update_checkout",{update_shipping_method:!1})}},complete:()=>{x(s)}})})),a(document.body).on("removed_coupon_in_checkout",(()=>{d(),s.find(".result").remove(),s.find('input[name="coupon_code"]').val("").focus()}))),l.length&&l.on("submit",(function(e){if(e.preventDefault(),!C(l))return!1;const o=l.find('input[name="price"]');o.attr("disabled",!0);const n={_ajax_nonce:newspackBlocksModalCheckout.nyp_nonce,action:"process_name_your_price_request",price:l.find('input[name="price"]').val(),product_id:l.find('input[name="product_id"]').val(),newspack_checkout_name_your_price:l.find('input[name="newspack_checkout_name_your_price"]').val()};a.ajax({type:"POST",url:newspackBlocksModalCheckout.ajax_url,data:n,success:({success:e,data:o})=>{d(),l.find(".result").remove(),l.append(`<p class="result ${t}__helper-text ${e?"":t+"__inline-error"}">`+o.message+"</p>"),e?l.find('h3, input[name="price"]').removeClass("newspack-ui__field-error"):(l.find('input[name="price"]').focus(),l.find('h3, input[name="price"]').addClass("newspack-ui__field-error")),a(document.body).trigger("update_checkout",{update_shipping_method:!1})},complete:()=>{x(l),o.attr("disabled",!1),o.focus()}})})),r.on("click","#place_order",(function(){(()=>{if("function"!=typeof window.gtag)return;const t=c("modal-checkout-product-details"),n=e("form_submission",t);o(n)})()}))}_()}function p(){const e=a("#newspack_subscription_terms_confirmation, #newspack_subscription_confirmation");if(e.length){const t=a("form.checkout"),o=t.find("button#place_order, button#place_order_clone");function n(){const t=e.is(":checked");o.each(((e,o)=>{a(o).attr("disabled",!t)}))}n(),e.on("change",n),t.on("submit",(function(t){if(!e.is(":checked"))return t.preventDefault(),t.stopPropagation(),!1}))}}a(document.body).on("updated_checkout payment_method_selected checkout_error",p),a(document).ready(p),a(document.body).on("checkout_error",(function(){const e=a(".woocommerce-NoticeGroup-checkout, .woocommerce-notices-wrapper");e.length&&e.each(((e,o)=>a(o).addClass(`${t}__notice ${t}__notice--error`)));const o=a("#checkout_error_back");o.length&&o.on("click",(e=>{e.preventDefault(),parent.newspackCloseModalCheckout()})),u(!1)})),document.addEventListener("keydown",(function(e){"Escape"===e.key&&parent.newspackCloseModalCheckout()})),newspackBlocksModalCheckout.is_error&&a(document.body).trigger("checkout_error")}))})();
|
|
@@ -304,14 +304,14 @@ final class Modal_Checkout {
|
|
|
304
304
|
$after_success_url = filter_input( INPUT_GET, 'after_success_url', FILTER_SANITIZE_URL );
|
|
305
305
|
$after_success_button_label = filter_input( INPUT_GET, 'after_success_button_label', FILTER_SANITIZE_SPECIAL_CHARS );
|
|
306
306
|
|
|
307
|
-
if ( ! $product_id ) {
|
|
308
|
-
return;
|
|
309
|
-
}
|
|
310
|
-
|
|
311
307
|
if ( $variation_id ) {
|
|
312
308
|
$product_id = $variation_id;
|
|
313
309
|
}
|
|
314
310
|
|
|
311
|
+
if ( ! $product_id ) {
|
|
312
|
+
return;
|
|
313
|
+
}
|
|
314
|
+
|
|
315
315
|
$referer = wp_get_referer();
|
|
316
316
|
$params = [];
|
|
317
317
|
$parsed_url = wp_parse_url( $referer );
|
|
@@ -192,6 +192,26 @@ final class Checkout_Data {
|
|
|
192
192
|
return $data;
|
|
193
193
|
}
|
|
194
194
|
|
|
195
|
+
/**
|
|
196
|
+
* Recursively get the children of a product, returning only ungrouped children.
|
|
197
|
+
*
|
|
198
|
+
* @param \WC_Product $product Product object.
|
|
199
|
+
* @return array Array of child product IDs.
|
|
200
|
+
*/
|
|
201
|
+
public static function get_children( $product ) {
|
|
202
|
+
$children = [];
|
|
203
|
+
foreach ( $product->get_children() as $child_id ) {
|
|
204
|
+
$child = \wc_get_product( $child_id );
|
|
205
|
+
// Check if the child has children of its own.
|
|
206
|
+
if ( method_exists( $child, 'get_children' ) && $child->get_children() ) {
|
|
207
|
+
$children = array_merge( $children, self::get_children( $child ) );
|
|
208
|
+
} else {
|
|
209
|
+
$children[] = $child_id;
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
return $children;
|
|
213
|
+
}
|
|
214
|
+
|
|
195
215
|
/**
|
|
196
216
|
* Returns checkout data given a product, product variation, cart or order object.
|
|
197
217
|
*
|
|
@@ -209,18 +229,30 @@ final class Checkout_Data {
|
|
|
209
229
|
$order = null;
|
|
210
230
|
$referrer = '';
|
|
211
231
|
$variation_id = null;
|
|
232
|
+
$is_variable = false;
|
|
233
|
+
$is_grouped = false;
|
|
212
234
|
|
|
213
|
-
if ( $source instanceof \
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
$product_id
|
|
235
|
+
if ( $source instanceof \WC_Product ) {
|
|
236
|
+
if ( $source->is_type( 'grouped' ) ) {
|
|
237
|
+
$is_grouped = true;
|
|
238
|
+
$product_id = $source->get_id();
|
|
239
|
+
$children = self::get_children( $source );
|
|
240
|
+
} elseif ( $source->is_type( 'variable' ) ) {
|
|
241
|
+
$is_variable = true;
|
|
242
|
+
$product_id = $source->get_id();
|
|
243
|
+
$children = self::get_children( $source );
|
|
244
|
+
} elseif ( $source instanceof \WC_Product_Variation ) {
|
|
245
|
+
$product_id = $source->get_parent_id();
|
|
221
246
|
$variation_id = $source->get_id();
|
|
247
|
+
$amount = $source->get_price();
|
|
248
|
+
} else {
|
|
249
|
+
$product_id = $source->get_id();
|
|
250
|
+
if ( $source->get_parent_id() ) {
|
|
251
|
+
$product_id = $source->get_parent_id();
|
|
252
|
+
$variation_id = $source->get_id();
|
|
253
|
+
}
|
|
254
|
+
$amount = $source->get_price();
|
|
222
255
|
}
|
|
223
|
-
$amount = $source->get_price();
|
|
224
256
|
} elseif ( $source instanceof \WC_Cart ) {
|
|
225
257
|
$cart_items = $source->get_cart();
|
|
226
258
|
$cart_item = reset( $cart_items ); // Use only the first item in the cart.
|
|
@@ -266,18 +298,29 @@ final class Checkout_Data {
|
|
|
266
298
|
}
|
|
267
299
|
|
|
268
300
|
$data = [
|
|
269
|
-
'
|
|
270
|
-
'
|
|
271
|
-
'
|
|
272
|
-
'
|
|
273
|
-
'
|
|
274
|
-
'price_summary' => self::get_price_summary( $name, $amount, $recurrence, $variation_id ? $variation_id : $product_id ),
|
|
275
|
-
'summary_template' => self::get_price_summary( $name, '{{PRICE}}', $recurrence, $variation_id ? $variation_id : $product_id ),
|
|
276
|
-
'referrer' => $referrer ? str_replace( home_url(), '', $referrer ) : '', // Keeps format consistent for Homepage with Donate and Checkout Button blocks.
|
|
277
|
-
'recurrence' => $recurrence,
|
|
278
|
-
'variation_id' => strval( $variation_id ? $variation_id : '' ),
|
|
301
|
+
'action_type' => self::get_action_type( $product_id ),
|
|
302
|
+
'currency' => function_exists( 'get_woocommerce_currency' ) ? \get_woocommerce_currency() : 'USD',
|
|
303
|
+
'product_id' => strval( $product_id ? $product_id : '' ),
|
|
304
|
+
'product_type' => $product_type,
|
|
305
|
+
'referrer' => $referrer ? str_replace( home_url(), '', $referrer ) : '', // Keeps format consistent for Homepage with Donate and Checkout Button blocks.
|
|
279
306
|
];
|
|
280
307
|
|
|
308
|
+
if ( $is_variable ) {
|
|
309
|
+
$data['is_variable'] = true;
|
|
310
|
+
$data['variation_ids'] = $children;
|
|
311
|
+
} elseif ( $is_grouped ) {
|
|
312
|
+
$data['is_grouped'] = true;
|
|
313
|
+
$data['child_ids'] = $children;
|
|
314
|
+
} else {
|
|
315
|
+
$data['amount'] = $amount;
|
|
316
|
+
$data['price_summary'] = self::get_price_summary( $name, $amount, $recurrence, $variation_id ? $variation_id : $product_id );
|
|
317
|
+
$data['summary_template'] = self::get_price_summary( $name, '{{PRICE}}', $recurrence, $variation_id ? $variation_id : $product_id );
|
|
318
|
+
$data['recurrence'] = $recurrence;
|
|
319
|
+
}
|
|
320
|
+
if ( $variation_id ) {
|
|
321
|
+
$data['variation_id'] = strval( $variation_id );
|
|
322
|
+
}
|
|
323
|
+
|
|
281
324
|
/**
|
|
282
325
|
* Order specific data.
|
|
283
326
|
*/
|
package/newspack-blocks.php
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
* Author URI: https://newspack.com/
|
|
8
8
|
* Text Domain: newspack-blocks
|
|
9
9
|
* Domain Path: /languages
|
|
10
|
-
* Version: 4.16.0-alpha.
|
|
10
|
+
* Version: 4.16.0-alpha.2
|
|
11
11
|
*
|
|
12
12
|
* @package Newspack_Blocks
|
|
13
13
|
*/
|
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
define( 'NEWSPACK_BLOCKS__PLUGIN_FILE', __FILE__ );
|
|
16
16
|
define( 'NEWSPACK_BLOCKS__BLOCKS_DIRECTORY', 'dist/' );
|
|
17
17
|
define( 'NEWSPACK_BLOCKS__PLUGIN_DIR', plugin_dir_path( NEWSPACK_BLOCKS__PLUGIN_FILE ) );
|
|
18
|
-
define( 'NEWSPACK_BLOCKS__VERSION', '4.16.0-alpha.
|
|
18
|
+
define( 'NEWSPACK_BLOCKS__VERSION', '4.16.0-alpha.2' );
|
|
19
19
|
|
|
20
20
|
require_once NEWSPACK_BLOCKS__PLUGIN_DIR . 'includes/class-newspack-blocks.php';
|
|
21
21
|
require_once NEWSPACK_BLOCKS__PLUGIN_DIR . 'includes/class-newspack-blocks-api.php';
|
package/package.json
CHANGED
|
@@ -136,9 +136,6 @@ function render_callback( $attributes ) {
|
|
|
136
136
|
$min_price = \WC_Name_Your_Price_Helpers::get_minimum_price( $product_id );
|
|
137
137
|
}
|
|
138
138
|
|
|
139
|
-
$is_variable = $attributes['is_variable'];
|
|
140
|
-
$variation_id = $attributes['variation'];
|
|
141
|
-
|
|
142
139
|
// Check if the button should be output: it needs a price, or needs to be a product with variations to pick.
|
|
143
140
|
if ( $min_price && ! $price ) {
|
|
144
141
|
$price = $min_price;
|
|
@@ -148,8 +145,6 @@ function render_callback( $attributes ) {
|
|
|
148
145
|
}
|
|
149
146
|
|
|
150
147
|
$checkout_data = Checkout_Data::get_checkout_data( $product );
|
|
151
|
-
$checkout_data['is_variable'] = $is_variable;
|
|
152
|
-
$checkout_data['is_grouped'] = $product->is_type( 'grouped' );
|
|
153
148
|
|
|
154
149
|
$form = sprintf(
|
|
155
150
|
'<form data-checkout="%1$s">%2$s %3$s</form>',
|
|
@@ -15,6 +15,7 @@ export const manageOpened = ( data ) => {
|
|
|
15
15
|
const {
|
|
16
16
|
amount = '',
|
|
17
17
|
is_variable = '',
|
|
18
|
+
is_grouped = '',
|
|
18
19
|
price = '',
|
|
19
20
|
variation_id = '',
|
|
20
21
|
} = data;
|
|
@@ -32,6 +33,9 @@ export const manageOpened = ( data ) => {
|
|
|
32
33
|
if ( is_variable && ! variation_id ) {
|
|
33
34
|
action = 'opened_variations';
|
|
34
35
|
}
|
|
36
|
+
if ( is_grouped ) {
|
|
37
|
+
action = 'opened_grouped';
|
|
38
|
+
}
|
|
35
39
|
|
|
36
40
|
const payload = getEventPayload( action, params );
|
|
37
41
|
|
|
@@ -25,6 +25,10 @@ const eventKeys = [
|
|
|
25
25
|
'product_id',
|
|
26
26
|
'product_type',
|
|
27
27
|
'variation_id',
|
|
28
|
+
'variation_ids',
|
|
29
|
+
'is_variable',
|
|
30
|
+
'is_grouped',
|
|
31
|
+
'child_ids',
|
|
28
32
|
'price_summary',
|
|
29
33
|
'newspack_popup_id',
|
|
30
34
|
'gate_post_id',
|
|
@@ -46,6 +50,14 @@ export const sendEvent = (
|
|
|
46
50
|
const filteredPayload = {};
|
|
47
51
|
for ( const key of eventKeys ) {
|
|
48
52
|
if ( payload[ key ] ) {
|
|
53
|
+
// Normalize boolean values to 'yes' or 'no'.
|
|
54
|
+
if ( typeof payload[ key ] === 'boolean' ) {
|
|
55
|
+
payload[ key ] = payload[ key ] ? 'yes' : 'no';
|
|
56
|
+
} else if ( payload[ key ] === 'true' ) {
|
|
57
|
+
payload[ key ] = 'yes';
|
|
58
|
+
} else if ( payload[ key ] === 'false' ) {
|
|
59
|
+
payload[ key ] = 'no';
|
|
60
|
+
}
|
|
49
61
|
filteredPayload[ key ] = payload[ key ].toString();
|
|
50
62
|
}
|
|
51
63
|
}
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
'name' => 'automattic/newspack-blocks',
|
|
4
4
|
'pretty_version' => 'dev-trunk',
|
|
5
5
|
'version' => 'dev-trunk',
|
|
6
|
-
'reference' => '
|
|
6
|
+
'reference' => '74cf571dbeb5e963f817f9f3cb02ecd117f9ab50',
|
|
7
7
|
'type' => 'wordpress-plugin',
|
|
8
8
|
'install_path' => __DIR__ . '/../../',
|
|
9
9
|
'aliases' => array(),
|
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
'automattic/newspack-blocks' => array(
|
|
14
14
|
'pretty_version' => 'dev-trunk',
|
|
15
15
|
'version' => 'dev-trunk',
|
|
16
|
-
'reference' => '
|
|
16
|
+
'reference' => '74cf571dbeb5e963f817f9f3cb02ecd117f9ab50',
|
|
17
17
|
'type' => 'wordpress-plugin',
|
|
18
18
|
'install_path' => __DIR__ . '/../../',
|
|
19
19
|
'aliases' => array(),
|