@automattic/newspack-blocks 4.34.0 → 4.34.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 +15 -0
- package/dist/modal.asset.php +1 -1
- package/dist/modal.js +1 -1
- package/languages/newspack-blocks.pot +1 -1
- package/newspack-blocks.php +2 -2
- package/package.json +3 -3
- package/src/modal-checkout/modal.js +11 -1
- package/src/modal-checkout/utils.js +33 -0
- package/src/modal-checkout/utils.test.js +67 -1
- package/vendor/composer/installed.php +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,3 +1,18 @@
|
|
|
1
|
+
## @automattic/newspack-blocks [4.34.2](https://github.com/Automattic/newspack-workspace/compare/newspack-blocks@4.34.1...newspack-blocks@4.34.2) (2026-09-29)
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
### Bug Fixes
|
|
5
|
+
|
|
6
|
+
* **modal-checkout:** promotional links wait for reader activation ([#1076](https://github.com/Automattic/newspack-workspace/issues/1076)) ([522ae9a](https://github.com/Automattic/newspack-workspace/commit/522ae9aeb3235a91972f3835a4c21aff6acc5543))
|
|
7
|
+
|
|
8
|
+
## @automattic/newspack-blocks [4.34.1](https://github.com/Automattic/newspack-workspace/compare/newspack-blocks@4.34.0...newspack-blocks@4.34.1) (2026-09-28)
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
### Dependencies
|
|
12
|
+
|
|
13
|
+
* **newspack-icons:** upgraded to 1.1.3
|
|
14
|
+
* **newspack-components:** upgraded to 4.9.2
|
|
15
|
+
|
|
1
16
|
# @automattic/newspack-blocks [4.34.0](https://github.com/Automattic/newspack-workspace/compare/newspack-blocks@4.33.2...newspack-blocks@4.34.0) (2026-09-28)
|
|
2
17
|
|
|
3
18
|
|
package/dist/modal.asset.php
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
<?php return array('dependencies' => array(), 'version' => '
|
|
1
|
+
<?php return array('dependencies' => array(), 'version' => 'd540ac3428d006bff92c');
|
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("checkout-after-success");c=null!==o?o:n.getElementById("checkout_cancel"),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","quantity","variation_id","variation_ids","is_variable","is_grouped","child_ids","price_summary","newspack_popup_id","prompt_title","gate_post_id","contextual_prompt_post_id","contextual_prompt_placement","contextual_prompt_condition","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:r="",is_grouped:a="",price:i="",variation_id:s=""}=e,l={...e};(c||i)&&(l.amount=c||i),r&&!s&&(n="opened_variations"),a&&(n="opened_grouped");const u=t(n,l);o(u)};function r(e,t=null){const n=document.createElement("input");return n.type="hidden",n.name=e,t&&(n.value=t),n}function a(e){e.requestSubmit(e.querySelector('button[type="submit"]'))}function i(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}const s=e=>{if("function"!=typeof window.gtag)return;e=e||i("newspack_modal_checkout");const n=t("dismissed",e);o(n)};function l(e){const t=e&&e.dataset?e.dataset.checkout:null;if(!t)return null;try{return JSON.parse(t)}catch(e){return null}}const u=e=>Boolean(e.closest(".newspack-blocks__url-triggered-checkout"));function d(e,t,n=null,o={}){const{synthesized:c=null}=o,r=e.querySelectorAll(".wp-block-newspack-blocks-checkout-button"),a=null!=n&&""!==String(n);let i=null;return r.forEach(e=>{if(i)return;if(null!==c&&u(e)!==c)return;const o=e.querySelector("form"),r=l(o);r&&String(r.product_id)===String(t)&&(a&&String(r.variation_id)!==String(n)||!a&&r.variation_id||(i=o))}),i}function p(e,t,n={}){const{synthesized:o=null}=n,c=e.querySelectorAll(".wp-block-newspack-blocks-checkout-button");let r=null,a=null;return c.forEach(e=>{if(a)return;if(null!==o&&u(e)!==o)return;const n=e.querySelector("form"),c=l(n);c&&String(c.product_id)===String(t)&&(c.variation_id?r=r||n:a=n)}),a||r}function m(e,t,n,o={}){const{variationModalClassPrefix:c,iframeName:r}=o,a=[...e.querySelectorAll(`.${c}`)].find(e=>String(e.dataset.productId)===String(t));if(!a)return null;const i=a.querySelectorAll("form"),s=r?[...i].find(e=>e.getAttribute("target")===r):i[0];if(!s)return null;const l=[...s.querySelectorAll('input[type="radio"][name="product_id"]')].find(e=>String(e.value)===String(n));return l?(l.checked=!0,s):null}const h=["after_success_behavior","after_success_url","after_success_button_label","after_success_token","gate_post_id","newspack_popup_id","prompt_title","contextual_prompt_post_id","contextual_prompt_placement","contextual_prompt_condition","coupon","quantity"];function f(e,t,n=h){if(!e||!t)return;const o=t.ownerDocument,c=new FormData(e);n.forEach(e=>{if(t.querySelector(`input[name="${e}"]`))return;const n=c.getAll(e).filter(e=>"string"==typeof e&&e);if(!n.length)return;const r=o.createElement("input");r.type="hidden",r.name=e,r.value=n[n.length-1],t.prepend(r)})}const y=["coupon","after_success_behavior","after_success_url","after_success_button_label"],_=["tiered","frequency","untiered"],w=["once","month","year"];const k={gate:"gate_post_id",prompt:"newspack_popup_id"};const g=newspackBlocksModal.newspack_class_prefix,v="newspack_modal_checkout_iframe",b="newspack_modal_checkout_container",S=`${g}__modal`,E="newspack-blocks__modal-variation",q=`${g}__processing-payment-text`,A=newspackBlocksModal.processing_payment_messages;let L=!1,$=newspackBlocksModal.labels.checkout_modal_title,R=null;const M=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(`.${S}-container`).forEach(e=>M(e)))};const x=new CustomEvent("checkout-closed");var C;window.newspackRAS=window.newspackRAS||[],C=()=>{const t=document.querySelector("#newspack_modal_checkout");if(!t)return;const n=t.querySelector(`.${S}__content`),o=r("modal_checkout","1"),u=n.querySelector(`.${g}__spinner`);let C=document.querySelector(".newspack-reader__account-link")?.[0];const B="600px",P=document.createElement("iframe");P.name=v,P.style.height=B,P.style.visibility="hidden";const T=e=>{j.observe(e),"none"!==u.style.display&&(u.style.display="none"),"visible"!==P.style.visibility&&(P.style.visibility="visible"),P._ready=!0};!function(e,t,n){e._ready=!1,e._readyTimer&&clearTimeout(e._readyTimer);let o=!1,c="";function r(){o||(o=!0,clearTimeout(e._readyTimer),t.call(this))}function a(){"complete"===this.readyState&&r.call(this)}function i(){e._ready=!1,n&&n(),e._readyTimer&&clearTimeout(e._readyTimer);const t=e.contentDocument||e.contentWindow?.document;t&&(t.removeEventListener("DOMContentLoaded",r),t.removeEventListener("readystatechange",a))}function s(){if(e._ready)return void i();const t=e.contentDocument||e.contentWindow?.document;t&&0!==t.URL.indexOf("about:")?"complete"===t?.readyState?r.call(t):(t.addEventListener("DOMContentLoaded",r),t.addEventListener("readystatechange",a)):e._readyTimer=setTimeout(s,10)}e._observer||(e._observer=new MutationObserver(e=>{e.forEach(e=>{"attributes"===e.type&&"src"===e.attributeName&&(o=!1,i(),s())})}),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,i(),s())},50)),s()}(P,function(){const n=P.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=P?.contentDocument?.querySelector(`#${b}`);if(!o)return;const c=i(o.querySelector("#modal-checkout-product-details")),r=document.createElement("p");r.classList.add(q);let a=[];const s=()=>{a.forEach(e=>clearTimeout(e)),a=[]},l=()=>{u.style.display="none",s(),u.querySelectorAll(`.${q}`).forEach(e=>e.remove())};!function(e,t){e.checkoutCancel?t():e.addEventListener("checkout-cancel",t)}(o,()=>{z()}),function(e,t){e.checkoutPlaceOrderStart?t():e.addEventListener("checkout-place-order-start",t)}(o,e=>{u.querySelectorAll(`.${q}`).forEach(e=>e.remove()),u.style.display="flex",s(),r.textContent=A[0]?.text??"",A.slice(1).forEach(({text:t,delay:n})=>{const o=setTimeout(()=>{e.target.dispatchEvent(new CustomEvent("checkout-place-order-processing")),r.textContent=t},n);a.push(o)}),u.appendChild(r)}),function(e,t){e.checkoutPlaceOrderError?t():e.addEventListener("checkout-place-order-error",t)}(o,l),function(e,t){e.checkoutReady?t():e.addEventListener("checkout-ready",t)}(o,()=>{if(t.initialErrors){const e=document.createElement("div");e.classList.add("woocommerce-error"),e.textContent=t.initialErrors,o.prepend(e),delete t.initialErrors}J(),H($),P.contentWindow?.newspackBlocksModalCheckout?.checkout_nonce&&(t.checkout_nonce=P.contentWindow.newspackBlocksModalCheckout.checkout_nonce),T(o)}),function(e,t){e.checkoutComplete?t():e.addEventListener("checkout-complete",t)}(o,()=>{window.newspackRAS.push(["checkout_completed",c]),window?.newspackReaderActivation?.refreshNewslettersSignupModal&&window?.newspackReaderActivation?.getReader()?.email&&window.newspackReaderActivation.refreshNewslettersSignupModal(window.newspackReaderActivation.getReader().email),J("small"),H(newspackBlocksModal.labels.thankyou_modal_title),T(o),e(t.querySelector(`.${S}`)),l()}),function(e,t){e.checkoutPlaceOrderCriticalError?t():e.addEventListener("checkout-place-order-critical-error",t)}(o,()=>{var e;(e=R)&&(z(),u.style.display="none",t.initialErrors=newspackBlocksModal.labels.critical_error,e.requestSubmit(e.querySelector('button[type="submit"]')),l())})},()=>{u.style.display="flex"});const D=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)}),I=()=>"undefined"!=typeof newspack_ras_config&&!newspack_ras_config?.is_logged_in&&!window?.newspackReaderActivation?.getReader?.()?.authenticated&&newspackBlocksModal?.is_registration_required&&window?.newspackReaderActivation?.openAuthModal,N=function(e){const t={};return new URLSearchParams(e).forEach((e,n)=>{n.startsWith("utm")&&e&&(t[n]=e)}),t}(window.location.search),O=t=>{const n=!newspackBlocksModal.has_unsupported_payment_gateway;n||t.preventDefault();const o=t.target;o.classList.add("modal-processing"),function(e){if(!e||"function"!=typeof e.querySelector)return!1;if(e.closest(".newspack-content-gate__gate"))return!1;const t=function(){let e,t;try{e=window.sessionStorage.getItem("newspack_cta_attribution")}catch(e){return null}if(!e)return null;try{t=JSON.parse(e)}catch(e){return null}return t&&1===t.v&&k[t.type]&&t.id?"number"!=typeof t.ts||Date.now()-t.ts>18e5?null:t:null}();if(!t)return!1;const n=k[t.type];if(e.querySelector(`input[name="${n}"]`))return!1;const o=document.createElement("input");o.type="hidden",o.name=n,o.value=t.id,e.prepend(o)}(o),function(e,t){if(!e||!t)return;const n=e.ownerDocument;Object.keys(t).forEach(o=>{if(!t[o]||e.elements.namedItem(o))return;const c=n.createElement("input");c.type="hidden",c.name=o,c.value=t[o],e.prepend(c)})}(o,N);const u=i(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,r;n?(c=t[n],r=u[`donation_value_${e}`]):(c=t[0],u[`donation_value_${e}_untiered`]?r=u[`donation_value_${e}_untiered`]:(r=u[`donation_value_${e}`],"other"===r&&(r=u[`donation_value_${e}_other`])));const a=i(c);for(const e in a)u[e]=a[e];u.amount=r,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(r(e,u[e]))}),u.variation_id||(C=t.submitter);const d=document.querySelectorAll(`.${E}`);if(d.forEach(e=>{(I()||n)&&M(e)}),u.is_grouped||u.is_variable&&!u.variation_id){const n=[...d].find(e=>e.dataset.productId===u.product_id);if(n)return n.querySelectorAll(`form[target="${v}"]`).forEach(e=>{!function(e,t,n=h){if(!e||!t)return;const o=e.ownerDocument;n.forEach(n=>{if(e.querySelectorAll(`input[type="hidden"][name="${n}"]`).forEach(e=>e.remove()),function(e,t){return!!e.querySelector(`input[name="${t}"]:not([type="hidden"])`)}(e,n))return;const c=t[n],r=null==c?"":String(c);if(!r)return;const a=o.createElement("input");a.type="hidden",a.name=n,a.value=r,e.prepend(a)})}(e,u);const t=l(e);t&&Object.keys(t).forEach(n=>{0===e.querySelectorAll('input[name="'+n+'"]').length&&e.prepend(r(n,t[n]))})}),t.preventDefault(),o.classList.remove("modal-processing"),F(n),e(n,!1),L||c(u),void document.getElementById("newspack_modal_checkout").setAttribute("data-checkout",JSON.stringify(u))}if(n||I()){if(o.classList.remove("modal-processing"),L||c(u),L=!0,I()){t.preventDefault();const e=D(u);e.then(e=>{window.newspackReaderActivation?.setPendingCheckout?.(e)}),window.newspackReaderActivation.openAuthModal({title:newspackBlocksModal.labels.auth_modal_title,onSuccess:(t,o)=>{e.then(e=>{o?.registered&&n&&(e+=`&${newspackBlocksModal.checkout_registration_flag}=1`),n?a(U(e)):D(u).then(window.location.href=e)}).catch(e=>{console.warn("Unable to generate cart:",e),z()})},onError:()=>{z()},onDismiss:()=>{s(u),L=!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}},trigger:t.submitter,closeOnSuccess:n})}else W(),document.getElementById("newspack_modal_checkout").setAttribute("data-checkout",JSON.stringify(u));R=o}else D(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>"})},U=e=>{const t=document.createElement("form");t.method="POST",t.action=e,t.target=v,t.style.display="none";const n=document.createElement("button");return n.setAttribute("type","submit"),t.appendChild(n),document.body.appendChild(t),t.addEventListener("submit",O),t},j=new ResizeObserver(e=>{if(!e||!e.length)return;if(!P.contentDocument)return;const o=e[0].contentRect;if(o){const e=.01*Math.max(document.documentElement.clientHeight,window.innerHeight||0)*90-(t.querySelector(`.${S}__header`)?.offsetHeight||0),c=o.top+o.bottom,r=Math.min(c,e);if(0===r)return void(P.style.visibility="hidden");n.style.height=r+"px",P.style.height=r+"px"}}),z=()=>{const e=P?.contentDocument?.querySelector(`#${b}`),o=e?.querySelector('input[name="after_success_url"]'),c=e?.querySelector('input[name="after_success_behavior"]'),r=document?.querySelector(".newspack-newsletters-signup-modal"),a=i(e?.querySelector("#modal-checkout-product-details"));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 l=!(P.contentDocument&&o&&c&&e?.checkoutComplete);if((l||r)&&(u.style.display="flex",P&&n.contains(P)&&(P._ready=!1,P.src="about:blank",P.style.height=B,P.style.visibility="hidden",n.style.height=B,n.removeChild(P)),j&&j.disconnect(),document.querySelectorAll(`.${S}-container`).forEach(e=>M(e)),C&&C.focus(),document.dispatchEvent(x)),e?.checkoutComplete){const e=()=>{if(o&&c){const e=o.getAttribute("value"),t=c.getAttribute("value");if("custom"===t)window.location.href=e;else if("referrer"===t){const e=document.referrer;let t=!1;if(e)try{new URL(e).origin===window.location.origin&&(window.location.href=e,t=!0)}catch(e){}t||window.history.back()}}window?.newspackReaderActivation?.setPendingCheckout?.(),L=!1};"subscription_switch"!==a.action_type&&window?.newspackReaderActivation?.openNewslettersSignupModal?window.newspackReaderActivation.openNewslettersSignupModal({onSuccess:e,onError:e,closeOnSuccess:l}):e(),l&&($=newspackBlocksModal.labels.checkout_modal_title,J(),H($))}else window?.newspackReaderActivation?.setPendingCheckout?.(),s(),L=!1,document.getElementById("newspack_modal_checkout").removeAttribute("data-checkout");document.removeEventListener("keydown",K)},W=o=>{o&&(P.src=o),u.style.display="flex",F(t),n.appendChild(P),t.addEventListener("click",e=>{e.target===t&&z()}),e(t,P),document.addEventListener("keydown",K)},F=e=>{window.newspackReaderActivation?.overlays&&(e.overlayId=window.newspackReaderActivation?.overlays.add()),e.setAttribute("data-state","open"),document.body.style.overflow="hidden"},H=e=>{const n=t.querySelector(`.${S}__header h2`);n&&(n.innerText=e)},J=(e="default")=>{const n=t.querySelector(`.${S}`);n&&("small"===e?n.classList.add(`${S}--small`):n.classList.remove(`${S}--small`))};t.querySelectorAll(`.${S}__close`).forEach(e=>{e.addEventListener("click",e=>{e.preventDefault(),z()})}),document.querySelectorAll(".newspack-blocks__modal-variation").forEach(e=>{e.addEventListener("click",t=>{t.target===e&&z()}),e.querySelectorAll(`.${S}__close`).forEach(e=>{e.addEventListener("click",e=>{e.preventDefault(),z()})})});const K=e=>{"Escape"===e.key&&z()};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=v,e.addEventListener("submit",O)})});const V=["checkout","type","layout","frequency","amount","other","product_id","variation_id"],G=()=>{const e=new URL(window.location.href);V.forEach(t=>e.searchParams.delete(t)),window.history.replaceState(null,null,e.href)},Q=(e,t,n,o=null)=>{const c=function(e,{layout:t,frequency:n,amount:o}){if(!function(e,t,n){return!(!_.includes(e)||!w.includes(t))&&("other"===n?"frequency"===e:/^\d+(\.\d+)?$/.test(n))}(t,n,o))return{status:"invalid-params"};let c=null;for(const r of e.querySelectorAll(".wpbnbd.wpbnbd--platform-wc form")){const e=r.closest(".wpbnbd--tiers-based");if("tiered"===t){if(!e)continue;const t=r.querySelector(`.wpbnbd__tiers__amount [data-frequency-slug="${n}"][data-amount="${o}"]`);if(!t)continue;const a=parseInt(t.getAttribute("data-tier-index"));if(isNaN(a))continue;const i=r.querySelector(`button[data-frequency-slug="${n}"]`);if(!i&&!r.querySelector(`input[name="donation_frequency"][value="${n}"]`))continue;if(!e.hasAttribute("data-tiers-based-ready")){c||(c=r);continue}return{status:"tiered",form:r,frequencyButton:i,tierIndex:a}}if(e)continue;const a=r.querySelector(`input[name="donation_frequency"][value="${n}"]`);if(!a)continue;const i="untiered"===t?r.querySelector(`input[name="donation_value_${n}_untiered"]`):r.querySelector(`input[name="donation_value_${n}"][value="${o}"]`);if(i)return{status:t,form:r,frequencyInput:a,amountInput:i}}return c?{status:"not-ready",form:c}:{status:"no-match"}}(document,{layout:e,frequency:t,amount:n}),r=`layout "${e}", frequency "${t}" and amount "${n}"`;if("invalid-params"===c.status)return console.warn(`Newspack modal checkout: invalid donate trigger parameters (${r}). The checkout was not triggered.`),!1;if("no-match"===c.status)return console.warn(`Newspack modal checkout: no donate form matches ${r}. The checkout was not triggered.`),!1;if("not-ready"===c.status){const c=setTimeout(()=>{console.warn(`Newspack modal checkout: the donate form matching ${r} never finished initializing. The checkout was not triggered; the URL params were kept so a reload can retry.`)},5e3);return document.addEventListener("newspack-tiers-based-ready",()=>{clearTimeout(c),Q(e,t,n,o)&&G()},{once:!0}),!1}const{form:i}=c;if("tiered"===c.status){c.frequencyButton&&c.frequencyButton.click();const e=i.querySelector(`button[type="submit"][data-tier-index="${c.tierIndex}"]`);return e?(e.click(),!0):(console.warn(`Newspack modal checkout: no tier submit button matches ${r}. The checkout was not triggered.`),!1)}if(c.frequencyInput.checked=!0,"untiered"===c.status)c.amountInput.value=n;else if("other"===n){c.amountInput.click();const e=i.querySelector(`input[name="donation_value_${t}_other"]`);e&&o&&(e.value=o)}else c.amountInput.checked=!0;return i.checkValidity()?(a(i),!0):(console.warn(`Newspack modal checkout: the donate form rejected the values for ${r}. The checkout was not triggered.`),!1)};(()=>{const e=new URLSearchParams(window.location.search);if(!e.has("checkout"))return;let t=!0;const n=e.get("type");if("donate"===n){const n=e.get("layout"),o=e.get("frequency"),c=e.get("amount"),r=e.get("other");n&&o&&c?t=Q(n,o,c,r):(t=!1,console.warn("Newspack modal checkout: donate trigger is missing layout, frequency or amount. The checkout was not triggered."))}else if("checkout_button"===n){const n=e.get("product_id"),o=e.get("variation_id");n?t=((e,t=null)=>{const n=function(e,t,n,o={}){if(null==n||""===String(n))return d(e,t,null,{synthesized:!1})||d(e,t,null,{synthesized:!0});const c=d(e,t,n,{synthesized:!1});if(c)return c;const r=p(e,t,{synthesized:!1});if(r){const c=m(e,t,n,o);if(c)return f(r,c),c}const a=d(e,t,n,{synthesized:!0});if(a)return a;const i=m(e,t,n,o);return i?(f(p(e,t),i),i):null}(document,e,t,{variationModalClassPrefix:E,iframeName:v});if(n){const e=function(e,t){const n=new URLSearchParams(t);return y.filter(t=>n.get(t)&&!(e&&e.elements.namedItem(t)))}(n,window.location.search);return e.length&&console.warn(`Newspack modal checkout: the resolved checkout form does not carry ${e.join(", ")} from the URL. The page block's own settings apply instead.`),a(n),!0}const o=`Newspack modal checkout: no checkout form found for product_id "${e}"`+(t?` and variation_id "${t}"`:"")+". The checkout was not triggered.";return console.warn(o),!1})(n,o):(t=!1,console.warn("Newspack modal checkout: checkout_button trigger is missing product_id. The checkout was not triggered."))}else{const e=window.newspackReaderActivation?.getPendingCheckout?.();e&&a(U(e))}t&&G()})(),window.newspackOpenModalCheckout=({url:e=null,title:t=null,actionType:n=null,afterSuccess:o={},quantity:c=null,onCheckoutComplete:r=null,onClose:a=null})=>{if($=t||newspackBlocksModal.labels.checkout_modal_title,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),c&&parseInt(c,10)>1&&e.searchParams.set("quantity",String(parseInt(c,10))),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),r){const e=({detail:{action:e,data:t}})=>{"checkout_completed"===e&&r(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)}W(e.toString())},window.newspackCloseModalCheckout=z},"undefined"!=typeof document&&("complete"!==document.readyState&&"interactive"!==document.readyState?document.addEventListener("DOMContentLoaded",C):C())})();
|
|
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("checkout-after-success");c=null!==o?o:n.getElementById("checkout_cancel"),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","quantity","variation_id","variation_ids","is_variable","is_grouped","child_ids","price_summary","newspack_popup_id","prompt_title","gate_post_id","contextual_prompt_post_id","contextual_prompt_placement","contextual_prompt_condition","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:r="",is_grouped:a="",price:i="",variation_id:s=""}=e,u={...e};(c||i)&&(u.amount=c||i),r&&!s&&(n="opened_variations"),a&&(n="opened_grouped");const l=t(n,u);o(l)};function r(e,t=null){const n=document.createElement("input");return n.type="hidden",n.name=e,t&&(n.value=t),n}function a(e){e.requestSubmit(e.querySelector('button[type="submit"]'))}function i(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}const s=e=>{if("function"!=typeof window.gtag)return;e=e||i("newspack_modal_checkout");const n=t("dismissed",e);o(n)};function u(e){const t=e&&e.dataset?e.dataset.checkout:null;if(!t)return null;try{return JSON.parse(t)}catch(e){return null}}const l=e=>Boolean(e.closest(".newspack-blocks__url-triggered-checkout"));function d(e,t,n=null,o={}){const{synthesized:c=null}=o,r=e.querySelectorAll(".wp-block-newspack-blocks-checkout-button"),a=null!=n&&""!==String(n);let i=null;return r.forEach(e=>{if(i)return;if(null!==c&&l(e)!==c)return;const o=e.querySelector("form"),r=u(o);r&&String(r.product_id)===String(t)&&(a&&String(r.variation_id)!==String(n)||!a&&r.variation_id||(i=o))}),i}function p(e,t,n={}){const{synthesized:o=null}=n,c=e.querySelectorAll(".wp-block-newspack-blocks-checkout-button");let r=null,a=null;return c.forEach(e=>{if(a)return;if(null!==o&&l(e)!==o)return;const n=e.querySelector("form"),c=u(n);c&&String(c.product_id)===String(t)&&(c.variation_id?r=r||n:a=n)}),a||r}function m(e,t,n,o={}){const{variationModalClassPrefix:c,iframeName:r}=o,a=[...e.querySelectorAll(`.${c}`)].find(e=>String(e.dataset.productId)===String(t));if(!a)return null;const i=a.querySelectorAll("form"),s=r?[...i].find(e=>e.getAttribute("target")===r):i[0];if(!s)return null;const u=[...s.querySelectorAll('input[type="radio"][name="product_id"]')].find(e=>String(e.value)===String(n));return u?(u.checked=!0,s):null}const h=["after_success_behavior","after_success_url","after_success_button_label","after_success_token","gate_post_id","newspack_popup_id","prompt_title","contextual_prompt_post_id","contextual_prompt_placement","contextual_prompt_condition","coupon","quantity"];function f(e,t,n=h){if(!e||!t)return;const o=t.ownerDocument,c=new FormData(e);n.forEach(e=>{if(t.querySelector(`input[name="${e}"]`))return;const n=c.getAll(e).filter(e=>"string"==typeof e&&e);if(!n.length)return;const r=o.createElement("input");r.type="hidden",r.name=e,r.value=n[n.length-1],t.prepend(r)})}const y=["coupon","after_success_behavior","after_success_url","after_success_button_label"],_=["tiered","frequency","untiered"],w=["once","month","year"];const k={gate:"gate_post_id",prompt:"newspack_popup_id"};const g=newspackBlocksModal.newspack_class_prefix,v="newspack_modal_checkout_iframe",b="newspack_modal_checkout_container",S=`${g}__modal`,E="newspack-blocks__modal-variation",q=`${g}__processing-payment-text`,A=newspackBlocksModal.processing_payment_messages;let L=!1,$=newspackBlocksModal.labels.checkout_modal_title,R=null;const M=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(`.${S}-container`).forEach(e=>M(e)))};const C=new CustomEvent("checkout-closed");var x;window.newspackRAS=window.newspackRAS||[],x=()=>{const t=document.querySelector("#newspack_modal_checkout");if(!t)return;const n=t.querySelector(`.${S}__content`),o=r("modal_checkout","1"),l=n.querySelector(`.${g}__spinner`);let x=document.querySelector(".newspack-reader__account-link")?.[0];const B="600px",T=document.createElement("iframe");T.name=v,T.style.height=B,T.style.visibility="hidden";const P=e=>{j.observe(e),"none"!==l.style.display&&(l.style.display="none"),"visible"!==T.style.visibility&&(T.style.visibility="visible"),T._ready=!0};!function(e,t,n){e._ready=!1,e._readyTimer&&clearTimeout(e._readyTimer);let o=!1,c="";function r(){o||(o=!0,clearTimeout(e._readyTimer),t.call(this))}function a(){"complete"===this.readyState&&r.call(this)}function i(){e._ready=!1,n&&n(),e._readyTimer&&clearTimeout(e._readyTimer);const t=e.contentDocument||e.contentWindow?.document;t&&(t.removeEventListener("DOMContentLoaded",r),t.removeEventListener("readystatechange",a))}function s(){if(e._ready)return void i();const t=e.contentDocument||e.contentWindow?.document;t&&0!==t.URL.indexOf("about:")?"complete"===t?.readyState?r.call(t):(t.addEventListener("DOMContentLoaded",r),t.addEventListener("readystatechange",a)):e._readyTimer=setTimeout(s,10)}e._observer||(e._observer=new MutationObserver(e=>{e.forEach(e=>{"attributes"===e.type&&"src"===e.attributeName&&(o=!1,i(),s())})}),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,i(),s())},50)),s()}(T,function(){const n=T.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=T?.contentDocument?.querySelector(`#${b}`);if(!o)return;const c=i(o.querySelector("#modal-checkout-product-details")),r=document.createElement("p");r.classList.add(q);let a=[];const s=()=>{a.forEach(e=>clearTimeout(e)),a=[]},u=()=>{l.style.display="none",s(),l.querySelectorAll(`.${q}`).forEach(e=>e.remove())};!function(e,t){e.checkoutCancel?t():e.addEventListener("checkout-cancel",t)}(o,()=>{z()}),function(e,t){e.checkoutPlaceOrderStart?t():e.addEventListener("checkout-place-order-start",t)}(o,e=>{l.querySelectorAll(`.${q}`).forEach(e=>e.remove()),l.style.display="flex",s(),r.textContent=A[0]?.text??"",A.slice(1).forEach(({text:t,delay:n})=>{const o=setTimeout(()=>{e.target.dispatchEvent(new CustomEvent("checkout-place-order-processing")),r.textContent=t},n);a.push(o)}),l.appendChild(r)}),function(e,t){e.checkoutPlaceOrderError?t():e.addEventListener("checkout-place-order-error",t)}(o,u),function(e,t){e.checkoutReady?t():e.addEventListener("checkout-ready",t)}(o,()=>{if(t.initialErrors){const e=document.createElement("div");e.classList.add("woocommerce-error"),e.textContent=t.initialErrors,o.prepend(e),delete t.initialErrors}J(),H($),T.contentWindow?.newspackBlocksModalCheckout?.checkout_nonce&&(t.checkout_nonce=T.contentWindow.newspackBlocksModalCheckout.checkout_nonce),P(o)}),function(e,t){e.checkoutComplete?t():e.addEventListener("checkout-complete",t)}(o,()=>{window.newspackRAS.push(["checkout_completed",c]),window?.newspackReaderActivation?.refreshNewslettersSignupModal&&window?.newspackReaderActivation?.getReader()?.email&&window.newspackReaderActivation.refreshNewslettersSignupModal(window.newspackReaderActivation.getReader().email),J("small"),H(newspackBlocksModal.labels.thankyou_modal_title),P(o),e(t.querySelector(`.${S}`)),u()}),function(e,t){e.checkoutPlaceOrderCriticalError?t():e.addEventListener("checkout-place-order-critical-error",t)}(o,()=>{var e;(e=R)&&(z(),l.style.display="none",t.initialErrors=newspackBlocksModal.labels.critical_error,e.requestSubmit(e.querySelector('button[type="submit"]')),u())})},()=>{l.style.display="flex"});const D=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)}),I=()=>"undefined"!=typeof newspack_ras_config&&!newspack_ras_config?.is_logged_in&&!window?.newspackReaderActivation?.getReader?.()?.authenticated&&newspackBlocksModal?.is_registration_required&&window?.newspackReaderActivation?.openAuthModal,N=function(e){const t={};return new URLSearchParams(e).forEach((e,n)=>{n.startsWith("utm")&&e&&(t[n]=e)}),t}(window.location.search),O=t=>{const n=!newspackBlocksModal.has_unsupported_payment_gateway;n||t.preventDefault();const o=t.target;o.classList.add("modal-processing"),function(e){if(!e||"function"!=typeof e.querySelector)return!1;if(e.closest(".newspack-content-gate__gate"))return!1;const t=function(){let e,t;try{e=window.sessionStorage.getItem("newspack_cta_attribution")}catch(e){return null}if(!e)return null;try{t=JSON.parse(e)}catch(e){return null}return t&&1===t.v&&k[t.type]&&t.id?"number"!=typeof t.ts||Date.now()-t.ts>18e5?null:t:null}();if(!t)return!1;const n=k[t.type];if(e.querySelector(`input[name="${n}"]`))return!1;const o=document.createElement("input");o.type="hidden",o.name=n,o.value=t.id,e.prepend(o)}(o),function(e,t){if(!e||!t)return;const n=e.ownerDocument;Object.keys(t).forEach(o=>{if(!t[o]||e.elements.namedItem(o))return;const c=n.createElement("input");c.type="hidden",c.name=o,c.value=t[o],e.prepend(c)})}(o,N);const l=i(o);if(l.newspack_donate){const e=l.donation_frequency,t=[...o.querySelectorAll(`.donation-tier__${e}, .donation-frequency__${e}`)],n=l.donation_tier_index;let c,r;n?(c=t[n],r=l[`donation_value_${e}`]):(c=t[0],l[`donation_value_${e}_untiered`]?r=l[`donation_value_${e}_untiered`]:(r=l[`donation_value_${e}`],"other"===r&&(r=l[`donation_value_${e}_other`])));const a=i(c);for(const e in a)l[e]=a[e];l.amount=r,l.price_summary=l.summary_template.replace("{{PRICE}}",function(e,t="USD"){return parseFloat(e).toLocaleString(document.documentElement.lang,{style:"currency",currency:t,currencyDisplay:"narrowSymbol"})}(l.amount,l.currency))}l&&Object.keys(l).forEach(e=>{0===o.querySelectorAll('input[name="'+e+'"]').length&&o.prepend(r(e,l[e]))}),l.variation_id||(x=t.submitter);const d=document.querySelectorAll(`.${E}`);if(d.forEach(e=>{(I()||n)&&M(e)}),l.is_grouped||l.is_variable&&!l.variation_id){const n=[...d].find(e=>e.dataset.productId===l.product_id);if(n)return n.querySelectorAll(`form[target="${v}"]`).forEach(e=>{!function(e,t,n=h){if(!e||!t)return;const o=e.ownerDocument;n.forEach(n=>{if(e.querySelectorAll(`input[type="hidden"][name="${n}"]`).forEach(e=>e.remove()),function(e,t){return!!e.querySelector(`input[name="${t}"]:not([type="hidden"])`)}(e,n))return;const c=t[n],r=null==c?"":String(c);if(!r)return;const a=o.createElement("input");a.type="hidden",a.name=n,a.value=r,e.prepend(a)})}(e,l);const t=u(e);t&&Object.keys(t).forEach(n=>{0===e.querySelectorAll('input[name="'+n+'"]').length&&e.prepend(r(n,t[n]))})}),t.preventDefault(),o.classList.remove("modal-processing"),F(n),e(n,!1),L||c(l),void document.getElementById("newspack_modal_checkout").setAttribute("data-checkout",JSON.stringify(l))}if(n||I()){if(o.classList.remove("modal-processing"),L||c(l),L=!0,I()){t.preventDefault();const e=D(l);e.then(e=>{window.newspackReaderActivation?.setPendingCheckout?.(e)}),window.newspackReaderActivation.openAuthModal({title:newspackBlocksModal.labels.auth_modal_title,onSuccess:(t,o)=>{e.then(e=>{o?.registered&&n&&(e+=`&${newspackBlocksModal.checkout_registration_flag}=1`),n?a(U(e)):D(l).then(window.location.href=e)}).catch(e=>{console.warn("Unable to generate cart:",e),z()})},onError:()=>{z()},onDismiss:()=>{s(l),L=!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}},trigger:t.submitter,closeOnSuccess:n})}else W(),document.getElementById("newspack_modal_checkout").setAttribute("data-checkout",JSON.stringify(l));R=o}else D(l).then(e=>{window.location.href=e}),(!l.is_variable||l.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>"})},U=e=>{const t=document.createElement("form");t.method="POST",t.action=e,t.target=v,t.style.display="none";const n=document.createElement("button");return n.setAttribute("type","submit"),t.appendChild(n),document.body.appendChild(t),t.addEventListener("submit",O),t},j=new ResizeObserver(e=>{if(!e||!e.length)return;if(!T.contentDocument)return;const o=e[0].contentRect;if(o){const e=.01*Math.max(document.documentElement.clientHeight,window.innerHeight||0)*90-(t.querySelector(`.${S}__header`)?.offsetHeight||0),c=o.top+o.bottom,r=Math.min(c,e);if(0===r)return void(T.style.visibility="hidden");n.style.height=r+"px",T.style.height=r+"px"}}),z=()=>{const e=T?.contentDocument?.querySelector(`#${b}`),o=e?.querySelector('input[name="after_success_url"]'),c=e?.querySelector('input[name="after_success_behavior"]'),r=document?.querySelector(".newspack-newsletters-signup-modal"),a=i(e?.querySelector("#modal-checkout-product-details"));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 u=!(T.contentDocument&&o&&c&&e?.checkoutComplete);if((u||r)&&(l.style.display="flex",T&&n.contains(T)&&(T._ready=!1,T.src="about:blank",T.style.height=B,T.style.visibility="hidden",n.style.height=B,n.removeChild(T)),j&&j.disconnect(),document.querySelectorAll(`.${S}-container`).forEach(e=>M(e)),x&&x.focus(),document.dispatchEvent(C)),e?.checkoutComplete){const e=()=>{if(o&&c){const e=o.getAttribute("value"),t=c.getAttribute("value");if("custom"===t)window.location.href=e;else if("referrer"===t){const e=document.referrer;let t=!1;if(e)try{new URL(e).origin===window.location.origin&&(window.location.href=e,t=!0)}catch(e){}t||window.history.back()}}window?.newspackReaderActivation?.setPendingCheckout?.(),L=!1};"subscription_switch"!==a.action_type&&window?.newspackReaderActivation?.openNewslettersSignupModal?window.newspackReaderActivation.openNewslettersSignupModal({onSuccess:e,onError:e,closeOnSuccess:u}):e(),u&&($=newspackBlocksModal.labels.checkout_modal_title,J(),H($))}else window?.newspackReaderActivation?.setPendingCheckout?.(),s(),L=!1,document.getElementById("newspack_modal_checkout").removeAttribute("data-checkout");document.removeEventListener("keydown",K)},W=o=>{o&&(T.src=o),l.style.display="flex",F(t),n.appendChild(T),t.addEventListener("click",e=>{e.target===t&&z()}),e(t,T),document.addEventListener("keydown",K)},F=e=>{window.newspackReaderActivation?.overlays&&(e.overlayId=window.newspackReaderActivation?.overlays.add()),e.setAttribute("data-state","open"),document.body.style.overflow="hidden"},H=e=>{const n=t.querySelector(`.${S}__header h2`);n&&(n.innerText=e)},J=(e="default")=>{const n=t.querySelector(`.${S}`);n&&("small"===e?n.classList.add(`${S}--small`):n.classList.remove(`${S}--small`))};t.querySelectorAll(`.${S}__close`).forEach(e=>{e.addEventListener("click",e=>{e.preventDefault(),z()})}),document.querySelectorAll(".newspack-blocks__modal-variation").forEach(e=>{e.addEventListener("click",t=>{t.target===e&&z()}),e.querySelectorAll(`.${S}__close`).forEach(e=>{e.addEventListener("click",e=>{e.preventDefault(),z()})})});const K=e=>{"Escape"===e.key&&z()};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=v,e.addEventListener("submit",O)})});const V=["checkout","type","layout","frequency","amount","other","product_id","variation_id"],G=()=>{const e=new URL(window.location.href);V.forEach(t=>e.searchParams.delete(t)),window.history.replaceState(null,null,e.href)},Q=(e,t,n,o=null)=>{const c=function(e,{layout:t,frequency:n,amount:o}){if(!function(e,t,n){return!(!_.includes(e)||!w.includes(t))&&("other"===n?"frequency"===e:/^\d+(\.\d+)?$/.test(n))}(t,n,o))return{status:"invalid-params"};let c=null;for(const r of e.querySelectorAll(".wpbnbd.wpbnbd--platform-wc form")){const e=r.closest(".wpbnbd--tiers-based");if("tiered"===t){if(!e)continue;const t=r.querySelector(`.wpbnbd__tiers__amount [data-frequency-slug="${n}"][data-amount="${o}"]`);if(!t)continue;const a=parseInt(t.getAttribute("data-tier-index"));if(isNaN(a))continue;const i=r.querySelector(`button[data-frequency-slug="${n}"]`);if(!i&&!r.querySelector(`input[name="donation_frequency"][value="${n}"]`))continue;if(!e.hasAttribute("data-tiers-based-ready")){c||(c=r);continue}return{status:"tiered",form:r,frequencyButton:i,tierIndex:a}}if(e)continue;const a=r.querySelector(`input[name="donation_frequency"][value="${n}"]`);if(!a)continue;const i="untiered"===t?r.querySelector(`input[name="donation_value_${n}_untiered"]`):r.querySelector(`input[name="donation_value_${n}"][value="${o}"]`);if(i)return{status:t,form:r,frequencyInput:a,amountInput:i}}return c?{status:"not-ready",form:c}:{status:"no-match"}}(document,{layout:e,frequency:t,amount:n}),r=`layout "${e}", frequency "${t}" and amount "${n}"`;if("invalid-params"===c.status)return console.warn(`Newspack modal checkout: invalid donate trigger parameters (${r}). The checkout was not triggered.`),!1;if("no-match"===c.status)return console.warn(`Newspack modal checkout: no donate form matches ${r}. The checkout was not triggered.`),!1;if("not-ready"===c.status){const c=setTimeout(()=>{console.warn(`Newspack modal checkout: the donate form matching ${r} never finished initializing. The checkout was not triggered; the URL params were kept so a reload can retry.`)},5e3);return document.addEventListener("newspack-tiers-based-ready",()=>{clearTimeout(c),Q(e,t,n,o)&&G()},{once:!0}),!1}const{form:i}=c;if("tiered"===c.status){c.frequencyButton&&c.frequencyButton.click();const e=i.querySelector(`button[type="submit"][data-tier-index="${c.tierIndex}"]`);return e?(e.click(),!0):(console.warn(`Newspack modal checkout: no tier submit button matches ${r}. The checkout was not triggered.`),!1)}if(c.frequencyInput.checked=!0,"untiered"===c.status)c.amountInput.value=n;else if("other"===n){c.amountInput.click();const e=i.querySelector(`input[name="donation_value_${t}_other"]`);e&&o&&(e.value=o)}else c.amountInput.checked=!0;return i.checkValidity()?(a(i),!0):(console.warn(`Newspack modal checkout: the donate form rejected the values for ${r}. The checkout was not triggered.`),!1)};(function(e){const{readyState:t}=document;"complete"===t||"interactive"===t&&function(){const[e]=window.performance?.getEntriesByType?.("navigation")||[];return!e||e.domContentLoadedEventStart>0}()?e():document.addEventListener("DOMContentLoaded",e,{once:!0})})(()=>{const e=new URLSearchParams(window.location.search);if(!e.has("checkout"))return;let t=!0;const n=e.get("type");if("donate"===n){const n=e.get("layout"),o=e.get("frequency"),c=e.get("amount"),r=e.get("other");n&&o&&c?t=Q(n,o,c,r):(t=!1,console.warn("Newspack modal checkout: donate trigger is missing layout, frequency or amount. The checkout was not triggered."))}else if("checkout_button"===n){const n=e.get("product_id"),o=e.get("variation_id");n?t=((e,t=null)=>{const n=function(e,t,n,o={}){if(null==n||""===String(n))return d(e,t,null,{synthesized:!1})||d(e,t,null,{synthesized:!0});const c=d(e,t,n,{synthesized:!1});if(c)return c;const r=p(e,t,{synthesized:!1});if(r){const c=m(e,t,n,o);if(c)return f(r,c),c}const a=d(e,t,n,{synthesized:!0});if(a)return a;const i=m(e,t,n,o);return i?(f(p(e,t),i),i):null}(document,e,t,{variationModalClassPrefix:E,iframeName:v});if(n){const e=function(e,t){const n=new URLSearchParams(t);return y.filter(t=>n.get(t)&&!(e&&e.elements.namedItem(t)))}(n,window.location.search);return e.length&&console.warn(`Newspack modal checkout: the resolved checkout form does not carry ${e.join(", ")} from the URL. The page block's own settings apply instead.`),a(n),!0}const o=`Newspack modal checkout: no checkout form found for product_id "${e}"`+(t?` and variation_id "${t}"`:"")+". The checkout was not triggered.";return console.warn(o),!1})(n,o):(t=!1,console.warn("Newspack modal checkout: checkout_button trigger is missing product_id. The checkout was not triggered."))}else{const e=window.newspackReaderActivation?.getPendingCheckout?.();e&&a(U(e))}t&&G()}),window.newspackOpenModalCheckout=({url:e=null,title:t=null,actionType:n=null,afterSuccess:o={},quantity:c=null,onCheckoutComplete:r=null,onClose:a=null})=>{if($=t||newspackBlocksModal.labels.checkout_modal_title,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),c&&parseInt(c,10)>1&&e.searchParams.set("quantity",String(parseInt(c,10))),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),r){const e=({detail:{action:e,data:t}})=>{"checkout_completed"===e&&r(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)}W(e.toString())},window.newspackCloseModalCheckout=z},"undefined"!=typeof document&&("complete"!==document.readyState&&"interactive"!==document.readyState?document.addEventListener("DOMContentLoaded",x):x())})();
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
# This file is distributed under the same license as the Newspack Blocks plugin.
|
|
3
3
|
msgid ""
|
|
4
4
|
msgstr ""
|
|
5
|
-
"Project-Id-Version: Newspack Blocks 4.34.
|
|
5
|
+
"Project-Id-Version: Newspack Blocks 4.34.2\n"
|
|
6
6
|
"Report-Msgid-Bugs-To: https://wordpress.org/support/plugin/newspack-blocks\n"
|
|
7
7
|
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
|
|
8
8
|
"Language-Team: LANGUAGE <LL@li.org>\n"
|
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.34.
|
|
10
|
+
* Version: 4.34.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.34.
|
|
18
|
+
define( 'NEWSPACK_BLOCKS__VERSION', '4.34.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
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@automattic/newspack-blocks",
|
|
3
|
-
"version": "4.34.
|
|
3
|
+
"version": "4.34.2",
|
|
4
4
|
"author": "Automattic",
|
|
5
5
|
"description": "=== Newspack Blocks === Contributors: (this should be a list of wordpress.org userid's) Donate link: https://example.com/ Tags: comments, spam Requires at least: 4.5 Tested up to: 5.1.1 Stable tag: 0.1.0 License: GPLv2 or later License URI: https://www.gnu.org/licenses/gpl-2.0.html",
|
|
6
6
|
"repository": {
|
|
@@ -49,7 +49,7 @@
|
|
|
49
49
|
"classnames": "^2.5.1",
|
|
50
50
|
"lodash": "^4.17.21",
|
|
51
51
|
"newspack-colors": "1.1.4",
|
|
52
|
-
"newspack-icons": "1.1.
|
|
52
|
+
"newspack-icons": "1.1.3",
|
|
53
53
|
"redux": "^5.0.0",
|
|
54
54
|
"redux-saga": "^1.5.0",
|
|
55
55
|
"regenerator-runtime": "^0.14.1",
|
|
@@ -57,7 +57,7 @@
|
|
|
57
57
|
},
|
|
58
58
|
"devDependencies": {
|
|
59
59
|
"@types/lodash": "^4.17.23",
|
|
60
|
-
"newspack-components": "4.9.
|
|
60
|
+
"newspack-components": "4.9.2",
|
|
61
61
|
"newspack-scripts": "5.11.0"
|
|
62
62
|
},
|
|
63
63
|
"overrides": {
|
|
@@ -11,6 +11,7 @@ import * as a11y from './accessibility.js';
|
|
|
11
11
|
*/
|
|
12
12
|
import { manageDismissed, manageOpened } from './analytics';
|
|
13
13
|
import {
|
|
14
|
+
afterDeferredScripts,
|
|
14
15
|
domReady,
|
|
15
16
|
iframeReady,
|
|
16
17
|
onCheckoutReady,
|
|
@@ -980,7 +981,16 @@ domReady( () => {
|
|
|
980
981
|
stripCheckoutUrlParams();
|
|
981
982
|
}
|
|
982
983
|
};
|
|
983
|
-
|
|
984
|
+
// A click reaches a form long after every script has loaded; the URL trigger
|
|
985
|
+
// fires as soon as this bundle runs. This bundle is async and the reader
|
|
986
|
+
// activation scripts are deferred, so firing here can beat them — and then
|
|
987
|
+
// the checkout opens without the sign-in step and without registering as an
|
|
988
|
+
// overlay, which lets prompts open on top of it. Deferred scripts are done
|
|
989
|
+
// by DOMContentLoaded, so the trigger waits for that rather than queueing on
|
|
990
|
+
// newspackRAS: that queue only flushes once newspack-plugin's reader
|
|
991
|
+
// activation script runs, and the modal needs only WooCommerce, so on a site
|
|
992
|
+
// without newspack-plugin a queued trigger would never fire.
|
|
993
|
+
afterDeferredScripts( handleModalCheckoutUrlParams );
|
|
984
994
|
|
|
985
995
|
/**
|
|
986
996
|
* Open the modal checkout.
|
|
@@ -20,6 +20,39 @@ export function domReady( callback ) {
|
|
|
20
20
|
document.addEventListener( 'DOMContentLoaded', callback );
|
|
21
21
|
}
|
|
22
22
|
|
|
23
|
+
/**
|
|
24
|
+
* Run a callback once every deferred script on the page has executed.
|
|
25
|
+
*
|
|
26
|
+
* Deferred scripts run after parsing ends and before DOMContentLoaded, and
|
|
27
|
+
* this bundle is async, so it can execute in between — domReady() only waits
|
|
28
|
+
* for parsing. readyState is `interactive` on both sides of DOMContentLoaded,
|
|
29
|
+
* so in that state navigation timing settles whether the event already fired.
|
|
30
|
+
*
|
|
31
|
+
* @param {Function} callback The function to run.
|
|
32
|
+
* @return {void}
|
|
33
|
+
*/
|
|
34
|
+
export function afterDeferredScripts( callback ) {
|
|
35
|
+
const { readyState } = document;
|
|
36
|
+
if ( readyState === 'complete' || ( readyState === 'interactive' && hasDomContentLoadedFired() ) ) {
|
|
37
|
+
return void callback();
|
|
38
|
+
}
|
|
39
|
+
document.addEventListener( 'DOMContentLoaded', callback, { once: true } );
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Whether DOMContentLoaded has fired, according to navigation timing.
|
|
44
|
+
*
|
|
45
|
+
* Without a navigation entry there is nothing to consult, and waiting would
|
|
46
|
+
* risk an event that never comes: report it as fired, which degrades to
|
|
47
|
+
* running immediately.
|
|
48
|
+
*
|
|
49
|
+
* @return {boolean} Whether the event has fired.
|
|
50
|
+
*/
|
|
51
|
+
function hasDomContentLoadedFired() {
|
|
52
|
+
const [ navigation ] = window.performance?.getEntriesByType?.( 'navigation' ) || [];
|
|
53
|
+
return ! navigation || navigation.domContentLoadedEventStart > 0;
|
|
54
|
+
}
|
|
55
|
+
|
|
23
56
|
/**
|
|
24
57
|
* Create a hidden input field.
|
|
25
58
|
*
|
|
@@ -2,12 +2,78 @@
|
|
|
2
2
|
* Tests for modal-checkout utils.
|
|
3
3
|
*/
|
|
4
4
|
|
|
5
|
-
import { getCheckoutData } from './utils';
|
|
5
|
+
import { afterDeferredScripts, getCheckoutData } from './utils';
|
|
6
6
|
|
|
7
7
|
afterEach( () => {
|
|
8
8
|
document.body.innerHTML = '';
|
|
9
9
|
} );
|
|
10
10
|
|
|
11
|
+
describe( 'afterDeferredScripts()', () => {
|
|
12
|
+
let readyState;
|
|
13
|
+
let navigationEntries;
|
|
14
|
+
|
|
15
|
+
beforeEach( () => {
|
|
16
|
+
readyState = 'complete';
|
|
17
|
+
navigationEntries = [];
|
|
18
|
+
Object.defineProperty( document, 'readyState', { configurable: true, get: () => readyState } );
|
|
19
|
+
Object.defineProperty( window.performance, 'getEntriesByType', {
|
|
20
|
+
configurable: true,
|
|
21
|
+
value: type => ( type === 'navigation' ? navigationEntries : [] ),
|
|
22
|
+
} );
|
|
23
|
+
} );
|
|
24
|
+
|
|
25
|
+
afterEach( () => {
|
|
26
|
+
delete document.readyState;
|
|
27
|
+
delete window.performance.getEntriesByType;
|
|
28
|
+
} );
|
|
29
|
+
|
|
30
|
+
// Images still loading keep readyState at `interactive` after DOMContentLoaded,
|
|
31
|
+
// so a bundle arriving then must not wait for an event that will not repeat.
|
|
32
|
+
// Missing navigation timing leaves nothing to consult, and the trigger
|
|
33
|
+
// degrades to running immediately rather than to never running.
|
|
34
|
+
it.each( [
|
|
35
|
+
[ 'the document is complete', 'complete', [] ],
|
|
36
|
+
[ 'DOMContentLoaded already fired and images keep the document interactive', 'interactive', [ { domContentLoadedEventStart: 850 } ] ],
|
|
37
|
+
[ 'navigation timing is unavailable', 'interactive', [] ],
|
|
38
|
+
] )( 'runs at once when %s', ( _, state, entries ) => {
|
|
39
|
+
readyState = state;
|
|
40
|
+
navigationEntries = entries;
|
|
41
|
+
const callback = jest.fn();
|
|
42
|
+
|
|
43
|
+
afterDeferredScripts( callback );
|
|
44
|
+
expect( callback ).toHaveBeenCalledTimes( 1 );
|
|
45
|
+
} );
|
|
46
|
+
|
|
47
|
+
it( 'waits for DOMContentLoaded, once, when parsing has ended but the event has not fired', () => {
|
|
48
|
+
// The window an async bundle lands in when it beats the deferred scripts:
|
|
49
|
+
// readyState is already `interactive`, DOMContentLoaded is still pending.
|
|
50
|
+
readyState = 'interactive';
|
|
51
|
+
navigationEntries = [ { domContentLoadedEventStart: 0 } ];
|
|
52
|
+
const callback = jest.fn();
|
|
53
|
+
|
|
54
|
+
afterDeferredScripts( callback );
|
|
55
|
+
expect( callback ).not.toHaveBeenCalled();
|
|
56
|
+
|
|
57
|
+
document.dispatchEvent( new Event( 'DOMContentLoaded' ) );
|
|
58
|
+
document.dispatchEvent( new Event( 'DOMContentLoaded' ) );
|
|
59
|
+
expect( callback ).toHaveBeenCalledTimes( 1 );
|
|
60
|
+
} );
|
|
61
|
+
|
|
62
|
+
it( 'waits for DOMContentLoaded while the document is still loading, without consulting timing', () => {
|
|
63
|
+
// `loading` alone says the event is ahead; the empty navigation timing
|
|
64
|
+
// must not be read as permission to run.
|
|
65
|
+
readyState = 'loading';
|
|
66
|
+
navigationEntries = [];
|
|
67
|
+
const callback = jest.fn();
|
|
68
|
+
|
|
69
|
+
afterDeferredScripts( callback );
|
|
70
|
+
expect( callback ).not.toHaveBeenCalled();
|
|
71
|
+
|
|
72
|
+
document.dispatchEvent( new Event( 'DOMContentLoaded' ) );
|
|
73
|
+
expect( callback ).toHaveBeenCalledTimes( 1 );
|
|
74
|
+
} );
|
|
75
|
+
} );
|
|
76
|
+
|
|
11
77
|
/**
|
|
12
78
|
* Build a checkout-button-style form: a `quantity` hidden input (as view.php
|
|
13
79
|
* emits when a block's default seat count is above 1) plus a `data-checkout`
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
'name' => 'automattic/newspack-blocks',
|
|
4
4
|
'pretty_version' => 'dev-main',
|
|
5
5
|
'version' => 'dev-main',
|
|
6
|
-
'reference' => '
|
|
6
|
+
'reference' => '522ae9aeb3235a91972f3835a4c21aff6acc5543',
|
|
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-main',
|
|
15
15
|
'version' => 'dev-main',
|
|
16
|
-
'reference' => '
|
|
16
|
+
'reference' => '522ae9aeb3235a91972f3835a4c21aff6acc5543',
|
|
17
17
|
'type' => 'wordpress-plugin',
|
|
18
18
|
'install_path' => __DIR__ . '/../../',
|
|
19
19
|
'aliases' => array(),
|