@automattic/newspack-blocks 4.11.0 → 4.12.0

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.
Files changed (43) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/dist/block_styles-rtl.css +1 -1
  3. package/dist/block_styles.asset.php +1 -1
  4. package/dist/block_styles.css +1 -1
  5. package/dist/editor-rtl.css +3 -3
  6. package/dist/editor.asset.php +1 -1
  7. package/dist/editor.css +3 -3
  8. package/dist/editor.js +3 -3
  9. package/dist/modal.asset.php +1 -1
  10. package/dist/modal.js +1 -1
  11. package/dist/modalCheckout.asset.php +1 -1
  12. package/dist/modalCheckout.js +1 -1
  13. package/includes/class-modal-checkout.php +61 -25
  14. package/includes/class-newspack-blocks-api.php +3 -48
  15. package/includes/class-newspack-blocks-caching.php +3 -0
  16. package/includes/class-newspack-blocks.php +47 -15
  17. package/includes/tracking/class-data-events.php +34 -7
  18. package/newspack-blocks.php +2 -2
  19. package/package.json +3 -3
  20. package/src/block-styles/core/columns/editor.scss +1 -1
  21. package/src/block-styles/core/columns/view.scss +1 -1
  22. package/src/blocks/carousel/edit.js +5 -10
  23. package/src/blocks/carousel/editor.scss +8 -0
  24. package/src/blocks/homepage-articles/edit.tsx +3 -9
  25. package/src/blocks/homepage-articles/editor.scss +8 -4
  26. package/src/blocks/homepage-articles/utils.ts +7 -8
  27. package/src/blocks/homepage-articles/view.php +10 -2
  28. package/src/modal-checkout/analytics/ga4/checkout-attempt.js +1 -17
  29. package/src/modal-checkout/analytics/ga4/checkout-success.js +17 -0
  30. package/src/modal-checkout/analytics/ga4/dismissed.js +1 -22
  31. package/src/modal-checkout/analytics/ga4/loaded.js +1 -27
  32. package/src/modal-checkout/analytics/ga4/opened.js +1 -26
  33. package/src/modal-checkout/analytics/ga4/pagination.js +16 -1
  34. package/src/modal-checkout/analytics/index.js +2 -1
  35. package/src/modal-checkout/index.js +3 -1
  36. package/src/modal-checkout/modal.js +19 -0
  37. package/src/modal-checkout/templates/thankyou.php +7 -1
  38. package/src/shared/js/utils.js +8 -29
  39. package/src/types/index.d.ts +2 -5
  40. package/vendor/autoload.php +1 -1
  41. package/vendor/composer/autoload_real.php +4 -4
  42. package/vendor/composer/autoload_static.php +2 -2
  43. package/vendor/composer/installed.php +2 -2
@@ -1 +1 @@
1
- <?php return array('dependencies' => array(), 'version' => 'ca25042ae4f3573f9bfc');
1
+ <?php return array('dependencies' => array(), 'version' => 'b5f530bd0370ec7ca0ff');
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=(e,t="np_modal_checkout_interaction")=>{"function"==typeof window.gtag&&e&&window.gtag("event",t,e)},o=e=>{if("function"!=typeof window.gtag)return;let o="opened";const{action_type:c,amount:a="",currency:r,is_variable:i="",price:s="",product_id:l,product_type:d,recurrence:u,referrer:p,variation_id:m=""}=e,_={action_type:c,currency:r,product_id:l,product_type:d,referrer:p};(a||s)&&(_.amount=a||s),i&&(_.is_variable=i),m&&(_.variation_id=m),u&&(_.recurrence=u),i&&!m&&(o="opened_variations");const y=t(o,_);n(y)},c=e=>{if("function"!=typeof window.gtag)return;e=e||(e=>{const t=document.getElementById("newspack_modal_checkout"),n=!!t&&t.getAttribute("data-order-details");return!!n&&JSON.parse(n)||{}})();const{action_type:o,amount:c="",currency:a,price:r="",product_id:i,product_type:s,recurrence:l,referrer:d,variation_id:u=""}=e,p={action_type:o,currency:a,product_id:i,product_type:s,recurrence:l,referrer:d};(c||r)&&(p.amount=c||r),u&&(p.variation_id=u);const m=t("dismissed",p);n(m)};function a(e,t=null){const n=document.createElement("input");return n.type="hidden",n.name=e,t&&(n.value=t),n}const r=newspackBlocksModal.newspack_class_prefix,i="newspack_modal_checkout_iframe",s="newspack_modal_checkout_container",l=`${r}__modal`,d="newspack-blocks__modal-variation";let u={},p=!1;const m=e=>{e.overlayId&&window.newspackReaderActivation?.overlays&&window.newspackReaderActivation?.overlays.remove(e.overlayId),e.setAttribute("data-state","closed"),document.body.style.overflow="auto"};var _;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(`.${l}-container`).forEach((e=>m(e))))},_=()=>{const t=document.querySelector("#newspack_modal_checkout");if(!t)return;const n=t.querySelector(`.${l}__content`),_=a("modal_checkout","1"),y=n.querySelector(`.${r}__spinner`);let w=document.querySelector(".newspack-reader__account-link")?.[0];const h="600px",f=document.createElement("iframe");function k(){const n=f.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=f?.contentDocument?.querySelector(`#${s}`),c=()=>{E.observe(o),"none"!==y.style.display&&(y.style.display="none"),"visible"!==f.style.visibility&&(f.style.visibility="visible"),f._ready=!0};o&&(o.checkoutComplete?(window?.newspackReaderActivation?.refreshNewslettersSignupModal&&window?.newspackReaderActivation?.getReader()?.email&&window.newspackReaderActivation.refreshNewslettersSignupModal(window.newspackReaderActivation.getReader().email),R("small"),L(newspackBlocksModal.labels.thankyou_modal_title),c(),e(t.querySelector(`.${l}`))):(R(),L(newspackBlocksModal.labels.checkout_modal_title),f.contentWindow?.newspackBlocksModalCheckout?.checkout_nonce&&(t.checkout_nonce=f.contentWindow.newspackBlocksModalCheckout.checkout_nonce)),o.checkoutReady?c():o.addEventListener("checkout-ready",c))}f.name=i,f.style.height=h,f.style.visibility="hidden",f.addEventListener("load",k);const g=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)})),v=()=>"undefined"!=typeof newspack_ras_config&&!newspack_ras_config?.is_logged_in&&!window?.newspackReaderActivation?.getReader?.()?.authenticated&&newspackBlocksModal?.is_registration_required&&window?.newspackReaderActivation?.openAuthModal,b=t=>{const n=!newspackBlocksModal.has_unsupported_payment_gateway;n||t.preventDefault();const s=t.target;s.classList.add("modal-processing");const l=s.dataset.product;if(l){const e=JSON.parse(l);Object.keys(e).forEach((t=>{0===s.querySelectorAll('input[name="'+t+'"]').length&&s.appendChild(a(t,e[t]))}))}const _=new FormData(s);_.get("variation_id")||(w=t.submitter);const y=document.querySelectorAll(`.${d}`);if(y.forEach((e=>{(v()||n)&&m(e)})),_.get("is_variable")&&!_.get("variation_id")){const n=[...y].find((e=>e.dataset.productId===_.get("product_id")));if(n){n.querySelectorAll(`form[target="${i}"]`).forEach((e=>{["after_success_behavior","after_success_url","after_success_button_label"].forEach((t=>{0===e.querySelectorAll('input[name="'+t+'"]').length&&e.appendChild(a(t,_.get(t)))}));const t=e.dataset.product;if(t){const n=JSON.parse(t);Object.keys(n).forEach((t=>{0===e.querySelectorAll('input[name="'+t+'"]').length&&e.appendChild(a(t,n[t]))}))}})),t.preventDefault(),s.classList.remove("modal-processing"),$(n),e(n,!1);const c=s.getAttribute("data-product");return u=c?JSON.parse(c):{},p||o(u),void document.getElementById("newspack_modal_checkout").setAttribute("data-order-details",JSON.stringify(u))}}if(!n&&!v())return g(_).then((e=>{window.location.href=e})),void((!_.get("is_variable")||_.get("variation_id"))&&s.querySelectorAll("button[type=submit]:focus").forEach((e=>{e.classList.add("non-modal-checkout-loading");const t=e.innerHTML;e.innerHTML="<span>"+t+"</span>"})));s.classList.remove("modal-processing");const h=_.get("newspack_donate"),f=_.get("newspack_checkout");if(f){const e=s.getAttribute("data-product");u=e?JSON.parse(e):{}}else if(h){const e=_.get("donation_frequency");let t="",n="";for(const n of _.keys())n.indexOf("donation_value_"+e)>=0&&"other"!==_.get(n)&&""!==_.get(n)&&(t=_.get(n));const o=JSON.parse(_.get("frequency_ids"));for(const t in o)t===e&&(n=o[t].toString());u={amount:t,action_type:"donation",currency:_.get("donation_currency"),product_id:n,product_type:"donation",recurrence:e,referrer:_.get("_wp_http_referer")}}if(p||o(u),p=!0,v()){t.preventDefault();let e="",o="0",a="";if(h){const e=_.get("donation_frequency"),t=s.querySelectorAll(`.donation-tier__${e}, .donation-frequency__${e}`);if(t?.length){const n=_.get("donation_tier_index");if(n){const o=JSON.parse(t?.[n].dataset.product);o.hasOwnProperty(`donation_price_summary_${e}`)&&(a=o[`donation_price_summary_${e}`])}else{const n=s.querySelectorAll(`input[name="donation_value_${e}"], input[name="donation_value_${e}_untiered"]`);n?.length&&(n.forEach((e=>{e.checked&&"other"!==e.value&&(o=e.value)})),t.forEach((t=>{const n=JSON.parse(t.dataset.product);if(n.hasOwnProperty(`donation_price_summary_${e}`)){const t=n[`donation_price_summary_${e}`];new RegExp(`(?<=\\D)${o}(?=\\D)`).test(t)&&(a=t)}if("0"===o&&a){let t=_.get(`donation_value_${e}_other`);t||(t=_.get(`donation_value_${e}_untiered`)),t&&(a=a.replace("0",t))}})))}}}else if(f){const e=s.querySelector('input[name="product_price_summary"]');e&&(a=e.value)}a&&(e=`<div class="order-details-summary ${r}__box ${r}__box--text-center"><p><strong>${a}</strong></p></div>`);const i=g(_);i.then((e=>{window.newspackReaderActivation?.setPendingCheckout?.(e)})),window.newspackReaderActivation.openAuthModal({title:newspackBlocksModal.labels.auth_modal_title,onSuccess:(e,t)=>{i.then((e=>{if(t?.registered&&n&&(e+=`&${newspackBlocksModal.checkout_registration_flag}=1`),n){const t=S(e);M(t)}else g(_).then(window.location.href=e)})).catch((e=>{console.warn("Unable to generate cart:",e),A()}))},onError:()=>{A()},onDismiss:()=>{c(u),p=!1,document.getElementById("newspack_modal_checkout").removeAttribute("data-order-details")},skipSuccess:!0,skipNewslettersSignup:!0,labels:{signin:{title:newspackBlocksModal.labels.signin_modal_title},register:{title:newspackBlocksModal.labels.register_modal_title}},content:e,trigger:t.submitter,closeOnSuccess:n})}else q(),document.getElementById("newspack_modal_checkout").setAttribute("data-order-details",JSON.stringify(u))},S=e=>{const t=document.createElement("form");t.method="POST",t.action=e,t.target=i,t.style.display="none";const n=document.createElement("button");return n.setAttribute("type","submit"),t.appendChild(n),document.body.appendChild(t),t.addEventListener("submit",b),t},E=new ResizeObserver((e=>{if(!e||!e.length)return;if(!f.contentDocument)return;const o=e[0].contentRect;if(o){const e=.01*Math.max(document.documentElement.clientHeight,window.innerHeight||0)*90-(t.querySelector(`.${l}__header`)?.offsetHeight||0),c=o.top+o.bottom,a=Math.min(c,e);if(0===a)return void(f.style.visibility="hidden");n.style.height=a+"px",f.style.height=a+"px"}})),A=()=>{const e=f?.contentDocument?.querySelector(`#${s}`),o=e?.querySelector('input[name="after_success_url"]'),a=e?.querySelector('input[name="after_success_behavior"]'),r=document?.querySelector(".newspack-newsletters-signup-modal");e?.checkoutComplete||(()=>{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,fetch(newspackBlocksModal.ajax_url,{method:"POST",body:e})})();const i=!(f.contentDocument&&o&&a&&e?.checkoutComplete);if((i||r)&&(y.style.display="flex",f&&n.contains(f)&&(f._ready=!1,f.src="about:blank",f.style.height=h,f.style.visibility="hidden",n.style.height=h,n.removeChild(f)),E&&E.disconnect(),document.querySelectorAll(`.${l}-container`).forEach((e=>m(e))),w&&w.focus()),e?.checkoutComplete){const e=()=>{if(o&&a){const e=o.getAttribute("value"),t=a.getAttribute("value");"custom"===t?window.location.href=e:"referrer"===t&&window.history.back()}window?.newspackReaderActivation?.setPendingCheckout?.(),p=!1};window?.newspackReaderActivation?.openNewslettersSignupModal?window.newspackReaderActivation.openNewslettersSignupModal({onSuccess:e,onError:e,closeOnSuccess:i}):e(),i&&(R(),L(newspackBlocksModal.labels.checkout_modal_title))}else window?.newspackReaderActivation?.setPendingCheckout?.(),c(),p=!1,document.getElementById("newspack_modal_checkout").removeAttribute("data-order-details")},q=()=>{y.style.display="flex",$(t),n.appendChild(f),t.addEventListener("click",(e=>{e.target===t&&A()})),e(t,f),function(e){f._readyTimer&&clearTimeout(f._readyTimer);let t=!1;function n(){t||(t=!0,clearTimeout(f._readyTimer),e.call(this))}function o(){"complete"===this.readyState&&n.call(this)}!function e(){if(f._ready)return void clearTimeout(f._readyTimer);const t=f.contentDocument||f.contentWindow?.document;t&&0!==t.URL.indexOf("about:")?"complete"===t?.readyState?n.call(t):(t.addEventListener("DOMContentLoaded",n),t.addEventListener("readystatechange",o)):f._readyTimer=setTimeout(e,10)}()}(k)},$=e=>{window.newspackReaderActivation?.overlays&&(e.overlayId=window.newspackReaderActivation?.overlays.add()),e.setAttribute("data-state","open"),document.body.style.overflow="hidden"},L=e=>{const n=t.querySelector(`.${l}__header h2`);n&&(n.innerText=e)},R=(e="default")=>{const n=t.querySelector(`.${l}`);n&&("small"===e?n.classList.add(`${l}--small`):n.classList.remove(`${l}--small`))};window.newspackCloseModalCheckout=A,t.querySelectorAll(`.${l}__close`).forEach((e=>{e.addEventListener("click",(e=>{e.preventDefault(),A()}))})),document.querySelectorAll(".newspack-blocks__modal-variation").forEach((e=>{e.addEventListener("click",(t=>{t.target===e&&A()})),e.querySelectorAll(`.${l}__close`).forEach((e=>{e.addEventListener("click",(e=>{e.preventDefault(),A()}))}))})),document.addEventListener("keydown",(function(e){"Escape"===e.key&&A()})),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.appendChild(_.cloneNode()),e.target=i,e.addEventListener("submit",b)}))}));const M=e=>{e.requestSubmit(e.querySelector('button[type="submit"]'))};(()=>{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 i="untiered"===e?a.querySelector(`input[name="donation_value_${t}_untiered"]`):a.querySelector(`input[name="donation_value_${t}"][value="${n}"]`);if(r&&i){if(r.checked=!0,"untiered"===e)i.value=n;else if("other"===n){i.click();const e=a.querySelector(`input[name="donation_value_${t}_other"]`);e&&o&&(e.value=o)}else i.checked=!0;c=a}}})),c&&M(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(`.${d}`)].find((t=>t.dataset.productId===e));o&&o.querySelectorAll(`form[target="${i}"]`).forEach((e=>{const o=JSON.parse(e.dataset.product);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.product);c?.product_id===e&&(n=o)}));n&&M(n)})(t,n)}else{const e=window.newspackReaderActivation?.getPendingCheckout?.();if(e){const t=S(e);M(t)}}window.history.replaceState(null,null,window.location.pathname)})()},"undefined"!=typeof document&&("complete"!==document.readyState&&"interactive"!==document.readyState?document.addEventListener("DOMContentLoaded",_):_())})();
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=(e,t="np_modal_checkout_interaction")=>{"function"==typeof window.gtag&&e&&window.gtag("event",t,e)},o=e=>{const t=document.getElementById(e),n=!!t&&t.getAttribute("data-order-details");return!!n&&JSON.parse(n)||{}},c=e=>{if("function"!=typeof window.gtag)return;let o="opened";const{amount:c="",is_variable:a="",price:r="",variation_id:i=""}=e,s={...e};(c||r)&&(s.amount=c||r),a&&!i&&(o="opened_variations");const l=t(o,s);n(l)},a=e=>{if("function"!=typeof window.gtag)return;e=e||o("newspack_modal_checkout");const c=t("dismissed",e);n(c)};function r(e,t=null){const n=document.createElement("input");return n.type="hidden",n.name=e,t&&(n.value=t),n}const i=newspackBlocksModal.newspack_class_prefix,s="newspack_modal_checkout_iframe",l="newspack_modal_checkout_container",d="newspack_modal_checkout",u=`${i}__modal`,p="newspack-blocks__modal-variation";let m={},_=!1;const w=e=>{e.overlayId&&window.newspackReaderActivation?.overlays&&window.newspackReaderActivation?.overlays.remove(e.overlayId),e.setAttribute("data-state","closed"),document.body.style.overflow="auto"};var h;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(`.${u}-container`).forEach((e=>w(e))))},h=()=>{const t=document.querySelector(`#${d}`);if(!t)return;const n=t.querySelector(`.${u}__content`),h=r("modal_checkout","1"),y=n.querySelector(`.${i}__spinner`);let f=document.querySelector(".newspack-reader__account-link")?.[0];const k="600px",g=document.createElement("iframe");function v(){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 c=g?.contentDocument?.querySelector(`#${l}`),a=()=>{q.observe(c),"none"!==y.style.display&&(y.style.display="none"),"visible"!==g.style.visibility&&(g.style.visibility="visible"),g._ready=!0};if(c){if(c.checkoutComplete){const n=o(d);window.newspackRAS=window.newspackRAS||[],window.newspackRAS.push((function(e){e.dispatchActivity("checkout_completed",n)})),window?.newspackReaderActivation?.refreshNewslettersSignupModal&&window?.newspackReaderActivation?.getReader()?.email&&window.newspackReaderActivation.refreshNewslettersSignupModal(window.newspackReaderActivation.getReader().email),B("small"),M(newspackBlocksModal.labels.thankyou_modal_title),a(),e(t.querySelector(`.${u}`))}else B(),M(newspackBlocksModal.labels.checkout_modal_title),g.contentWindow?.newspackBlocksModalCheckout?.checkout_nonce&&(t.checkout_nonce=g.contentWindow.newspackBlocksModalCheckout.checkout_nonce);c.checkoutReady?a():c.addEventListener("checkout-ready",a)}}g.name=s,g.style.height=k,g.style.visibility="hidden",g.addEventListener("load",v);const b=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)})),S=()=>"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 l=o.dataset.product;if(l){const e=JSON.parse(l);Object.keys(e).forEach((t=>{0===o.querySelectorAll('input[name="'+t+'"]').length&&o.appendChild(r(t,e[t]))}))}const d=new FormData(o);d.get("variation_id")||(f=t.submitter);const u=document.querySelectorAll(`.${p}`);if(u.forEach((e=>{(S()||n)&&w(e)})),d.get("is_variable")&&!d.get("variation_id")){const n=[...u].find((e=>e.dataset.productId===d.get("product_id")));if(n){n.querySelectorAll(`form[target="${s}"]`).forEach((e=>{["after_success_behavior","after_success_url","after_success_button_label"].forEach((t=>{0===e.querySelectorAll('input[name="'+t+'"]').length&&e.appendChild(r(t,d.get(t)))}));const t=e.dataset.product;if(t){const n=JSON.parse(t);Object.keys(n).forEach((t=>{0===e.querySelectorAll('input[name="'+t+'"]').length&&e.appendChild(r(t,n[t]))}))}})),t.preventDefault(),o.classList.remove("modal-processing"),L(n),e(n,!1);const a=o.getAttribute("data-product");return m=a?JSON.parse(a):{},_||c(m),void document.getElementById("newspack_modal_checkout").setAttribute("data-order-details",JSON.stringify(m))}}if(!n&&!S())return b(d).then((e=>{window.location.href=e})),void((!d.get("is_variable")||d.get("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>"})));o.classList.remove("modal-processing");const h=d.get("newspack_donate"),y=d.get("newspack_checkout");if(y){const e=o.getAttribute("data-product");m=e?JSON.parse(e):{}}else if(h){const e=d.get("donation_frequency");let t="",n="";for(const n of d.keys())n.indexOf("donation_value_"+e)>=0&&"other"!==d.get(n)&&""!==d.get(n)&&(t=d.get(n));const o=JSON.parse(d.get("frequency_ids"));for(const t in o)t===e&&(n=o[t].toString());m={amount:t,action_type:"donation",currency:d.get("donation_currency"),product_id:n,product_type:"donation",recurrence:e,referrer:d.get("_wp_http_referer")}}const k=d.get("memberships_content_gate");k&&(m.gate_post_id=k);const g=d.get("newspack_popup_id");if(g&&(m.newspack_popup_id=g),_||c(m),_=!0,S()){t.preventDefault();let e="",c="0",r="";if(h){const e=d.get("donation_frequency"),t=o.querySelectorAll(`.donation-tier__${e}, .donation-frequency__${e}`);if(t?.length){const n=d.get("donation_tier_index");if(n){const o=JSON.parse(t?.[n].dataset.product);o.hasOwnProperty(`donation_price_summary_${e}`)&&(r=o[`donation_price_summary_${e}`])}else{const n=o.querySelectorAll(`input[name="donation_value_${e}"], input[name="donation_value_${e}_untiered"]`);n?.length&&(n.forEach((e=>{e.checked&&"other"!==e.value&&(c=e.value)})),t.forEach((t=>{const n=JSON.parse(t.dataset.product);if(n.hasOwnProperty(`donation_price_summary_${e}`)){const t=n[`donation_price_summary_${e}`];new RegExp(`(?<=\\D)${c}(?=\\D)`).test(t)&&(r=t)}if("0"===c&&r){let t=d.get(`donation_value_${e}_other`);t||(t=d.get(`donation_value_${e}_untiered`)),t&&(r=r.replace("0",t))}})))}}}else if(y){const e=o.querySelector('input[name="product_price_summary"]');e&&(r=e.value)}r&&(e=`<div class="order-details-summary ${i}__box ${i}__box--text-center"><p><strong>${r}</strong></p></div>`);const s=b(d);s.then((e=>{window.newspackReaderActivation?.setPendingCheckout?.(e)})),window.newspackReaderActivation.openAuthModal({title:newspackBlocksModal.labels.auth_modal_title,onSuccess:(e,t)=>{s.then((e=>{if(t?.registered&&n&&(e+=`&${newspackBlocksModal.checkout_registration_flag}=1`),n){const t=E(e);O(t)}else b(d).then(window.location.href=e)})).catch((e=>{console.warn("Unable to generate cart:",e),$()}))},onError:()=>{$()},onDismiss:()=>{a(m),_=!1,document.getElementById("newspack_modal_checkout").removeAttribute("data-order-details")},skipSuccess:!0,skipNewslettersSignup:!0,labels:{signin:{title:newspackBlocksModal.labels.signin_modal_title},register:{title:newspackBlocksModal.labels.register_modal_title}},content:e,trigger:t.submitter,closeOnSuccess:n})}else R(),document.getElementById("newspack_modal_checkout").setAttribute("data-order-details",JSON.stringify(m))},E=e=>{const t=document.createElement("form");t.method="POST",t.action=e,t.target=s,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},q=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(`.${u}__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"}})),$=()=>{const e=g?.contentDocument?.querySelector(`#${l}`),o=e?.querySelector('input[name="after_success_url"]'),c=e?.querySelector('input[name="after_success_behavior"]'),r=document?.querySelector(".newspack-newsletters-signup-modal");e?.checkoutComplete||(()=>{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,fetch(newspackBlocksModal.ajax_url,{method:"POST",body:e})})();const i=!(g.contentDocument&&o&&c&&e?.checkoutComplete);if((i||r)&&(y.style.display="flex",g&&n.contains(g)&&(g._ready=!1,g.src="about:blank",g.style.height=k,g.style.visibility="hidden",n.style.height=k,n.removeChild(g)),q&&q.disconnect(),document.querySelectorAll(`.${u}-container`).forEach((e=>w(e))),f&&f.focus()),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:i}):e(),i&&(B(),M(newspackBlocksModal.labels.checkout_modal_title))}else window?.newspackReaderActivation?.setPendingCheckout?.(),a(),_=!1,document.getElementById("newspack_modal_checkout").removeAttribute("data-order-details")},R=()=>{y.style.display="flex",L(t),n.appendChild(g),t.addEventListener("click",(e=>{e.target===t&&$()})),e(t,g),function(e){g._readyTimer&&clearTimeout(g._readyTimer);let t=!1;function n(){t||(t=!0,clearTimeout(g._readyTimer),e.call(this))}function o(){"complete"===this.readyState&&n.call(this)}!function e(){if(g._ready)return void clearTimeout(g._readyTimer);const t=g.contentDocument||g.contentWindow?.document;t&&0!==t.URL.indexOf("about:")?"complete"===t?.readyState?n.call(t):(t.addEventListener("DOMContentLoaded",n),t.addEventListener("readystatechange",o)):g._readyTimer=setTimeout(e,10)}()}(v)},L=e=>{window.newspackReaderActivation?.overlays&&(e.overlayId=window.newspackReaderActivation?.overlays.add()),e.setAttribute("data-state","open"),document.body.style.overflow="hidden"},M=e=>{const n=t.querySelector(`.${u}__header h2`);n&&(n.innerText=e)},B=(e="default")=>{const n=t.querySelector(`.${u}`);n&&("small"===e?n.classList.add(`${u}--small`):n.classList.remove(`${u}--small`))};window.newspackCloseModalCheckout=$,t.querySelectorAll(`.${u}__close`).forEach((e=>{e.addEventListener("click",(e=>{e.preventDefault(),$()}))})),document.querySelectorAll(".newspack-blocks__modal-variation").forEach((e=>{e.addEventListener("click",(t=>{t.target===e&&$()})),e.querySelectorAll(`.${u}__close`).forEach((e=>{e.addEventListener("click",(e=>{e.preventDefault(),$()}))}))})),document.addEventListener("keydown",(function(e){"Escape"===e.key&&$()})),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.appendChild(h.cloneNode()),e.target=s,e.addEventListener("submit",A)}))}));const O=e=>{e.requestSubmit(e.querySelector('button[type="submit"]'))};(()=>{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 i="untiered"===e?a.querySelector(`input[name="donation_value_${t}_untiered"]`):a.querySelector(`input[name="donation_value_${t}"][value="${n}"]`);if(r&&i){if(r.checked=!0,"untiered"===e)i.value=n;else if("other"===n){i.click();const e=a.querySelector(`input[name="donation_value_${t}_other"]`);e&&o&&(e.value=o)}else i.checked=!0;c=a}}})),c&&O(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="${s}"]`).forEach((e=>{const o=JSON.parse(e.dataset.product);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.product);c?.product_id===e&&(n=o)}));n&&O(n)})(t,n)}else{const e=window.newspackReaderActivation?.getPendingCheckout?.();if(e){const t=E(e);O(t)}}window.history.replaceState(null,null,window.location.pathname)})()},"undefined"!=typeof document&&("complete"!==document.readyState&&"interactive"!==document.readyState?document.addEventListener("DOMContentLoaded",h):h())})();
@@ -1 +1 @@
1
- <?php return array('dependencies' => array(), 'version' => 'e30e3b91b298c26dec0a');
1
+ <?php return array('dependencies' => array(), 'version' => 'f994d978f4aa233ad919');
@@ -1 +1 @@
1
- (()=>{"use strict";const e=(e,t={})=>({...t,action:e}),t=(e,t="np_modal_checkout_interaction")=>{"function"==typeof window.gtag&&e&&window.gtag("event",t,e)},o=e=>{const t=document.getElementById(e),o=!!t&&t.getAttribute("data-order-details");return!!o&&JSON.parse(o)||{}};function c(e){"undefined"!=typeof document&&"function"==typeof e&&("complete"!==document.readyState&&"interactive"!==document.readyState?document.addEventListener("DOMContentLoaded",e):e())}const n=(c="continue")=>{if("function"!=typeof window.gtag)return;const{action_type:n,amount:i,currency:r,product_id:a,product_type:s,recurrence:d,referrer:u,variation_id:l=""}=o("modal-checkout-product-details"),p={action_type:n,amount:i,currency:r,product_id:a,product_type:s,recurrence:d,referrer:u};l&&(p.variation_id=l);const _=e(c,p);t(_)};var i;i=jQuery,c((()=>{if(!i)return void console.warn("jQuery is not available.");const r=newspackBlocksModalCheckout.newspack_class_prefix,a=new CustomEvent("checkout-ready");function s(){i(`.woocommerce-NoticeGroup-checkout, .${r}__inline-error, .woocommerce-error, .woocommerce-message, .wc-block-components-notice-banner, .woocommerce-notices-wrapper`).remove()}function d(n=!0){const i=document.querySelector("#newspack_modal_checkout_container");i.checkoutReady=!0,i.dispatchEvent(a),n&&c((function(){if("function"!=typeof window.gtag)return;const{action_type:c,amount:n,currency:i,product_id:r,product_type:a,recurrence:s,referrer:d,variation_id:u=""}=o("modal-checkout-product-details"),l={action_type:c,amount:n,currency:i,product_id:r,product_type:a,recurrence:s,referrer:d};u&&(l.variation_id=u);const p=e("loaded",l);t(p)}))}if(newspackBlocksModalCheckout.is_checkout_complete){const l=document.querySelector("#newspack_modal_checkout_container");l&&(l.checkoutComplete=!0)}else{function p(){i("#wcpay-express-checkout-button-separator, #wc-stripe-payment-request-button-separator").after('<div class="newspack-ui__word-divider">'+newspackBlocksModalCheckout.divider_text+"</div>");let c=[];const a=i("form.checkout");if(!a.length)return void console.warn("Form is not available");const l=i("form.modal_checkout_coupon"),p=i("form.modal_checkout_nyp"),_=i("#checkout_continue"),m=i("#customer_details"),h=i("#after_customer_details"),f=i(".newspack-wcsg--wrapper");function g(){const e=i('input[name="payment_method"]:checked').val();i(".wc_payment_method").removeClass("selected"),i(".wc_payment_method.payment_method_"+e).addClass("selected")}function k(){let e;if(i.ajax({url:newspackBlocksModalCheckout.ajax_url,method:"POST",async:!1,data:{action:"get_cart_total"},success:t=>{e=t}}),e)return e}if(i('input[name="payment_method"]').change(g),i(document).on("payment_method_selected",g),i(document).on("updated_checkout",g),g(),i(document).on("updated_checkout",(function(){i("#payment .wc_payment_methods").length?i("#after_customer_details > h3").show():i("#after_customer_details > h3").hide()})),i(document).on("updated_checkout",(function(){const e=i("#after_customer_details > .order-review-wrapper");if(!e.length)return;const t=e.clone();i("#after_customer_details").hasClass("transaction-details-expanded")&&i('[id="order_review_heading"]',t).attr("aria-expanded","true"),i("#payment .order-review-wrapper").remove();const o=t.find("table");o.is(".empty")?t.addClass("hidden"):(o.unblock(),t.removeClass("hidden")),i(".payment_methods").after(t)})),i(document).on("click","#order_review_heading",(function(){i(this).attr("aria-expanded",(function(e,t){return"false"===t?"true":"false"})),i("#after_customer_details").toggleClass("transaction-details-expanded")})),i(document).on("updated_checkout",(function(){let e=newspackBlocksModalCheckout.labels.complete_button;if(e){if(i("#place_order").has(i("span.cart-price"))){const t=i("<div>"+e+"</div>");t.find(".cart-price").html(k,(function(){return this.childNodes})),e=t.html()}i("#place_order").html(e),i("#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){a.find(".input-text, select, input:checkbox").trigger("validate").trigger("blur");let t=!1;const o=[],c=e=>{const c=i("#"+e.data("id")+"_field");if(c?.length){t||(t=c);const o=c.find(".woocommerce-error");o.length&&o.remove(),c.addClass("woocommerce-invalid").removeClass("woocommerce-valid"),c.append(`<span class="${r}__inline-error">`+e.text()+"</span>"),e.remove()}else e.is("li")||(e=i("<li />").append(e)),o.push(e)};if(s(),0!==e.trimStart().indexOf("<")?c(i("<li />").append(e)):e.includes("<li")?i(e).find("li").each((function(){c(i(this))})):c(i(e)),o.length){t=!1;const e=i('<div class="woocommerce-NoticeGroup woocommerce-NoticeGroup-checkout"/>').append(i('<ul class="woocommerce-error" role="alert" />').append(o));a.prepend(e),e.get(0).scrollIntoView({behavior:"smooth"})}t?.length&&(window.scroll({top:t.offset().top-100,left:0,behavior:"smooth"}),t.find("input.input-text, select, input:checkbox").trigger("focus")),x(a),i(document.body).trigger("update_checkout"),i(document.body).trigger("checkout_error",[e])}function y(e){e.preventDefault(),e.stopImmediatePropagation(),b(),n("continue")}function v(e){const t=window.newspack_grecaptcha||{};if(s(),i("#checkout_details").remove(),e)a.attr("data-skip-recaptcha","1"),a.append('<input name="is_validation_only" type="hidden" value="1" />'),"v3"===t?.version&&t.destroy(a.get()),l.length&&l.hide(),p.length&&p.hide(),m.show(),h.hide(),m.find("input").first().focus(),c=function(e,t){const o=i._data(e,"events");return o?t?i._data(e,"events")[t]:o:[]}(a[0],"submit").slice(0),c.forEach((e=>{a.off("submit",e.handler)})),a.on("submit",y);else{a.removeAttr("data-skip-recaptcha");const e=a.find('[name="is_validation_only"]');if(e.length&&e.remove(),t?.render){a.data("newspack-recaptcha","newspack_modal_checkout");const e=()=>{s(),a.get(0).scrollIntoView({behavior:"smooth"})},o=e=>w(e);t.render(a.get(),e,o),i(document).on("updated_checkout",(()=>t.render(a.get(),e,o))),i(document.body).on("checkout_error",(()=>t.render(a.get(),e,o)))}l.length&&l.show(),p.length&&p.show(),m.hide(),h.show(),function(){i("#checkout_details").remove();const e={};a.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>")),i(".order-details-summary").after('<div id="checkout_details">'+o.join("")+"</div>")}(),a.off("submit",y),c.forEach((e=>{a.on("submit",e.handler)})),u()}a.triggerHandler("editing_details",[e]),window.scroll({top:0,left:0,behavior:"smooth"})}function b(e=!1,t=(()=>{})){if(!C(a))return console.warn("Unable to block the form"),t(),!1;s();const o=a.find(".woocommerce-NoticeGroup.woocommerce-NoticeGroup-checkout");o.length&&o.remove();const c=["save_user_in_woopay"],d=a.serializeArray().filter((e=>!c.includes(e.name)));d.push({name:"woocommerce_checkout_update_totals",value:"1"}),i.ajax({type:"POST",url:wc_checkout_params.checkout_url,data:d,dataType:"html",success:o=>{let c;try{c=JSON.parse(o)}catch(e){c={messages:'<div class="woocommerce-error">'+wc_checkout_params.i18n_checkout_error+"</div>"}}e||!0!==c.reload?(x(a),c.messages?e||(c.messages?w(c.messages):w(`<div class="${r}__inline-error">`+wc_checkout_params.i18n_checkout_error+"</div>")):(v(!1),i._data(a[0],"events")?.click?.some((e=>"#checkout_back"===e.selector))||a.on("click","#checkout_back",(function(e){e.preventDefault(),v(!0),n("back")}))),t(c)):window.location.reload()},error:(o,c,n)=>{let i="";e||(i='<div class="woocommerce-error">'+(n||wc_checkout_params.i18n_checkout_error)+"</div>",w(i)),t({messages:i})}})}function C(e){return!e.is(".modal-processing")&&(e.find("button[type=submit]").each(((e,t)=>{i(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)=>{i(t).attr("disabled",!1)})),e.removeClass("modal-processing"),!0)}_.length?(v(!0),f.length?d():b(!0,d)):d(),l.length&&(l.on("submit",(function(e){if(e.preventDefault(),!C(l))return!1;const t={security:wc_checkout_params.apply_coupon_nonce,coupon_code:l.find('input[name="coupon_code"]').val()};i.ajax({type:"POST",url:wc_checkout_params.wc_ajax_url.toString().replace("%%endpoint%%","apply_coupon"),data:t,dataType:"html",success:e=>{if(s(),l.find(".result").remove(),e){const o=e.includes("error");l.append(`<p class="result ${r}__helper-text ${o?r+"__inline-error":""}">`+i(e).text()+"</p>"),o?(l.find('input[name="coupon_code"]').focus(),l.find('h3, input[name="coupon_code"]').addClass("newspack-ui__field-error")):(l.find('input[name="coupon_code"]').focus(),l.find('h3, input[name="coupon_code"]').removeClass("newspack-ui__field-error")),i(document.body).trigger("applied_coupon_in_checkout",[t.coupon_code]),i(document.body).trigger("update_checkout",{update_shipping_method:!1})}},complete:()=>{x(l)}})})),i(document.body).on("removed_coupon_in_checkout",(()=>{s(),l.find(".result").remove(),l.find('input[name="coupon_code"]').val("").focus()}))),p.length&&p.on("submit",(function(e){if(e.preventDefault(),!C(p))return!1;const t=p.find('input[name="price"]');t.attr("disabled",!0);const o={_ajax_nonce:newspackBlocksModalCheckout.nyp_nonce,action:"process_name_your_price_request",price:p.find('input[name="price"]').val(),product_id:p.find('input[name="product_id"]').val(),newspack_checkout_name_your_price:p.find('input[name="newspack_checkout_name_your_price"]').val()};i.ajax({type:"POST",url:newspackBlocksModalCheckout.ajax_url,data:o,success:({success:e,data:t})=>{s(),p.find(".result").remove(),p.append(`<p class="result ${r}__helper-text ${e?"":r+"__inline-error"}">`+t.message+"</p>"),e?p.find('h3, input[name="price"]').removeClass("newspack-ui__field-error"):(p.find('input[name="price"]').focus(),p.find('h3, input[name="price"]').addClass("newspack-ui__field-error")),i(document.body).trigger("update_checkout",{update_shipping_method:!1})},complete:()=>{x(p),t.attr("disabled",!1),t.focus()}})})),a.on("click","#place_order",(function(){(()=>{if("function"!=typeof window.gtag)return;const{action_type:c,amount:n,currency:i,product_id:r,product_type:a,recurrence:s,referrer:d,variation_id:u=""}=o("modal-checkout-product-details"),l={action_type:c,amount:n,currency:i,product_id:r,product_type:a,recurrence:s,referrer:d};u&&(l.variation_id=u);const p=e("form_submission",l);t(p)})()}))}p()}function u(){const e=i("#newspack_subscription_terms_confirmation, #newspack_subscription_confirmation");if(e.length){const t=i("form.checkout"),o=t.find("button#place_order, button#place_order_clone");function c(){const t=e.is(":checked");o.each(((e,o)=>{i(o).attr("disabled",!t)}))}c(),e.on("change",c),t.on("submit",(function(t){if(!e.is(":checked"))return t.preventDefault(),t.stopPropagation(),!1}))}}i(document.body).on("updated_checkout payment_method_selected checkout_error",u),i(document).ready(u),i(document.body).on("checkout_error",(function(){const e=i(".woocommerce-NoticeGroup-checkout, .woocommerce-notices-wrapper");e.length&&e.each(((e,t)=>i(t).addClass(`${r}__notice ${r}__notice--error`)));const t=i("#checkout_error_back");t.length&&t.on("click",(e=>{e.preventDefault(),parent.newspackCloseModalCheckout()})),d(!1)})),document.addEventListener("keydown",(function(e){"Escape"===e.key&&parent.newspackCloseModalCheckout()})),newspackBlocksModalCheckout.is_error&&i(document.body).trigger("checkout_error")}))})();
1
+ (()=>{"use strict";const e=(e,t={})=>({...t,action:e}),t=(e,t="np_modal_checkout_interaction")=>{"function"==typeof window.gtag&&e&&window.gtag("event",t,e)},o=e=>{const t=document.getElementById(e),o=!!t&&t.getAttribute("data-order-details");return!!o&&JSON.parse(o)||{}};function c(e){"undefined"!=typeof document&&"function"==typeof e&&("complete"!==document.readyState&&"interactive"!==document.readyState?document.addEventListener("DOMContentLoaded",e):e())}const n=(c="continue")=>{if("function"!=typeof window.gtag)return;const{action_type:n,amount:i,currency:a,product_id:s,product_type:r,recurrence:d,referrer:l,variation_id:u="",gate_post_id:p=""}=o("modal-checkout-product-details"),_={action_type:n,amount:i,currency:a,product_id:s,product_type:r,recurrence:d,referrer:l};u&&(_.variation_id=u),p&&(_.gate_post_id=p);const m=e(c,_);t(m)};var i;i=jQuery,c((()=>{if(!i)return void console.warn("jQuery is not available.");const a=newspackBlocksModalCheckout.newspack_class_prefix,s=new CustomEvent("checkout-ready");function r(){i(`.woocommerce-NoticeGroup-checkout, .${a}__inline-error, .woocommerce-error, .woocommerce-message, .wc-block-components-notice-banner, .woocommerce-notices-wrapper`).remove()}function d(n=!0){const i=document.querySelector("#newspack_modal_checkout_container");i.checkoutReady=!0,i.dispatchEvent(s),n&&c((function(){if("function"!=typeof window.gtag)return;const c=o("modal-checkout-product-details"),n=e("loaded",c);t(n)}))}if(newspackBlocksModalCheckout.is_checkout_complete){(()=>{if("function"!=typeof window.gtag)return;const c=o("modal-checkout-product-details"),n=e("form_submission_success",c);t(n)})();const u=document.querySelector("#newspack_modal_checkout_container");u&&(u.checkoutComplete=!0)}else{function p(){i("#wcpay-express-checkout-button-separator, #wc-stripe-payment-request-button-separator").after('<div class="newspack-ui__word-divider">'+newspackBlocksModalCheckout.divider_text+"</div>");let c=[];const s=i("form.checkout");if(!s.length)return void console.warn("Form is not available");const u=i("form.modal_checkout_coupon"),p=i("form.modal_checkout_nyp"),_=i("#checkout_continue"),m=i("#customer_details"),h=i("#after_customer_details"),f=i(".newspack-wcsg--wrapper");function g(){const e=i('input[name="payment_method"]:checked').val();i(".wc_payment_method").removeClass("selected"),i(".wc_payment_method.payment_method_"+e).addClass("selected")}function k(){let e;if(i.ajax({url:newspackBlocksModalCheckout.ajax_url,method:"POST",async:!1,data:{action:"get_cart_total"},success:t=>{e=t}}),e)return e}if(i('input[name="payment_method"]').change(g),i(document).on("payment_method_selected",g),i(document).on("updated_checkout",g),g(),i(document).on("updated_checkout",(function(){i("#payment .wc_payment_methods").length?i("#after_customer_details > h3").show():i("#after_customer_details > h3").hide()})),i(document).on("updated_checkout",(function(){const e=i("#after_customer_details > .order-review-wrapper");if(!e.length)return;const t=e.clone();i("#after_customer_details").hasClass("transaction-details-expanded")&&i('[id="order_review_heading"]',t).attr("aria-expanded","true"),i("#payment .order-review-wrapper").remove();const o=t.find("table");o.is(".empty")?t.addClass("hidden"):(o.unblock(),t.removeClass("hidden")),i(".payment_methods").after(t)})),i(document).on("click","#order_review_heading",(function(){i(this).attr("aria-expanded",(function(e,t){return"false"===t?"true":"false"})),i("#after_customer_details").toggleClass("transaction-details-expanded")})),i(document).on("updated_checkout",(function(){let e=newspackBlocksModalCheckout.labels.complete_button;if(e){if(i("#place_order").has(i("span.cart-price"))){const t=i("<div>"+e+"</div>");t.find(".cart-price").html(k,(function(){return this.childNodes})),e=t.html()}i("#place_order").html(e),i("#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){s.find(".input-text, select, input:checkbox").trigger("validate").trigger("blur");let t=!1;const o=[],c=e=>{const c=i("#"+e.data("id")+"_field");if(c?.length){t||(t=c);const o=c.find(".woocommerce-error");o.length&&o.remove(),c.addClass("woocommerce-invalid").removeClass("woocommerce-valid"),c.append(`<span class="${a}__inline-error">`+e.text()+"</span>"),e.remove()}else e.is("li")||(e=i("<li />").append(e)),o.push(e)};if(r(),0!==e.trimStart().indexOf("<")?c(i("<li />").append(e)):e.includes("<li")?i(e).find("li").each((function(){c(i(this))})):c(i(e)),o.length){t=!1;const e=i('<div class="woocommerce-NoticeGroup woocommerce-NoticeGroup-checkout"/>').append(i('<ul class="woocommerce-error" role="alert" />').append(o));s.prepend(e),e.get(0).scrollIntoView({behavior:"smooth"})}t?.length&&(window.scroll({top:t.offset().top-100,left:0,behavior:"smooth"}),t.find("input.input-text, select, input:checkbox").trigger("focus")),x(s),i(document.body).trigger("update_checkout"),i(document.body).trigger("checkout_error",[e])}function b(e){e.preventDefault(),e.stopImmediatePropagation(),y(),n("continue")}function v(e){const t=window.newspack_grecaptcha||{};if(r(),i("#checkout_details").remove(),e)s.attr("data-skip-recaptcha","1"),s.append('<input name="is_validation_only" type="hidden" value="1" />'),"v3"===t?.version&&t.destroy(s.get()),u.length&&u.hide(),p.length&&p.hide(),m.show(),h.hide(),m.find("input").first().focus(),c=function(e,t){const o=i._data(e,"events");return o?t?i._data(e,"events")[t]:o:[]}(s[0],"submit").slice(0),c.forEach((e=>{s.off("submit",e.handler)})),s.on("submit",b);else{s.removeAttr("data-skip-recaptcha");const e=s.find('[name="is_validation_only"]');if(e.length&&e.remove(),t?.render){s.data("newspack-recaptcha","newspack_modal_checkout");const e=()=>{r(),s.get(0).scrollIntoView({behavior:"smooth"})},o=e=>w(e);t.render(s.get(),e,o),i(document).on("updated_checkout",(()=>t.render(s.get(),e,o))),i(document.body).on("checkout_error",(()=>t.render(s.get(),e,o)))}u.length&&u.show(),p.length&&p.show(),m.hide(),h.show(),function(){i("#checkout_details").remove();const e={};s.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>")),i(".order-details-summary").after('<div id="checkout_details">'+o.join("")+"</div>")}(),s.off("submit",b),c.forEach((e=>{s.on("submit",e.handler)})),l()}s.triggerHandler("editing_details",[e]),window.scroll({top:0,left:0,behavior:"smooth"})}function y(e=!1,t=(()=>{})){if(!C(s))return console.warn("Unable to block the form"),t(),!1;r();const o=s.find(".woocommerce-NoticeGroup.woocommerce-NoticeGroup-checkout");o.length&&o.remove();const c=["save_user_in_woopay"],d=s.serializeArray().filter((e=>!c.includes(e.name)));d.push({name:"woocommerce_checkout_update_totals",value:"1"}),i.ajax({type:"POST",url:wc_checkout_params.checkout_url,data:d,dataType:"html",success:o=>{let c;try{c=JSON.parse(o)}catch(e){c={messages:'<div class="woocommerce-error">'+wc_checkout_params.i18n_checkout_error+"</div>"}}e||!0!==c.reload?(x(s),c.messages?e||(c.messages?w(c.messages):w(`<div class="${a}__inline-error">`+wc_checkout_params.i18n_checkout_error+"</div>")):(v(!1),i._data(s[0],"events")?.click?.some((e=>"#checkout_back"===e.selector))||s.on("click","#checkout_back",(function(e){e.preventDefault(),v(!0),n("back")}))),t(c)):window.location.reload()},error:(o,c,n)=>{let i="";e||(i='<div class="woocommerce-error">'+(n||wc_checkout_params.i18n_checkout_error)+"</div>",w(i)),t({messages:i})}})}function C(e){return!e.is(".modal-processing")&&(e.find("button[type=submit]").each(((e,t)=>{i(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)=>{i(t).attr("disabled",!1)})),e.removeClass("modal-processing"),!0)}_.length?(v(!0),f.length?d():y(!0,d)):d(),u.length&&(u.on("submit",(function(e){if(e.preventDefault(),!C(u))return!1;const t={security:wc_checkout_params.apply_coupon_nonce,coupon_code:u.find('input[name="coupon_code"]').val()};i.ajax({type:"POST",url:wc_checkout_params.wc_ajax_url.toString().replace("%%endpoint%%","apply_coupon"),data:t,dataType:"html",success:e=>{if(r(),u.find(".result").remove(),e){const o=e.includes("error");u.append(`<p class="result ${a}__helper-text ${o?a+"__inline-error":""}">`+i(e).text()+"</p>"),o?(u.find('input[name="coupon_code"]').focus(),u.find('h3, input[name="coupon_code"]').addClass("newspack-ui__field-error")):(u.find('input[name="coupon_code"]').focus(),u.find('h3, input[name="coupon_code"]').removeClass("newspack-ui__field-error")),i(document.body).trigger("applied_coupon_in_checkout",[t.coupon_code]),i(document.body).trigger("update_checkout",{update_shipping_method:!1})}},complete:()=>{x(u)}})})),i(document.body).on("removed_coupon_in_checkout",(()=>{r(),u.find(".result").remove(),u.find('input[name="coupon_code"]').val("").focus()}))),p.length&&p.on("submit",(function(e){if(e.preventDefault(),!C(p))return!1;const t=p.find('input[name="price"]');t.attr("disabled",!0);const o={_ajax_nonce:newspackBlocksModalCheckout.nyp_nonce,action:"process_name_your_price_request",price:p.find('input[name="price"]').val(),product_id:p.find('input[name="product_id"]').val(),newspack_checkout_name_your_price:p.find('input[name="newspack_checkout_name_your_price"]').val()};i.ajax({type:"POST",url:newspackBlocksModalCheckout.ajax_url,data:o,success:({success:e,data:t})=>{r(),p.find(".result").remove(),p.append(`<p class="result ${a}__helper-text ${e?"":a+"__inline-error"}">`+t.message+"</p>"),e?p.find('h3, input[name="price"]').removeClass("newspack-ui__field-error"):(p.find('input[name="price"]').focus(),p.find('h3, input[name="price"]').addClass("newspack-ui__field-error")),i(document.body).trigger("update_checkout",{update_shipping_method:!1})},complete:()=>{x(p),t.attr("disabled",!1),t.focus()}})})),s.on("click","#place_order",(function(){(()=>{if("function"!=typeof window.gtag)return;const c=o("modal-checkout-product-details"),n=e("form_submission",c);t(n)})()}))}p()}function l(){const e=i("#newspack_subscription_terms_confirmation, #newspack_subscription_confirmation");if(e.length){const t=i("form.checkout"),o=t.find("button#place_order, button#place_order_clone");function c(){const t=e.is(":checked");o.each(((e,o)=>{i(o).attr("disabled",!t)}))}c(),e.on("change",c),t.on("submit",(function(t){if(!e.is(":checked"))return t.preventDefault(),t.stopPropagation(),!1}))}}i(document.body).on("updated_checkout payment_method_selected checkout_error",l),i(document).ready(l),i(document.body).on("checkout_error",(function(){const e=i(".woocommerce-NoticeGroup-checkout, .woocommerce-notices-wrapper");e.length&&e.each(((e,t)=>i(t).addClass(`${a}__notice ${a}__notice--error`)));const t=i("#checkout_error_back");t.length&&t.on("click",(e=>{e.preventDefault(),parent.newspackCloseModalCheckout()})),d(!1)})),document.addEventListener("keydown",(function(e){"Escape"===e.key&&parent.newspackCloseModalCheckout()})),newspackBlocksModalCheckout.is_error&&i(document.body).trigger("checkout_error")}))})();
@@ -7,6 +7,8 @@
7
7
 
8
8
  namespace Newspack_Blocks;
9
9
 
10
+ use Newspack_Blocks\Tracking\Data_Events;
11
+
10
12
  defined( 'ABSPATH' ) || exit;
11
13
 
12
14
  /**
@@ -348,11 +350,6 @@ final class Modal_Checkout {
348
350
 
349
351
  $cart_item_data = self::amend_cart_item_data( [ 'referer' => $referer ] );
350
352
 
351
- $newspack_popup_id = filter_input( INPUT_GET, 'newspack_popup_id', FILTER_SANITIZE_NUMBER_INT );
352
- if ( $newspack_popup_id ) {
353
- $cart_item_data['newspack_popup_id'] = $newspack_popup_id;
354
- }
355
-
356
353
  /** Apply NYP custom price */
357
354
  $price = filter_input( INPUT_GET, 'price', FILTER_SANITIZE_FULL_SPECIAL_CHARS );
358
355
  if ( \Newspack_Blocks::can_use_name_your_price() ? \WC_Name_Your_Price_Helpers::is_nyp( $product_id ) : false ) {
@@ -714,7 +711,7 @@ final class Modal_Checkout {
714
711
  $price = $variation->get_price();
715
712
  $price_html = $variation->get_price_html();
716
713
  $frequency = '';
717
- $product_type = \Newspack_Blocks\Tracking\Data_Events::get_product_type( $product_id );
714
+ $product_type = Data_Events::get_product_type( $product_id );
718
715
 
719
716
  // Use suggested price if NYP is active and set for variation.
720
717
  if ( \Newspack_Blocks::can_use_name_your_price() && \WC_Name_Your_Price_Helpers::is_nyp( $variation_id ) ) {
@@ -1114,13 +1111,29 @@ final class Modal_Checkout {
1114
1111
  * Get after success button params.
1115
1112
  */
1116
1113
  private static function get_after_success_params() {
1117
- return array_filter(
1118
- [
1119
- 'after_success_behavior' => isset( $_REQUEST['after_success_behavior'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['after_success_behavior'] ) ) : '', // phpcs:ignore WordPress.Security.NonceVerification.Recommended
1120
- 'after_success_url' => isset( $_REQUEST['after_success_url'] ) ? sanitize_url( wp_unslash( $_REQUEST['after_success_url'] ) ) : '', // phpcs:ignore WordPress.Security.NonceVerification.Recommended
1121
- 'after_success_button_label' => isset( $_REQUEST['after_success_button_label'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['after_success_button_label'] ) ) : '', // phpcs:ignore WordPress.Security.NonceVerification.Recommended
1122
- ]
1123
- );
1114
+ // Express checkout payment requests are separate requests, so they won't have the after_success attributes. We'll have to check the HTTP_REFERER instead.
1115
+ if ( self::is_express_checkout() ) {
1116
+ $referrer = isset( $_SERVER['HTTP_REFERER'] ) ? \esc_url_raw( \wp_unslash( $_SERVER['HTTP_REFERER'] ) ) : false; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
1117
+ if ( $referrer ) {
1118
+ $referrer_query = \wp_parse_url( $referrer, PHP_URL_QUERY );
1119
+ \wp_parse_str( $referrer_query, $referrer_query_params );
1120
+ return array_filter(
1121
+ [
1122
+ 'after_success_behavior' => isset( $referrer_query_params['after_success_behavior'] ) ? sanitize_text_field( wp_unslash( $referrer_query_params['after_success_behavior'] ) ) : '', // phpcs:ignore WordPress.Security.NonceVerification.Recommended
1123
+ 'after_success_url' => isset( $referrer_query_params['after_success_url'] ) ? sanitize_url( wp_unslash( $referrer_query_params['after_success_url'] ) ) : '', // phpcs:ignore WordPress.Security.NonceVerification.Recommended
1124
+ 'after_success_button_label' => isset( $referrer_query_params['after_success_button_label'] ) ? sanitize_text_field( wp_unslash( $referrer_query_params['after_success_button_label'] ) ) : '', // phpcs:ignore WordPress.Security.NonceVerification.Recommended
1125
+ ]
1126
+ );
1127
+ }
1128
+ } else {
1129
+ return array_filter(
1130
+ [
1131
+ 'after_success_behavior' => isset( $_REQUEST['after_success_behavior'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['after_success_behavior'] ) ) : '', // phpcs:ignore WordPress.Security.NonceVerification.Recommended
1132
+ 'after_success_url' => isset( $_REQUEST['after_success_url'] ) ? sanitize_url( wp_unslash( $_REQUEST['after_success_url'] ) ) : '', // phpcs:ignore WordPress.Security.NonceVerification.Recommended
1133
+ 'after_success_button_label' => isset( $_REQUEST['after_success_button_label'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['after_success_button_label'] ) ) : '', // phpcs:ignore WordPress.Security.NonceVerification.Recommended
1134
+ ]
1135
+ );
1136
+ }
1124
1137
  }
1125
1138
 
1126
1139
  /**
@@ -1165,7 +1178,6 @@ final class Modal_Checkout {
1165
1178
  if ( isset( $_REQUEST[ self::CHECKOUT_REGISTRATION_FLAG ] ) && $_REQUEST[ self::CHECKOUT_REGISTRATION_FLAG ] ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.MissingUnslash
1166
1179
  $args[ self::CHECKOUT_REGISTRATION_FLAG ] = '1';
1167
1180
  }
1168
-
1169
1181
  return add_query_arg(
1170
1182
  $args,
1171
1183
  $url
@@ -1526,7 +1538,16 @@ final class Modal_Checkout {
1526
1538
  */
1527
1539
  public static function pass_url_param_on_redirect( $location ) {
1528
1540
  if ( self::is_modal_checkout() ) {
1529
- $location = \add_query_arg( [ 'modal_checkout' => 1 ], $location );
1541
+ $params = [ 'modal_checkout' => 1 ];
1542
+ $newspack_popup_id = filter_input( INPUT_GET, 'newspack_popup_id', FILTER_SANITIZE_NUMBER_INT );
1543
+ $gate_post_id = filter_input( INPUT_GET, 'memberships_content_gate', FILTER_SANITIZE_NUMBER_INT );
1544
+ if ( $newspack_popup_id ) {
1545
+ $params['newspack_popup_id'] = $newspack_popup_id;
1546
+ }
1547
+ if ( $gate_post_id ) {
1548
+ $params['memberships_content_gate'] = $gate_post_id;
1549
+ }
1550
+ $location = \add_query_arg( $params, $location );
1530
1551
  }
1531
1552
  return $location;
1532
1553
  }
@@ -1592,21 +1613,33 @@ final class Modal_Checkout {
1592
1613
  $is_modal_checkout = strpos( $_REQUEST['post_data'], 'modal_checkout=1' ) !== false; // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.MissingUnslash, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
1593
1614
  }
1594
1615
 
1595
- // Express checkout payment requests are separate requests, so they won't have the modal checkout flag. We'll have to check the HTTP_REFERER insteaad.
1596
- $payment_request_type = filter_input( INPUT_POST, 'payment_request_type', FILTER_SANITIZE_FULL_SPECIAL_CHARS );
1597
- $is_express_checkout = ! empty( $payment_request_type ) && in_array( $payment_request_type, [ 'apple_pay', 'google_pay', 'payment_request_api' ], true ); // Validate payment request types: https://github.com/woocommerce/woocommerce-gateway-stripe/blob/develop/includes/payment-methods/class-wc-stripe-payment-request.php#L529-L548.
1616
+ if ( self::is_express_checkout() ) {
1617
+ $is_modal_checkout = true;
1618
+ }
1619
+
1620
+ return $is_modal_checkout;
1621
+ }
1622
+
1623
+ /**
1624
+ * Is this transaction using an express checkout method?
1625
+ */
1626
+ public static function is_express_checkout() {
1627
+ // Get express_payment_type in a way that works for both Stripe and WooPayments.
1628
+ $express_payment_info = isset( $_POST['express_payment_type'] ) ? sanitize_text_field( wp_unslash( $_POST['express_payment_type'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification
1629
+
1630
+ $is_express_checkout = ! empty( $express_payment_info ) && in_array( $express_payment_info, [ 'apple_pay', 'google_pay', 'payment_request_api' ], true ); // Validate payment request types: https://github.com/woocommerce/woocommerce-gateway-stripe/blob/develop/includes/payment-methods/class-wc-stripe-payment-request.php#L557-L586.
1631
+
1598
1632
  if ( $is_express_checkout ) {
1599
1633
  $referrer = isset( $_SERVER['HTTP_REFERER'] ) ? \esc_url_raw( \wp_unslash( $_SERVER['HTTP_REFERER'] ) ) : false; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
1600
1634
  if ( $referrer ) {
1601
1635
  $referrer_query = \wp_parse_url( $referrer, PHP_URL_QUERY );
1602
1636
  \wp_parse_str( $referrer_query, $referrer_query_params );
1603
1637
  if ( isset( $referrer_query_params['modal_checkout'] ) && $referrer_query_params['modal_checkout'] ) {
1604
- $is_modal_checkout = true;
1638
+ return true;
1605
1639
  }
1606
1640
  }
1607
1641
  }
1608
-
1609
- return $is_modal_checkout;
1642
+ return false;
1610
1643
  }
1611
1644
 
1612
1645
  /**
@@ -1682,10 +1715,8 @@ final class Modal_Checkout {
1682
1715
  foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) :
1683
1716
  $_product = apply_filters( 'woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key );
1684
1717
  if ( $_product && $_product->exists() && $cart_item['quantity'] > 0 && apply_filters( 'woocommerce_checkout_cart_item_visible', true, $cart_item, $cart_item_key ) ) :
1685
- // Create an empty array to store data order information.
1686
- $data_order_details = [];
1687
1718
  // Create an array of order information to pass to GA4 via JavaScript.
1688
- $data_order_details = \Newspack_Blocks\Tracking\Data_Events::build_js_data_events( $_product->get_id(), $cart_item, $_product->get_parent_id() );
1719
+ $data_order_details = Data_Events::build_js_data_events( $_product->get_id(), $cart_item );
1689
1720
  ?>
1690
1721
  <p id="modal-checkout-product-details" data-order-details='<?php echo wp_json_encode( $data_order_details ); ?>'>
1691
1722
  <strong>
@@ -2015,7 +2046,12 @@ final class Modal_Checkout {
2015
2046
  ),
2016
2047
  'after_success' => __( 'Continue browsing', 'newspack-blocks' ),
2017
2048
  'donation_gift_details' => __( 'This donation is a gift', 'newspack-blocks' ),
2018
- 'purchase_gift_details' => __( 'This purchase is a gift', 'newspack-blocks' ),
2049
+ 'purchase_gift_details' => get_option(
2050
+ 'woocommerce_subscriptions_gifting_gifting_checkbox_text',
2051
+ method_exists( 'Newspack\WooCommerce_Subscriptions_Gifting', 'default_gifting_checkbox_text' ) ?
2052
+ \Newspack\WooCommerce_Subscriptions_Gifting::default_gifting_checkbox_text() :
2053
+ __( 'This purchase is a gift', 'newspack-blocks' )
2054
+ ),
2019
2055
  'checkout_confirm' => __( 'Complete transaction', 'newspack-blocks' ),
2020
2056
  'checkout_confirm_variation' => __( 'Purchase', 'newspack-blocks' ),
2021
2057
  'checkout_back' => __( 'Back', 'newspack-blocks' ),
@@ -73,53 +73,6 @@ class Newspack_Blocks_API {
73
73
  return $featured_image_set;
74
74
  }
75
75
 
76
- /**
77
- * Get author info for the rest field.
78
- *
79
- * @param array $object_info The object info.
80
- * @return array Author data.
81
- */
82
- public static function newspack_blocks_get_author_info( $object_info ) {
83
- $author_data = [];
84
-
85
- if ( function_exists( 'coauthors_posts_links' ) && ! empty( get_coauthors() ) ) :
86
- $authors = get_coauthors();
87
-
88
- foreach ( $authors as $author ) {
89
- $author_avatar = coauthors_get_avatar( $author, 48 );
90
- $author_link = null;
91
-
92
- if ( function_exists( 'coauthors_posts_links' ) ) {
93
- $author_link = get_author_posts_url( $author->ID, $author->user_nicename );
94
- }
95
- $author_data[] = array(
96
- /* Get the author name */
97
- 'display_name' => esc_html( $author->display_name ),
98
- /* Get the author avatar */
99
- 'avatar' => wp_kses_post( $author_avatar ),
100
- /* Get the author ID */
101
- 'id' => $author->ID,
102
- /* Get the author Link */
103
- 'author_link' => $author_link,
104
- );
105
- }
106
- else :
107
- $author_data[] = array(
108
- /* Get the author name */
109
- 'display_name' => get_the_author_meta( 'display_name', $object_info['author'] ),
110
- /* Get the author avatar */
111
- 'avatar' => get_avatar( $object_info['author'], 48 ),
112
- /* Get the author ID */
113
- 'id' => $object_info['author'],
114
- /* Get the author Link */
115
- 'author_link' => get_author_posts_url( $object_info['author'] ),
116
- );
117
- endif;
118
-
119
- /* Return the author data */
120
- return $author_data;
121
- }
122
-
123
76
  /**
124
77
  * Get primary category for the rest field.
125
78
  *
@@ -306,9 +259,9 @@ class Newspack_Blocks_API {
306
259
  ];
307
260
 
308
261
  $sponsors = Newspack_Blocks::get_all_sponsors( $post->ID );
262
+ $author_info = Newspack_Blocks::prepare_authors();
309
263
  $add_ons = [
310
264
  'newspack_article_classes' => Newspack_Blocks::get_term_classes( $data['id'] ),
311
- 'newspack_author_info' => self::newspack_blocks_get_author_info( $data ),
312
265
  'newspack_category_info' => self::newspack_blocks_get_primary_category( $data ),
313
266
  'newspack_featured_image_caption' => Newspack_Blocks::get_image_caption( $data['featured_media'], $attributes['showCaption'], $attributes['showCredit'] ),
314
267
  'newspack_featured_image_src' => self::newspack_blocks_get_image_src( $data ),
@@ -316,6 +269,8 @@ class Newspack_Blocks_API {
316
269
  'newspack_post_sponsors' => self::newspack_blocks_sponsor_info( $data ),
317
270
  'newspack_sponsors_show_author' => Newspack_Blocks::newspack_display_sponsors_and_authors( $sponsors ),
318
271
  'newspack_sponsors_show_categories' => Newspack_Blocks::newspack_display_sponsors_and_categories( $sponsors ),
272
+ 'newspack_post_avatars' => \newspack_blocks_format_avatars( $author_info ),
273
+ 'newspack_post_byline' => \newspack_blocks_format_byline( $author_info ),
319
274
  'post_status' => $post->post_status,
320
275
  'post_type' => $post->post_type,
321
276
  'post_link' => Newspack_Blocks::get_post_link( $post->ID ),
@@ -139,6 +139,7 @@ class Newspack_Blocks_Caching {
139
139
  *
140
140
  * The tradeoff is that occasionally the current post may show up in an article block on a post.
141
141
  * Archives should all use a global cache group, because there is nothing that would need de-duplication.
142
+ * Feeds have their own cache group because some blocks have (e.g. content loop) have different markup in feeds vs. site frontend.
142
143
  *
143
144
  * @return string Cache group.
144
145
  */
@@ -150,6 +151,8 @@ class Newspack_Blocks_Caching {
150
151
  return sprintf( self::CACHE_GROUP . '-post-%d', get_the_ID() );
151
152
  }
152
153
  return self::CACHE_GROUP;
154
+ } elseif ( is_feed() ) {
155
+ return self::CACHE_GROUP . '-feed';
153
156
  } else {
154
157
  return self::CACHE_GROUP;
155
158
  }
@@ -29,6 +29,8 @@ class Newspack_Blocks {
29
29
  add_post_type_support( 'page', 'newspack_blocks' );
30
30
  add_action( 'jetpack_register_gutenberg_extensions', [ __CLASS__, 'disable_jetpack_donate' ], 99 );
31
31
  add_filter( 'the_content', [ __CLASS__, 'hide_post_content_when_iframe_block_is_fullscreen' ] );
32
+ add_filter( 'body_class', [ __CLASS__, 'add_body_classes' ] );
33
+ add_filter( 'admin_body_class', [ __CLASS__, 'add_body_classes' ] );
32
34
 
33
35
  /**
34
36
  * Disable NextGEN's `C_NextGen_Shortcode_Manager`.
@@ -80,6 +82,25 @@ class Newspack_Blocks {
80
82
  return $content;
81
83
  }
82
84
 
85
+ /**
86
+ * Body class.
87
+ *
88
+ * @param string|array $classes Array or string of body class names.
89
+ * @return string|array Modified array or string of body class names.
90
+ */
91
+ public static function add_body_classes( $classes ) {
92
+ if ( wp_is_block_theme() ) {
93
+ // Handle string (admin) vs array (frontend) cases.
94
+ if ( is_string( $classes ) ) {
95
+ $classes .= ' is-block-theme ';
96
+ } else {
97
+ $classes[] = 'is-block-theme';
98
+ }
99
+ }
100
+
101
+ return $classes;
102
+ }
103
+
83
104
  /**
84
105
  * Gather dependencies and paths needed for script enqueuing.
85
106
  *
@@ -772,27 +793,38 @@ class Newspack_Blocks {
772
793
  /**
773
794
  * Prepare an array of authors, taking presence of CoAuthors Plus into account.
774
795
  *
775
- * @return array Array of WP_User objects.
796
+ * @return object[] Array of user objects.
776
797
  */
777
798
  public static function prepare_authors() {
778
- if ( function_exists( 'coauthors_posts_links' ) && ! empty( get_coauthors() ) ) {
799
+ $authors = [];
800
+
801
+ if ( function_exists( 'get_coauthors' ) ) {
779
802
  $authors = get_coauthors();
780
803
  foreach ( $authors as $author ) {
781
804
  $author->avatar = coauthors_get_avatar( $author, 48 );
782
805
  $author->url = get_author_posts_url( $author->ID, $author->user_nicename );
783
806
  }
784
- return $authors;
785
- }
786
- $id = get_the_author_meta( 'ID' );
787
- return array(
788
- (object) array(
789
- 'ID' => $id,
790
- 'avatar' => get_avatar( $id, 48 ),
791
- 'url' => get_author_posts_url( $id ),
792
- 'user_nicename' => get_the_author(),
793
- 'display_name' => get_the_author_meta( 'display_name' ),
794
- ),
795
- );
807
+ }
808
+
809
+ if ( empty( $authors ) ) {
810
+ $id = get_the_author_meta( 'ID' );
811
+ $authors = array(
812
+ (object) array(
813
+ 'ID' => $id,
814
+ 'avatar' => get_avatar( $id, 48 ),
815
+ 'url' => get_author_posts_url( $id ),
816
+ 'user_nicename' => get_the_author(),
817
+ 'display_name' => get_the_author_meta( 'display_name' ),
818
+ ),
819
+ );
820
+ }
821
+
822
+ /**
823
+ * Filters the authors array.
824
+ *
825
+ * @param object[] $authors Array of user objects.
826
+ */
827
+ return apply_filters( 'newspack_blocks_post_authors', $authors );
796
828
  }
797
829
 
798
830
  /**
@@ -1450,7 +1482,7 @@ class Newspack_Blocks {
1450
1482
  */
1451
1483
  public static function get_formatted_amount( $amount = null, $frequency = null, $hide_once_label = false ) {
1452
1484
  if ( ! function_exists( 'wc_price' ) || ( method_exists( 'Newspack\Donations', 'is_platform_wc' ) && ! \Newspack\Donations::is_platform_wc() ) ) {
1453
- if ( 0 === $amount ) {
1485
+ if ( empty( $amount ) ) {
1454
1486
  return false;
1455
1487
  }
1456
1488
 
@@ -132,28 +132,55 @@ final class Data_Events {
132
132
  /**
133
133
  * Returns an array of product information.
134
134
  *
135
- * @param string $product_id Product's ID.
136
- * @param array $cart_item Cart item.
137
- * @param string $product_parent_id Product's ID when it has variations.
135
+ * @param int $product_id Product's ID.
136
+ * @param array $cart_item Cart item, if during checkout.
137
+ * @param WC_Order $order Completed order, if checkout is completed.
138
+ *
139
+ * @return array
138
140
  */
139
- public static function build_js_data_events( $product_id, $cart_item, $product_parent_id = '' ) {
141
+ public static function build_js_data_events( $product_id, $cart_item = null, $order = null ) {
142
+ $data_order_details = [];
143
+ if ( empty( $product_id ) || ( empty( $cart_item ) && empty( $order ) ) ) {
144
+ return $data_order_details;
145
+ }
146
+
140
147
  // Reassign the IDs to make sure the product is the product and the variation is the variation.
148
+ $product = \wc_get_product( $product_id );
149
+ $product_parent_id = $product->get_parent_id();
141
150
  $variation_id = '';
142
151
  if ( '' !== $product_parent_id && 0 !== $product_parent_id ) {
143
152
  $variation_id = $product_id;
144
- $product_id = $product_parent_id;
153
+ $product_id = $product_parent_id;
154
+ }
155
+
156
+ $amount = 0;
157
+ $referrer = '';
158
+ if ( ! empty( $order ) ) {
159
+ $amount = $order->get_total();
160
+ $referrer = $order->get_meta( '_newspack_referer' );
161
+ } elseif ( ! empty( $cart_item ) ) {
162
+ $amount = $cart_item['data']->get_price();
163
+ $referrer = $cart_item['referer'];
145
164
  }
146
165
 
147
166
  $data_order_details = [
148
- 'amount' => $cart_item['data']->get_price(),
167
+ 'amount' => $amount,
149
168
  'action_type' => self::get_action_type( $product_id ),
150
169
  'currency' => function_exists( 'get_woocommerce_currency' ) ? \get_woocommerce_currency() : 'USD',
151
170
  'product_id' => strval( $product_id ),
152
171
  'product_type' => self::get_product_type( $product_id ),
153
- 'referrer' => str_replace( home_url(), '', $cart_item['referer'] ), // Keeps format consistent for Homepage with Donate and Checkout Button blocks.
172
+ 'referrer' => str_replace( home_url(), '', $referrer ), // Keeps format consistent for Homepage with Donate and Checkout Button blocks.
154
173
  'recurrence' => self::get_purchase_recurrence( $product_id ),
155
174
  'variation_id' => strval( $variation_id ),
156
175
  ];
176
+ $gate_post_id = ! empty( $order ) ? $order->get_meta( '_memberships_content_gate' ) : filter_input( INPUT_GET, 'memberships_content_gate', FILTER_SANITIZE_NUMBER_INT );
177
+ if ( $gate_post_id ) {
178
+ $data_order_details['gate_post_id'] = $gate_post_id;
179
+ }
180
+ $newspack_popup_id = ! empty( $order ) ? $order->get_meta( '_newspack_popup_id' ) : filter_input( INPUT_GET, 'newspack_popup_id', FILTER_SANITIZE_NUMBER_INT );
181
+ if ( $newspack_popup_id ) {
182
+ $data_order_details['newspack_popup_id'] = $newspack_popup_id;
183
+ }
157
184
  return $data_order_details;
158
185
  }
159
186
 
@@ -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.11.0
10
+ * Version: 4.12.0
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.11.0' );
18
+ define( 'NEWSPACK_BLOCKS__VERSION', '4.12.0' );
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
@@ -1,18 +1,18 @@
1
1
  {
2
2
  "name": "@automattic/newspack-blocks",
3
- "version": "4.11.0",
3
+ "version": "4.12.0",
4
4
  "author": "Automattic",
5
5
  "devDependencies": {
6
6
  "@rushstack/eslint-patch": "^1.11.0",
7
7
  "@testing-library/dom": "^10.4.0",
8
8
  "@testing-library/user-event": "^14.6.1",
9
9
  "@types/lodash": "^4.17.16",
10
- "@wordpress/browserslist-config": "^6.21.0",
10
+ "@wordpress/browserslist-config": "^6.22.0",
11
11
  "eslint": "^8.57.0",
12
12
  "fetch-mock-jest": "^1.5.1",
13
13
  "html-entities": "^2.6.0",
14
14
  "identity-obj-proxy": "^3.0.0",
15
- "lint-staged": "^15.5.0",
15
+ "lint-staged": "^15.5.1",
16
16
  "newspack-components": "^3.1.0",
17
17
  "newspack-scripts": "^5.5.2",
18
18
  "postcss-scss": "^4.0.9"
@@ -1,7 +1,7 @@
1
1
  @use "../../../shared/sass/variables";
2
2
  @use "../../../shared/sass/mixins";
3
3
 
4
- body:not([class*="block-theme"]) .editor-styles-wrapper div.wp-block-columns {
4
+ body:not(.is-block-theme) .editor-styles-wrapper div.wp-block-columns {
5
5
  gap: 32px;
6
6
 
7
7
  &.is-style-borders {