@lockerverse/react 0.2.180-dev.1 → 0.2.182-dev.1
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/MIGRATIONS.md +9 -9
- package/dist/lockerverse-donate-launcher.d.ts.map +1 -1
- package/dist/lockerverse-donate-launcher.js +1 -1
- package/dist/lockerverse-donate-launcher.js.map +1 -1
- package/dist/lockerverse-payment.js +1 -1
- package/dist/lockerverse-payment.js.map +1 -1
- package/dist/payment-form.d.ts.map +1 -1
- package/dist/payment-primitives.d.ts +1 -2
- package/dist/payment-primitives.d.ts.map +1 -1
- package/dist/payment-summary.js +1 -1
- package/dist/payment-summary.js.map +1 -1
- package/dist/styles.css +2 -20
- package/guides/auctions.md +1 -1
- package/guides/events.md +1 -1
- package/guides/integration.md +1 -1
- package/guides/payment-widgets.md +1 -1
- package/guides/signup.md +1 -1
- package/package.json +2 -2
package/MIGRATIONS.md
CHANGED
|
@@ -4,15 +4,6 @@ This file ships in both @lockerverse/sdk and @lockerverse/react. Use the copy in
|
|
|
4
4
|
the target installed release. This is an agent-run procedure, not an install
|
|
5
5
|
script. Installing a package does not edit host code or guarantee these steps ran.
|
|
6
6
|
|
|
7
|
-
## 0.2.180-dev.1 — live shipping for payment widgets
|
|
8
|
-
|
|
9
|
-
- **Affected:** Core checkout quotes and React payment forms for widgets with live shipping enabled.
|
|
10
|
-
- **Required:** deploy a backend with the live-shipping quote contract, then update matching Core and React packages and deploy the host. Configure and enable shipping only after the sender, package, and packing rules are complete.
|
|
11
|
-
- **Automatic:** React collects a shipping address, requests rates only when the buyer selects Calculate shipping, shows the shipping amount, and blocks payment until a current quote is available. Core preserves shipping quote tokens and expected amounts during confirmation.
|
|
12
|
-
- **Custom Core hosts:** send `shipping` to `calculateTotal`, show `shippingCents` in the total, retain `shippingQuote`, and reuse its token for price-only changes. Recalculate after a destination or cart change. Do not persist quote tokens in URLs or logs.
|
|
13
|
-
- **Unchanged:** widgets without live shipping use the existing checkout flow.
|
|
14
|
-
- **Check:** verify complete and incomplete addresses, quote errors and expiry, changed quantities, optional donations, and the displayed full total without submitting a live payment.
|
|
15
|
-
|
|
16
7
|
## Upgrade procedure
|
|
17
8
|
|
|
18
9
|
1. Before installation, record the resolved installed version of each package
|
|
@@ -45,6 +36,15 @@ If it cannot be found, report that limit and use the baseline review below. Do n
|
|
|
45
36
|
claim that every historical migration was applied. Read this file even if the
|
|
46
37
|
version already matches: a previous upgrade may have missed host adoption steps.
|
|
47
38
|
|
|
39
|
+
## 0.2.182-dev.1 — email discounts and required shipping
|
|
40
|
+
|
|
41
|
+
Required: upgrade Core and React together. Existing email percentage discounts need no host changes.
|
|
42
|
+
|
|
43
|
+
Widgets can now use a private contact list for email eligibility, a fixed amount discount, and an optional discount message. Entered-email matching remains unchanged. Public quotes contain optional `amountOffCents` and `message`; custom renderers must not assume `percentageOff` exists.
|
|
44
|
+
|
|
45
|
+
Required shipping appears in `catalog.widget.requiredShipping`. Do not offer this product as a separate shopper choice. The SDK adds its quantity once when a trigger product is selected; the server also enforces this rule. Render authoritative quote line items and totals, including shipping. The built-in launcher and payment summary handle this automatically.
|
|
46
|
+
|
|
47
|
+
|
|
48
48
|
## 0.2.176-dev.1 — Secure checkout loading recovery
|
|
49
49
|
|
|
50
50
|
- **Affected:** React payment widget Stripe fields.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lockerverse-donate-launcher.d.ts","names":[],"sources":["../src/lockerverse-donate-launcher.tsx"],"mappings":";;
|
|
1
|
+
{"version":3,"file":"lockerverse-donate-launcher.d.ts","names":[],"sources":["../src/lockerverse-donate-launcher.tsx"],"mappings":";;iBA+kBgB,4BACd,aACA,UACA,WACG,gBACF,iDAA8B,IAAA"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e,t}from"./accent-contrast.js";import{n,t as r}from"./lockerverse-payment.js";import{createElement as i,useState as a}from"react";import{Fragment as o,jsx as s,jsxs as c}from"react/jsx-runtime";import{Dialog as l}from"@base-ui/react/dialog";import{getLockerverseMinimumCustomAmountCents as u}from"@lockerverse/sdk/checkout";const d=new Intl.NumberFormat(`en-US`,{currency:`USD`,style:`currency`}),f=/^(?:0|[1-9]\d*)(?:\.\d{1,2})?$/,p=[1e3,2500,5e3,1e4];function m(e){if(!f.test(e))return null;let t=Math.round(Number(e)*100);return Number.isSafeInteger(t)&&t>0?t:null}function h(e,t){let n=``;return t===`monthly`&&(n=`/month`),t===`annually`&&(n=`/year`),t===`every-six-months`&&(n=` every 6 months`),`${d.format(e/100)}${n}`}function g({customAmounts:e,product:t,quantities:n,recurringProductId:r,setCustomAmounts:i,setQuantities:a,setRecurringProductId:o}){let l=n[t.id]??0;if(t.pricingMode===`fixed`&&t.paymentOption===`one-time`){let e=t.minimumQuantity??1,n=Math.min(t.maximumQuantity??1/0,t.inventoryQuantity??1/0);return c(`span`,{className:`lockerverse-launcher__quantity`,children:[s(`button`,{"aria-label":`Decrease ${t.name} quantity`,disabled:l===0,onClick:()=>{o(null),a(n=>{let r=n[t.id]??0;return{...n,[t.id]:r<=e?0:r-1}})},type:`button`,children:`−`}),s(`output`,{"aria-label":`${t.name} quantity`,children:l}),s(`button`,{"aria-label":`Increase ${t.name} quantity`,disabled:n<e||l>=n,onClick:()=>{o(null),a(n=>{let r=n[t.id]??0;return{...n,[t.id]:r===0?e:r+1}})},type:`button`,children:`+`})]})}return t.pricingMode===`custom`&&t.paymentOption===`one-time`?c(`span`,{className:`lockerverse-launcher__custom-amount`,children:[s(`span`,{"aria-hidden":`true`,children:`$`}),s(`input`,{"aria-label":`${t.name} amount`,min:u(t)/100,name:`amount-${t.slug}`,onChange:e=>{o(null),i(n=>({...n,[t.id]:e.target.value}))},placeholder:`0.00`,step:`0.01`,type:`number`,value:e[t.id]??``}),t.minimumAmountCents===null?null:c(`small`,{children:[`Minimum `,d.format(t.minimumAmountCents/100)]})]}):s(`button`,{"aria-label":`Select ${t.name}`,"aria-pressed":r===t.id,className:`lockerverse-launcher__select`,onClick:()=>{a({}),i({}),o(e=>e===t.id?null:t.id)},type:`button`,children:`Select`})}function _({variant:e=`default`,...t}){let{customAmounts:n,product:r,quantities:i,recurringProductId:a}=t,o=m(n[r.id]??``),l=a===r.id||r.paymentOption===`one-time`&&(r.pricingMode===`fixed`&&(i[r.id]??0)>0||r.pricingMode===`custom`&&o!==null&&o>=u(r));return c(`article`,{className:`lockerverse-launcher__product lockerverse-launcher__product--${e}`,"data-selected":l||void 0,children:[c(`span`,{className:`lockerverse-launcher__product-copy`,children:[s(`strong`,{className:`lockerverse-launcher__product-name`,children:r.name}),r.description?s(`small`,{children:r.description}):null,r.amountCents===null?null:s(`span`,{className:`lockerverse-launcher__product-price`,children:h(r.amountCents,r.paymentOption)})]}),s(g,{...t})]})}function v({customAmounts:e,product:t,setCustomAmounts:n,setRecurringProductId:r}){let i=e[t.id]??``,a=m(i),o=p.filter(e=>e>=u(t)),l=o.includes(a??0),f=e=>{r(null),n(n=>({...n,[t.id]:e}))};return s(`div`,{className:`lockerverse-launcher__donation-option`,children:c(`fieldset`,{className:`lockerverse-launcher__donation-choices`,children:[c(`legend`,{className:`lockerverse-launcher__sr-only`,children:[t.name,` amount`]}),s(`button`,{"aria-pressed":i===``,onClick:()=>f(``),type:`button`,children:`No thanks`}),o.map(e=>s(`button`,{"aria-pressed":a===e,onClick:()=>f(String(e/100)),type:`button`,children:d.format(e/100).replace(`.00`,``)},e)),s(`label`,{className:`lockerverse-launcher__donation-other`,"data-selected":i!==``&&!l||void 0,children:s(`input`,{"aria-label":`${t.name} amount`,min:u(t)/100,name:`amount-${t.slug}`,onChange:e=>f(e.target.value),placeholder:`Other $`,step:`0.01`,type:`number`,value:l?``:i})})]})})}function y({products:e,variant:t=`default`,...n}){return s(`div`,{className:`lockerverse-launcher__product-list`,children:e.map(e=>t===`donation`?i(v,{...n,key:e.id,product:e}):i(_,{...n,key:e.id,product:e,variant:t}))})}function b(e,t){let n=0,r=0;for(let i of t){let t=e.products.find(e=>e.slug===i.productSlug);if(t){if(`quantity`in i){n+=i.quantity,r+=(t.amountCents??0)*i.quantity;continue}n+=1,r+=`amountCents`in i?i.amountCents:t.amountCents??0}}return{amountCents:r,itemCount:n}}function x(){return s(`div`,{"aria-label":`Loading donation options`,className:`lockerverse-launcher__loading`,role:`status`,children:[0,1,2].map(e=>s(`span`,{"aria-hidden":`true`,className:`lockerverse-launcher__loading-row`},e))})}function S(e,t,n,r){if(r){let t=e.products.find(e=>e.id===r&&e.paymentOption!==`one-time`);return t?[{productSlug:t.slug}]:[]}return e.products.flatMap(e=>{let r=t[e.id]??0;if(e.pricingMode===`fixed`&&e.paymentOption===`one-time`&&r>0)return[{productSlug:e.slug,quantity:r}];let i=m(n[e.id]??``);return e.pricingMode===`custom`&&e.paymentOption===`one-time`&&i!==null&&i>=u(e)?[{amountCents:i,productSlug:e.slug}]:[]})}function C({catalog:e,onContinue:t,...n}){let r=S(e,n.quantities,n.customAmounts,n.recurringProductId),i=b(e,r),a=e.products.filter(e=>e.paymentOption===`one-time`&&e.pricingMode===`custom`),o=e.products.filter(
|
|
1
|
+
import{n as e,t}from"./accent-contrast.js";import{n,t as r}from"./lockerverse-payment.js";import{createElement as i,useState as a}from"react";import{Fragment as o,jsx as s,jsxs as c}from"react/jsx-runtime";import{Dialog as l}from"@base-ui/react/dialog";import{getLockerverseMinimumCustomAmountCents as u}from"@lockerverse/sdk/checkout";const d=new Intl.NumberFormat(`en-US`,{currency:`USD`,style:`currency`}),f=/^(?:0|[1-9]\d*)(?:\.\d{1,2})?$/,p=[1e3,2500,5e3,1e4];function m(e){if(!f.test(e))return null;let t=Math.round(Number(e)*100);return Number.isSafeInteger(t)&&t>0?t:null}function h(e,t){let n=``;return t===`monthly`&&(n=`/month`),t===`annually`&&(n=`/year`),t===`every-six-months`&&(n=` every 6 months`),`${d.format(e/100)}${n}`}function g({customAmounts:e,product:t,quantities:n,recurringProductId:r,setCustomAmounts:i,setQuantities:a,setRecurringProductId:o}){let l=n[t.id]??0;if(t.pricingMode===`fixed`&&t.paymentOption===`one-time`){let e=t.minimumQuantity??1,n=Math.min(t.maximumQuantity??1/0,t.inventoryQuantity??1/0);return c(`span`,{className:`lockerverse-launcher__quantity`,children:[s(`button`,{"aria-label":`Decrease ${t.name} quantity`,disabled:l===0,onClick:()=>{o(null),a(n=>{let r=n[t.id]??0;return{...n,[t.id]:r<=e?0:r-1}})},type:`button`,children:`−`}),s(`output`,{"aria-label":`${t.name} quantity`,children:l}),s(`button`,{"aria-label":`Increase ${t.name} quantity`,disabled:n<e||l>=n,onClick:()=>{o(null),a(n=>{let r=n[t.id]??0;return{...n,[t.id]:r===0?e:r+1}})},type:`button`,children:`+`})]})}return t.pricingMode===`custom`&&t.paymentOption===`one-time`?c(`span`,{className:`lockerverse-launcher__custom-amount`,children:[s(`span`,{"aria-hidden":`true`,children:`$`}),s(`input`,{"aria-label":`${t.name} amount`,min:u(t)/100,name:`amount-${t.slug}`,onChange:e=>{o(null),i(n=>({...n,[t.id]:e.target.value}))},placeholder:`0.00`,step:`0.01`,type:`number`,value:e[t.id]??``}),t.minimumAmountCents===null?null:c(`small`,{children:[`Minimum `,d.format(t.minimumAmountCents/100)]})]}):s(`button`,{"aria-label":`Select ${t.name}`,"aria-pressed":r===t.id,className:`lockerverse-launcher__select`,onClick:()=>{a({}),i({}),o(e=>e===t.id?null:t.id)},type:`button`,children:`Select`})}function _({variant:e=`default`,...t}){let{customAmounts:n,product:r,quantities:i,recurringProductId:a}=t,o=m(n[r.id]??``),l=a===r.id||r.paymentOption===`one-time`&&(r.pricingMode===`fixed`&&(i[r.id]??0)>0||r.pricingMode===`custom`&&o!==null&&o>=u(r));return c(`article`,{className:`lockerverse-launcher__product lockerverse-launcher__product--${e}`,"data-selected":l||void 0,children:[c(`span`,{className:`lockerverse-launcher__product-copy`,children:[s(`strong`,{className:`lockerverse-launcher__product-name`,children:r.name}),r.description?s(`small`,{children:r.description}):null,r.amountCents===null?null:s(`span`,{className:`lockerverse-launcher__product-price`,children:h(r.amountCents,r.paymentOption)})]}),s(g,{...t})]})}function v({customAmounts:e,product:t,setCustomAmounts:n,setRecurringProductId:r}){let i=e[t.id]??``,a=m(i),o=p.filter(e=>e>=u(t)),l=o.includes(a??0),f=e=>{r(null),n(n=>({...n,[t.id]:e}))};return s(`div`,{className:`lockerverse-launcher__donation-option`,children:c(`fieldset`,{className:`lockerverse-launcher__donation-choices`,children:[c(`legend`,{className:`lockerverse-launcher__sr-only`,children:[t.name,` amount`]}),s(`button`,{"aria-pressed":i===``,onClick:()=>f(``),type:`button`,children:`No thanks`}),o.map(e=>s(`button`,{"aria-pressed":a===e,onClick:()=>f(String(e/100)),type:`button`,children:d.format(e/100).replace(`.00`,``)},e)),s(`label`,{className:`lockerverse-launcher__donation-other`,"data-selected":i!==``&&!l||void 0,children:s(`input`,{"aria-label":`${t.name} amount`,min:u(t)/100,name:`amount-${t.slug}`,onChange:e=>f(e.target.value),placeholder:`Other $`,step:`0.01`,type:`number`,value:l?``:i})})]})})}function y({products:e,variant:t=`default`,...n}){return s(`div`,{className:`lockerverse-launcher__product-list`,children:e.map(e=>t===`donation`?i(v,{...n,key:e.id,product:e}):i(_,{...n,key:e.id,product:e,variant:t}))})}function b(e,t){let n=0,r=0;for(let i of t){let t=e.products.find(e=>e.slug===i.productSlug);if(t){if(`quantity`in i){n+=i.quantity,r+=(t.amountCents??0)*i.quantity;continue}n+=1,r+=`amountCents`in i?i.amountCents:t.amountCents??0}}let i=e.widget.requiredShipping,a=i&&t.some(t=>e.products.some(e=>e.slug===t.productSlug&&i.triggerProductIds.includes(e.id)));return a&&(r+=e.products.find(e=>e.id===i.productId)?.amountCents??0),{amountCents:r,itemCount:n,needsShipping:a}}function x(){return s(`div`,{"aria-label":`Loading donation options`,className:`lockerverse-launcher__loading`,role:`status`,children:[0,1,2].map(e=>s(`span`,{"aria-hidden":`true`,className:`lockerverse-launcher__loading-row`},e))})}function S(e,t,n,r){if(r){let t=e.products.find(e=>e.id===r&&e.paymentOption!==`one-time`);return t?[{productSlug:t.slug}]:[]}return e.products.flatMap(e=>{let r=t[e.id]??0;if(e.pricingMode===`fixed`&&e.paymentOption===`one-time`&&r>0)return[{productSlug:e.slug,quantity:r}];let i=m(n[e.id]??``);return e.pricingMode===`custom`&&e.paymentOption===`one-time`&&i!==null&&i>=u(e)?[{amountCents:i,productSlug:e.slug}]:[]})}function C({catalog:e,onContinue:t,...n}){let r=S(e,n.quantities,n.customAmounts,n.recurringProductId),i=b(e,r),a=e.products.filter(e=>e.paymentOption===`one-time`&&e.pricingMode===`custom`),o=e.products.filter(t=>!a.includes(t)&&t.id!==e.widget.requiredShipping?.productId);return c(`form`,{className:`lockerverse-launcher__products`,onSubmit:e=>{e.preventDefault(),r.length>0&&t(r)},children:[o.length>0?s(`section`,{className:`lockerverse-launcher__section`,children:s(y,{...n,products:o})}):null,a.length>0?c(`section`,{className:`lockerverse-launcher__donation`,children:[c(`header`,{className:`lockerverse-launcher__section-header`,children:[s(`h3`,{children:`Add a donation`}),s(`p`,{children:`Choose an amount to add to this order.`})]}),s(y,{...n,products:a,variant:`donation`})]}):null,e.products.length>0?c(`footer`,{className:`lockerverse-launcher__footer`,children:[c(`p`,{"aria-live":`polite`,className:`lockerverse-launcher__summary`,children:[s(`span`,{children:i.itemCount===0?`No items selected`:`${i.itemCount} ${i.itemCount===1?`item`:`items`} selected`}),i.itemCount===0?null:s(`strong`,{children:d.format(i.amountCents/100)})]}),i.needsShipping?s(`p`,{children:`Shipping is included once per order.`}):null,s(`button`,{className:`lockerverse-launcher__continue`,disabled:r.length===0,type:`submit`,children:`Continue`})]}):null]})}function w({onEdit:e,paymentProps:t,selection:n,style:i,widget:a}){return c(`div`,{className:`lockerverse-launcher__checkout`,children:[s(`header`,{className:`lockerverse-launcher__checkout-toolbar`,children:s(`button`,{className:`lockerverse-launcher__back`,onClick:e,type:`button`,children:`Edit order`})}),s(r,{...t,selection:n,style:i,widget:a})]})}function T({catalog:e,checkout:t}){return t?c(o,{children:[s(l.Title,{className:`lockerverse-launcher__sr-only`,children:`Checkout`}),s(l.Description,{className:`lockerverse-launcher__sr-only`,children:`Review the order and complete payment.`})]}):e?c(`header`,{className:`lockerverse-launcher__header`,children:[e.community?c(`div`,{className:`lockerverse-launcher__brand`,children:[e.community.imageUrl?s(`img`,{alt:`${e.community.name} logo`,height:`28`,src:e.community.imageUrl,width:`28`}):null,s(`span`,{children:e.community.name})]}):null,s(l.Title,{className:`lockerverse-launcher__title`,children:e.widget.title??e.widget.name}),s(l.Description,{className:`lockerverse-launcher__description`,children:e.widget.description??`Choose your options, then continue to checkout.`})]}):c(`header`,{className:`lockerverse-launcher__header`,children:[s(l.Title,{className:`lockerverse-launcher__title`,children:`Donate`}),s(l.Description,{className:`lockerverse-launcher__description`,children:`Choose your options, then continue to checkout.`})]})}function E({buttonLabel:r=`Donate`,position:i=`inline`,widget:o,...u}){let[d,f]=a(null),[p,m]=a({}),[h,g]=a({}),[_,v]=a(null),{catalog:y,error:b,loading:S}=o,E=e(u.style?.[`--lockerverse-accent`]??y?.community?.accentColor??`#38d77a`),D=t(E),O={...u.style};(u.style?.[`--lockerverse-accent`]!==void 0||y?.community?.accentColor)&&(O[`--lockerverse-accent`]=E),D&&u.style?.[`--lockerverse-accent-contrast`]===void 0&&(O[`--lockerverse-accent-contrast`]=D);let k;return k=S?s(x,{}):b?c(`div`,{role:`alert`,children:[s(`p`,{children:`Unable to load donation options.`}),s(`button`,{onClick:o.refresh,type:`button`,children:`Retry`})]}):y?s(C,{catalog:y,customAmounts:p,onContinue:f,quantities:h,recurringProductId:_,setCustomAmounts:m,setQuantities:g,setRecurringProductId:v}):s(x,{}),!(S||b)&&d&&y&&(k=s(w,{onEdit:()=>f(null),paymentProps:u,selection:d,style:O,widget:o})),c(l.Root,{onOpenChange:e=>{e&&y&&u.stripeLoader===void 0&&requestAnimationFrame(()=>{n(y)})},children:[s(l.Trigger,{className:`lockerverse-launcher lockerverse-launcher--${i}`,"data-lockerverse-theme":u.theme??`dark`,style:O,children:r}),c(l.Portal,{children:[s(l.Backdrop,{className:`lockerverse-launcher__backdrop`}),s(l.Viewport,{className:`lockerverse-launcher__viewport`,children:c(l.Popup,{className:`lockerverse-launcher__dialog`,"data-lockerverse-theme":u.theme??`dark`,style:O,children:[s(T,{catalog:y,checkout:d!==null}),s(l.Close,{"aria-label":`Close donation dialog`,className:`lockerverse-launcher__close`,children:s(`span`,{"aria-hidden":`true`,children:`×`})}),k]})})]})]})}export{E as t};
|
|
2
2
|
//# sourceMappingURL=lockerverse-donate-launcher.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lockerverse-donate-launcher.js","names":[],"sources":["../src/lockerverse-donate-launcher.tsx"],"sourcesContent":["import { Dialog } from \"@base-ui/react/dialog\";\nimport {\n getLockerverseMinimumCustomAmountCents,\n type LockerverseCatalog,\n type LockerverseProduct,\n} from \"@lockerverse/sdk/checkout\";\nimport {\n type Dispatch,\n type ReactNode,\n type SetStateAction,\n useState,\n} from \"react\";\nimport { getAccentContrast, normalizeAccentColor } from \"./accent-contrast.ts\";\nimport { LockerversePayment } from \"./lockerverse-payment.tsx\";\nimport { preloadLockerversePayment } from \"./payment-form.tsx\";\nimport type {\n LockerverseDonateLauncherProps,\n LockerversePaymentProps,\n LockerversePaymentSelectionItem,\n LockerversePaymentStyle,\n} from \"./types.ts\";\nimport type { UseLockerverseWidgetResult } from \"./use-lockerverse-widget.ts\";\n\nconst usd = new Intl.NumberFormat(\"en-US\", {\n currency: \"USD\",\n style: \"currency\",\n});\nconst decimalAmountPattern = /^(?:0|[1-9]\\d*)(?:\\.\\d{1,2})?$/;\nconst suggestedDonationAmountsCents = [1000, 2500, 5000, 10_000];\n\nfunction parseAmountCents(value: string) {\n if (!decimalAmountPattern.test(value)) {\n return null;\n }\n const amountCents = Math.round(Number(value) * 100);\n return Number.isSafeInteger(amountCents) && amountCents > 0\n ? amountCents\n : null;\n}\n\nfunction formatProductPrice(\n amountCents: number,\n paymentOption: \"one-time\" | \"monthly\" | \"annually\" | \"every-six-months\"\n) {\n let cadence = \"\";\n if (paymentOption === \"monthly\") {\n cadence = \"/month\";\n }\n if (paymentOption === \"annually\") {\n cadence = \"/year\";\n }\n if (paymentOption === \"every-six-months\") {\n cadence = \" every 6 months\";\n }\n return `${usd.format(amountCents / 100)}${cadence}`;\n}\n\ntype LauncherProductControlProps = {\n customAmounts: Record<string, string>;\n product: LockerverseProduct;\n quantities: Record<string, number>;\n recurringProductId: string | null;\n setCustomAmounts: Dispatch<SetStateAction<Record<string, string>>>;\n setQuantities: Dispatch<SetStateAction<Record<string, number>>>;\n setRecurringProductId: Dispatch<SetStateAction<string | null>>;\n};\n\nfunction LauncherProductControl({\n customAmounts,\n product,\n quantities,\n recurringProductId,\n setCustomAmounts,\n setQuantities,\n setRecurringProductId,\n}: LauncherProductControlProps) {\n const quantity = quantities[product.id] ?? 0;\n if (product.pricingMode === \"fixed\" && product.paymentOption === \"one-time\") {\n const minimum = product.minimumQuantity ?? 1;\n const maximum = Math.min(\n product.maximumQuantity ?? Number.POSITIVE_INFINITY,\n product.inventoryQuantity ?? Number.POSITIVE_INFINITY\n );\n return (\n <span className=\"lockerverse-launcher__quantity\">\n <button\n aria-label={`Decrease ${product.name} quantity`}\n disabled={quantity === 0}\n onClick={() => {\n setRecurringProductId(null);\n setQuantities((current) => {\n const currentQuantity = current[product.id] ?? 0;\n return {\n ...current,\n [product.id]:\n currentQuantity <= minimum ? 0 : currentQuantity - 1,\n };\n });\n }}\n type=\"button\"\n >\n −\n </button>\n <output aria-label={`${product.name} quantity`}>{quantity}</output>\n <button\n aria-label={`Increase ${product.name} quantity`}\n disabled={maximum < minimum || quantity >= maximum}\n onClick={() => {\n setRecurringProductId(null);\n setQuantities((current) => {\n const currentQuantity = current[product.id] ?? 0;\n return {\n ...current,\n [product.id]:\n currentQuantity === 0 ? minimum : currentQuantity + 1,\n };\n });\n }}\n type=\"button\"\n >\n +\n </button>\n </span>\n );\n }\n\n if (\n product.pricingMode === \"custom\" &&\n product.paymentOption === \"one-time\"\n ) {\n return (\n <span className=\"lockerverse-launcher__custom-amount\">\n <span aria-hidden=\"true\">$</span>\n <input\n aria-label={`${product.name} amount`}\n min={getLockerverseMinimumCustomAmountCents(product) / 100}\n name={`amount-${product.slug}`}\n onChange={(event) => {\n setRecurringProductId(null);\n setCustomAmounts((current) => ({\n ...current,\n [product.id]: event.target.value,\n }));\n }}\n placeholder=\"0.00\"\n step=\"0.01\"\n type=\"number\"\n value={customAmounts[product.id] ?? \"\"}\n />\n {product.minimumAmountCents === null ? null : (\n <small>Minimum {usd.format(product.minimumAmountCents / 100)}</small>\n )}\n </span>\n );\n }\n\n return (\n <button\n aria-label={`Select ${product.name}`}\n aria-pressed={recurringProductId === product.id}\n className=\"lockerverse-launcher__select\"\n onClick={() => {\n setQuantities({});\n setCustomAmounts({});\n setRecurringProductId((current) =>\n current === product.id ? null : product.id\n );\n }}\n type=\"button\"\n >\n Select\n </button>\n );\n}\n\ntype LauncherProductOptionProps = LauncherProductControlProps & {\n variant?: \"default\" | \"donation\";\n};\n\nfunction LauncherProductOption({\n variant = \"default\",\n ...props\n}: LauncherProductOptionProps) {\n const { customAmounts, product, quantities, recurringProductId } = props;\n const customAmount = parseAmountCents(customAmounts[product.id] ?? \"\");\n const isSelected =\n recurringProductId === product.id ||\n (product.paymentOption === \"one-time\" &&\n ((product.pricingMode === \"fixed\" && (quantities[product.id] ?? 0) > 0) ||\n (product.pricingMode === \"custom\" &&\n customAmount !== null &&\n customAmount >= getLockerverseMinimumCustomAmountCents(product))));\n return (\n <article\n className={`lockerverse-launcher__product lockerverse-launcher__product--${variant}`}\n data-selected={isSelected || undefined}\n >\n <span className=\"lockerverse-launcher__product-copy\">\n <strong className=\"lockerverse-launcher__product-name\">\n {product.name}\n </strong>\n {product.description ? <small>{product.description}</small> : null}\n {product.amountCents === null ? null : (\n <span className=\"lockerverse-launcher__product-price\">\n {formatProductPrice(product.amountCents, product.paymentOption)}\n </span>\n )}\n </span>\n <LauncherProductControl {...props} />\n </article>\n );\n}\n\nfunction LauncherDonationOption({\n customAmounts,\n product,\n setCustomAmounts,\n setRecurringProductId,\n}: LauncherProductControlProps) {\n const amount = customAmounts[product.id] ?? \"\";\n const amountCents = parseAmountCents(amount);\n const suggestions = suggestedDonationAmountsCents.filter(\n (suggestion) =>\n suggestion >= getLockerverseMinimumCustomAmountCents(product)\n );\n const isSuggestedAmount = suggestions.includes(amountCents ?? 0);\n const setAmount = (value: string) => {\n setRecurringProductId(null);\n setCustomAmounts((current) => ({\n ...current,\n [product.id]: value,\n }));\n };\n\n return (\n <div className=\"lockerverse-launcher__donation-option\">\n <fieldset className=\"lockerverse-launcher__donation-choices\">\n <legend className=\"lockerverse-launcher__sr-only\">\n {product.name} amount\n </legend>\n <button\n aria-pressed={amount === \"\"}\n onClick={() => setAmount(\"\")}\n type=\"button\"\n >\n No thanks\n </button>\n {suggestions.map((suggestion) => (\n <button\n aria-pressed={amountCents === suggestion}\n key={suggestion}\n onClick={() => setAmount(String(suggestion / 100))}\n type=\"button\"\n >\n {usd.format(suggestion / 100).replace(\".00\", \"\")}\n </button>\n ))}\n <label\n className=\"lockerverse-launcher__donation-other\"\n data-selected={amount !== \"\" && !isSuggestedAmount ? true : undefined}\n >\n <input\n aria-label={`${product.name} amount`}\n min={getLockerverseMinimumCustomAmountCents(product) / 100}\n name={`amount-${product.slug}`}\n onChange={(event) => setAmount(event.target.value)}\n placeholder=\"Other $\"\n step=\"0.01\"\n type=\"number\"\n value={isSuggestedAmount ? \"\" : amount}\n />\n </label>\n </fieldset>\n </div>\n );\n}\n\ntype LauncherProductListProps = Omit<LauncherProductControlProps, \"product\"> & {\n products: LockerverseProduct[];\n variant?: LauncherProductOptionProps[\"variant\"];\n};\n\nfunction LauncherProductList({\n products,\n variant = \"default\",\n ...controlProps\n}: LauncherProductListProps) {\n return (\n <div className=\"lockerverse-launcher__product-list\">\n {products.map((product) =>\n variant === \"donation\" ? (\n <LauncherDonationOption\n {...controlProps}\n key={product.id}\n product={product}\n />\n ) : (\n <LauncherProductOption\n {...controlProps}\n key={product.id}\n product={product}\n variant={variant}\n />\n )\n )}\n </div>\n );\n}\n\nfunction getSelectionSummary(\n catalog: LockerverseCatalog,\n selection: LockerversePaymentSelectionItem[]\n) {\n let itemCount = 0;\n let amountCents = 0;\n for (const item of selection) {\n const product = catalog.products.find(\n (candidate) => candidate.slug === item.productSlug\n );\n if (!product) {\n continue;\n }\n if (\"quantity\" in item) {\n itemCount += item.quantity;\n amountCents += (product.amountCents ?? 0) * item.quantity;\n continue;\n }\n itemCount += 1;\n amountCents +=\n \"amountCents\" in item ? item.amountCents : (product.amountCents ?? 0);\n }\n return { amountCents, itemCount };\n}\n\nfunction LauncherLoading() {\n return (\n <div\n aria-label=\"Loading donation options\"\n className=\"lockerverse-launcher__loading\"\n role=\"status\"\n >\n {[0, 1, 2].map((item) => (\n <span\n aria-hidden=\"true\"\n className=\"lockerverse-launcher__loading-row\"\n key={item}\n />\n ))}\n </div>\n );\n}\n\nfunction createLauncherSelection(\n catalog: LockerverseCatalog,\n quantities: Record<string, number>,\n customAmounts: Record<string, string>,\n recurringProductId: string | null\n): LockerversePaymentSelectionItem[] {\n if (recurringProductId) {\n const product = catalog.products.find(\n (candidate) =>\n candidate.id === recurringProductId &&\n candidate.paymentOption !== \"one-time\"\n );\n return product ? [{ productSlug: product.slug }] : [];\n }\n\n return catalog.products.flatMap(\n (product): LockerversePaymentSelectionItem[] => {\n const quantity = quantities[product.id] ?? 0;\n if (\n product.pricingMode === \"fixed\" &&\n product.paymentOption === \"one-time\" &&\n quantity > 0\n ) {\n return [{ productSlug: product.slug, quantity }];\n }\n const amountCents = parseAmountCents(customAmounts[product.id] ?? \"\");\n if (\n product.pricingMode === \"custom\" &&\n product.paymentOption === \"one-time\" &&\n amountCents !== null &&\n amountCents >= getLockerverseMinimumCustomAmountCents(product)\n ) {\n return [{ amountCents, productSlug: product.slug }];\n }\n return [];\n }\n );\n}\n\ntype LauncherSelectionStateProps = Omit<LauncherProductControlProps, \"product\">;\n\ntype LauncherCatalogProps = LauncherSelectionStateProps & {\n catalog: LockerverseCatalog;\n onContinue: (selection: LockerversePaymentSelectionItem[]) => void;\n};\n\nfunction LauncherCatalog({\n catalog,\n onContinue,\n ...selectionState\n}: LauncherCatalogProps) {\n const draftSelection = createLauncherSelection(\n catalog,\n selectionState.quantities,\n selectionState.customAmounts,\n selectionState.recurringProductId\n );\n const summary = getSelectionSummary(catalog, draftSelection);\n const donationProducts = catalog.products.filter(\n (product) =>\n product.paymentOption === \"one-time\" && product.pricingMode === \"custom\"\n );\n const orderProducts = catalog.products.filter(\n (product) => !donationProducts.includes(product)\n );\n\n return (\n <form\n className=\"lockerverse-launcher__products\"\n onSubmit={(event) => {\n event.preventDefault();\n if (draftSelection.length > 0) {\n onContinue(draftSelection);\n }\n }}\n >\n {orderProducts.length > 0 ? (\n <section className=\"lockerverse-launcher__section\">\n <LauncherProductList {...selectionState} products={orderProducts} />\n </section>\n ) : null}\n {donationProducts.length > 0 ? (\n <section className=\"lockerverse-launcher__donation\">\n <header className=\"lockerverse-launcher__section-header\">\n <h3>Add a donation</h3>\n <p>Choose an amount to add to this order.</p>\n </header>\n <LauncherProductList\n {...selectionState}\n products={donationProducts}\n variant=\"donation\"\n />\n </section>\n ) : null}\n {catalog.products.length > 0 ? (\n <footer className=\"lockerverse-launcher__footer\">\n <p aria-live=\"polite\" className=\"lockerverse-launcher__summary\">\n <span>\n {summary.itemCount === 0\n ? \"No items selected\"\n : `${summary.itemCount} ${summary.itemCount === 1 ? \"item\" : \"items\"} selected`}\n </span>\n {summary.itemCount === 0 ? null : (\n <strong>{usd.format(summary.amountCents / 100)}</strong>\n )}\n </p>\n <button\n className=\"lockerverse-launcher__continue\"\n disabled={draftSelection.length === 0}\n type=\"submit\"\n >\n Continue\n </button>\n </footer>\n ) : null}\n </form>\n );\n}\n\ntype LauncherPaymentProps = Omit<\n LockerversePaymentProps,\n \"selection\" | \"widget\"\n>;\n\ntype LauncherCheckoutProps = {\n onEdit: () => void;\n paymentProps: LauncherPaymentProps;\n selection: LockerversePaymentSelectionItem[];\n style: LockerversePaymentStyle;\n widget: UseLockerverseWidgetResult;\n};\n\nfunction LauncherCheckout({\n onEdit,\n paymentProps,\n selection,\n style,\n widget,\n}: LauncherCheckoutProps) {\n return (\n <div className=\"lockerverse-launcher__checkout\">\n <header className=\"lockerverse-launcher__checkout-toolbar\">\n <button\n className=\"lockerverse-launcher__back\"\n onClick={onEdit}\n type=\"button\"\n >\n Edit order\n </button>\n </header>\n <LockerversePayment\n {...paymentProps}\n selection={selection}\n style={style}\n widget={widget}\n />\n </div>\n );\n}\n\nfunction LauncherDialogHeading({\n catalog,\n checkout,\n}: {\n catalog: LockerverseCatalog | null;\n checkout: boolean;\n}) {\n if (checkout) {\n return (\n <>\n <Dialog.Title className=\"lockerverse-launcher__sr-only\">\n Checkout\n </Dialog.Title>\n <Dialog.Description className=\"lockerverse-launcher__sr-only\">\n Review the order and complete payment.\n </Dialog.Description>\n </>\n );\n }\n\n if (!catalog) {\n return (\n <header className=\"lockerverse-launcher__header\">\n <Dialog.Title className=\"lockerverse-launcher__title\">\n Donate\n </Dialog.Title>\n <Dialog.Description className=\"lockerverse-launcher__description\">\n Choose your options, then continue to checkout.\n </Dialog.Description>\n </header>\n );\n }\n\n return (\n <header className=\"lockerverse-launcher__header\">\n {catalog.community ? (\n <div className=\"lockerverse-launcher__brand\">\n {catalog.community.imageUrl ? (\n <img\n alt={`${catalog.community.name} logo`}\n height=\"28\"\n src={catalog.community.imageUrl}\n width=\"28\"\n />\n ) : null}\n <span>{catalog.community.name}</span>\n </div>\n ) : null}\n <Dialog.Title className=\"lockerverse-launcher__title\">\n {catalog.widget.title ?? catalog.widget.name}\n </Dialog.Title>\n <Dialog.Description className=\"lockerverse-launcher__description\">\n {catalog.widget.description ??\n \"Choose your options, then continue to checkout.\"}\n </Dialog.Description>\n </header>\n );\n}\n\nexport function LockerverseDonateLauncher({\n buttonLabel = \"Donate\",\n position = \"inline\",\n widget,\n ...paymentProps\n}: LockerverseDonateLauncherProps) {\n const [selection, setSelection] = useState<\n LockerversePaymentSelectionItem[] | null\n >(null);\n const [customAmounts, setCustomAmounts] = useState<Record<string, string>>(\n {}\n );\n const [quantities, setQuantities] = useState<Record<string, number>>({});\n const [recurringProductId, setRecurringProductId] = useState<string | null>(\n null\n );\n const { catalog, error, loading } = widget;\n const accent = normalizeAccentColor(\n paymentProps.style?.[\"--lockerverse-accent\"] ??\n catalog?.community?.accentColor ??\n \"#38d77a\"\n );\n const accentContrast = getAccentContrast(accent);\n const launcherStyle: LockerversePaymentStyle = { ...paymentProps.style };\n if (\n paymentProps.style?.[\"--lockerverse-accent\"] !== undefined ||\n catalog?.community?.accentColor\n ) {\n launcherStyle[\"--lockerverse-accent\"] = accent;\n }\n if (\n accentContrast &&\n paymentProps.style?.[\"--lockerverse-accent-contrast\"] === undefined\n ) {\n launcherStyle[\"--lockerverse-accent-contrast\"] = accentContrast;\n }\n\n let content: ReactNode;\n if (loading) {\n content = <LauncherLoading />;\n } else if (error) {\n content = (\n <div role=\"alert\">\n <p>Unable to load donation options.</p>\n <button onClick={widget.refresh} type=\"button\">\n Retry\n </button>\n </div>\n );\n } else if (catalog) {\n content = (\n <LauncherCatalog\n catalog={catalog}\n customAmounts={customAmounts}\n onContinue={setSelection}\n quantities={quantities}\n recurringProductId={recurringProductId}\n setCustomAmounts={setCustomAmounts}\n setQuantities={setQuantities}\n setRecurringProductId={setRecurringProductId}\n />\n );\n } else {\n content = <LauncherLoading />;\n }\n if (!(loading || error) && selection && catalog) {\n content = (\n <LauncherCheckout\n onEdit={() => setSelection(null)}\n paymentProps={paymentProps}\n selection={selection}\n style={launcherStyle}\n widget={widget}\n />\n );\n }\n\n return (\n <Dialog.Root\n onOpenChange={(open) => {\n if (open && catalog && paymentProps.stripeLoader === undefined) {\n requestAnimationFrame(() => {\n preloadLockerversePayment(catalog);\n });\n }\n }}\n >\n <Dialog.Trigger\n className={`lockerverse-launcher lockerverse-launcher--${position}`}\n data-lockerverse-theme={paymentProps.theme ?? \"dark\"}\n style={launcherStyle}\n >\n {buttonLabel}\n </Dialog.Trigger>\n <Dialog.Portal>\n <Dialog.Backdrop className=\"lockerverse-launcher__backdrop\" />\n <Dialog.Viewport className=\"lockerverse-launcher__viewport\">\n <Dialog.Popup\n className=\"lockerverse-launcher__dialog\"\n data-lockerverse-theme={paymentProps.theme ?? \"dark\"}\n style={launcherStyle}\n >\n <LauncherDialogHeading\n catalog={catalog}\n checkout={selection !== null}\n />\n <Dialog.Close\n aria-label=\"Close donation dialog\"\n className=\"lockerverse-launcher__close\"\n >\n <span aria-hidden=\"true\">×</span>\n </Dialog.Close>\n {content}\n </Dialog.Popup>\n </Dialog.Viewport>\n </Dialog.Portal>\n </Dialog.Root>\n );\n}\n"],"mappings":"gVAuBA,MAAM,EAAM,IAAI,KAAK,aAAa,QAAS,CACzC,SAAU,MACV,MAAO,UACT,CAAC,EACK,EAAuB,iCACvB,EAAgC,CAAC,IAAM,KAAM,IAAM,GAAM,EAE/D,SAAS,EAAiB,EAAe,CACvC,GAAI,CAAC,EAAqB,KAAK,CAAK,EAClC,OAAO,KAET,IAAM,EAAc,KAAK,MAAM,OAAO,CAAK,EAAI,GAAG,EAClD,OAAO,OAAO,cAAc,CAAW,GAAK,EAAc,EACtD,EACA,IACN,CAEA,SAAS,EACP,EACA,EACA,CACA,IAAI,EAAU,GAUd,OATI,IAAkB,YACpB,EAAU,UAER,IAAkB,aACpB,EAAU,SAER,IAAkB,qBACpB,EAAU,mBAEL,GAAG,EAAI,OAAO,EAAc,GAAG,IAAI,GAC5C,CAYA,SAAS,EAAuB,CAC9B,gBACA,UACA,aACA,qBACA,mBACA,gBACA,yBAC8B,CAC9B,IAAM,EAAW,EAAW,EAAQ,KAAO,EAC3C,GAAI,EAAQ,cAAgB,SAAW,EAAQ,gBAAkB,WAAY,CAC3E,IAAM,EAAU,EAAQ,iBAAmB,EAC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C,IACzD,yBAAwB,EAAa,OAAS,OAC9C,MAAO,EAEN,SAAA,CACa,CAAA,EAChB,EAAC,EAAO,OAAR,CAAA,SAAA,CACE,EAAC,EAAO,SAAR,CAAiB,UAAU,gCAAkC,CAAA,EAC7D,EAAC,EAAO,SAAR,CAAiB,UAAU,iCACzB,SAAA,EAAC,EAAO,MAAR,CACE,UAAU,+BACV,yBAAwB,EAAa,OAAS,OAC9C,MAAO,EAHT,SAAA,CAKE,EAAC,EAAD,CACW,UACT,SAAU,IAAc,IACzB,CAAA,EACD,EAAC,EAAO,MAAR,CACE,aAAW,wBACX,UAAU,8BAEV,SAAA,EAAC,OAAD,CAAM,cAAY,OAAO,SAAA,GAAO,CAAA,CACpB,CAAA,EACb,CACW,GACC,CAAA,CACJ,CAAA,CAAA,CACJ,GAEjB"}
|
|
1
|
+
{"version":3,"file":"lockerverse-donate-launcher.js","names":[],"sources":["../src/lockerverse-donate-launcher.tsx"],"sourcesContent":["import { Dialog } from \"@base-ui/react/dialog\";\nimport {\n getLockerverseMinimumCustomAmountCents,\n type LockerverseCatalog,\n type LockerverseProduct,\n} from \"@lockerverse/sdk/checkout\";\nimport {\n type Dispatch,\n type ReactNode,\n type SetStateAction,\n useState,\n} from \"react\";\nimport { getAccentContrast, normalizeAccentColor } from \"./accent-contrast.ts\";\nimport { LockerversePayment } from \"./lockerverse-payment.tsx\";\nimport { preloadLockerversePayment } from \"./payment-form.tsx\";\nimport type {\n LockerverseDonateLauncherProps,\n LockerversePaymentProps,\n LockerversePaymentSelectionItem,\n LockerversePaymentStyle,\n} from \"./types.ts\";\nimport type { UseLockerverseWidgetResult } from \"./use-lockerverse-widget.ts\";\n\nconst usd = new Intl.NumberFormat(\"en-US\", {\n currency: \"USD\",\n style: \"currency\",\n});\nconst decimalAmountPattern = /^(?:0|[1-9]\\d*)(?:\\.\\d{1,2})?$/;\nconst suggestedDonationAmountsCents = [1000, 2500, 5000, 10_000];\n\nfunction parseAmountCents(value: string) {\n if (!decimalAmountPattern.test(value)) {\n return null;\n }\n const amountCents = Math.round(Number(value) * 100);\n return Number.isSafeInteger(amountCents) && amountCents > 0\n ? amountCents\n : null;\n}\n\nfunction formatProductPrice(\n amountCents: number,\n paymentOption: \"one-time\" | \"monthly\" | \"annually\" | \"every-six-months\"\n) {\n let cadence = \"\";\n if (paymentOption === \"monthly\") {\n cadence = \"/month\";\n }\n if (paymentOption === \"annually\") {\n cadence = \"/year\";\n }\n if (paymentOption === \"every-six-months\") {\n cadence = \" every 6 months\";\n }\n return `${usd.format(amountCents / 100)}${cadence}`;\n}\n\ntype LauncherProductControlProps = {\n customAmounts: Record<string, string>;\n product: LockerverseProduct;\n quantities: Record<string, number>;\n recurringProductId: string | null;\n setCustomAmounts: Dispatch<SetStateAction<Record<string, string>>>;\n setQuantities: Dispatch<SetStateAction<Record<string, number>>>;\n setRecurringProductId: Dispatch<SetStateAction<string | null>>;\n};\n\nfunction LauncherProductControl({\n customAmounts,\n product,\n quantities,\n recurringProductId,\n setCustomAmounts,\n setQuantities,\n setRecurringProductId,\n}: LauncherProductControlProps) {\n const quantity = quantities[product.id] ?? 0;\n if (product.pricingMode === \"fixed\" && product.paymentOption === \"one-time\") {\n const minimum = product.minimumQuantity ?? 1;\n const maximum = Math.min(\n product.maximumQuantity ?? Number.POSITIVE_INFINITY,\n product.inventoryQuantity ?? Number.POSITIVE_INFINITY\n );\n return (\n <span className=\"lockerverse-launcher__quantity\">\n <button\n aria-label={`Decrease ${product.name} quantity`}\n disabled={quantity === 0}\n onClick={() => {\n setRecurringProductId(null);\n setQuantities((current) => {\n const currentQuantity = current[product.id] ?? 0;\n return {\n ...current,\n [product.id]:\n currentQuantity <= minimum ? 0 : currentQuantity - 1,\n };\n });\n }}\n type=\"button\"\n >\n −\n </button>\n <output aria-label={`${product.name} quantity`}>{quantity}</output>\n <button\n aria-label={`Increase ${product.name} quantity`}\n disabled={maximum < minimum || quantity >= maximum}\n onClick={() => {\n setRecurringProductId(null);\n setQuantities((current) => {\n const currentQuantity = current[product.id] ?? 0;\n return {\n ...current,\n [product.id]:\n currentQuantity === 0 ? minimum : currentQuantity + 1,\n };\n });\n }}\n type=\"button\"\n >\n +\n </button>\n </span>\n );\n }\n\n if (\n product.pricingMode === \"custom\" &&\n product.paymentOption === \"one-time\"\n ) {\n return (\n <span className=\"lockerverse-launcher__custom-amount\">\n <span aria-hidden=\"true\">$</span>\n <input\n aria-label={`${product.name} amount`}\n min={getLockerverseMinimumCustomAmountCents(product) / 100}\n name={`amount-${product.slug}`}\n onChange={(event) => {\n setRecurringProductId(null);\n setCustomAmounts((current) => ({\n ...current,\n [product.id]: event.target.value,\n }));\n }}\n placeholder=\"0.00\"\n step=\"0.01\"\n type=\"number\"\n value={customAmounts[product.id] ?? \"\"}\n />\n {product.minimumAmountCents === null ? null : (\n <small>Minimum {usd.format(product.minimumAmountCents / 100)}</small>\n )}\n </span>\n );\n }\n\n return (\n <button\n aria-label={`Select ${product.name}`}\n aria-pressed={recurringProductId === product.id}\n className=\"lockerverse-launcher__select\"\n onClick={() => {\n setQuantities({});\n setCustomAmounts({});\n setRecurringProductId((current) =>\n current === product.id ? null : product.id\n );\n }}\n type=\"button\"\n >\n Select\n </button>\n );\n}\n\ntype LauncherProductOptionProps = LauncherProductControlProps & {\n variant?: \"default\" | \"donation\";\n};\n\nfunction LauncherProductOption({\n variant = \"default\",\n ...props\n}: LauncherProductOptionProps) {\n const { customAmounts, product, quantities, recurringProductId } = props;\n const customAmount = parseAmountCents(customAmounts[product.id] ?? \"\");\n const isSelected =\n recurringProductId === product.id ||\n (product.paymentOption === \"one-time\" &&\n ((product.pricingMode === \"fixed\" && (quantities[product.id] ?? 0) > 0) ||\n (product.pricingMode === \"custom\" &&\n customAmount !== null &&\n customAmount >= getLockerverseMinimumCustomAmountCents(product))));\n return (\n <article\n className={`lockerverse-launcher__product lockerverse-launcher__product--${variant}`}\n data-selected={isSelected || undefined}\n >\n <span className=\"lockerverse-launcher__product-copy\">\n <strong className=\"lockerverse-launcher__product-name\">\n {product.name}\n </strong>\n {product.description ? <small>{product.description}</small> : null}\n {product.amountCents === null ? null : (\n <span className=\"lockerverse-launcher__product-price\">\n {formatProductPrice(product.amountCents, product.paymentOption)}\n </span>\n )}\n </span>\n <LauncherProductControl {...props} />\n </article>\n );\n}\n\nfunction LauncherDonationOption({\n customAmounts,\n product,\n setCustomAmounts,\n setRecurringProductId,\n}: LauncherProductControlProps) {\n const amount = customAmounts[product.id] ?? \"\";\n const amountCents = parseAmountCents(amount);\n const suggestions = suggestedDonationAmountsCents.filter(\n (suggestion) =>\n suggestion >= getLockerverseMinimumCustomAmountCents(product)\n );\n const isSuggestedAmount = suggestions.includes(amountCents ?? 0);\n const setAmount = (value: string) => {\n setRecurringProductId(null);\n setCustomAmounts((current) => ({\n ...current,\n [product.id]: value,\n }));\n };\n\n return (\n <div className=\"lockerverse-launcher__donation-option\">\n <fieldset className=\"lockerverse-launcher__donation-choices\">\n <legend className=\"lockerverse-launcher__sr-only\">\n {product.name} amount\n </legend>\n <button\n aria-pressed={amount === \"\"}\n onClick={() => setAmount(\"\")}\n type=\"button\"\n >\n No thanks\n </button>\n {suggestions.map((suggestion) => (\n <button\n aria-pressed={amountCents === suggestion}\n key={suggestion}\n onClick={() => setAmount(String(suggestion / 100))}\n type=\"button\"\n >\n {usd.format(suggestion / 100).replace(\".00\", \"\")}\n </button>\n ))}\n <label\n className=\"lockerverse-launcher__donation-other\"\n data-selected={amount !== \"\" && !isSuggestedAmount ? true : undefined}\n >\n <input\n aria-label={`${product.name} amount`}\n min={getLockerverseMinimumCustomAmountCents(product) / 100}\n name={`amount-${product.slug}`}\n onChange={(event) => setAmount(event.target.value)}\n placeholder=\"Other $\"\n step=\"0.01\"\n type=\"number\"\n value={isSuggestedAmount ? \"\" : amount}\n />\n </label>\n </fieldset>\n </div>\n );\n}\n\ntype LauncherProductListProps = Omit<LauncherProductControlProps, \"product\"> & {\n products: LockerverseProduct[];\n variant?: LauncherProductOptionProps[\"variant\"];\n};\n\nfunction LauncherProductList({\n products,\n variant = \"default\",\n ...controlProps\n}: LauncherProductListProps) {\n return (\n <div className=\"lockerverse-launcher__product-list\">\n {products.map((product) =>\n variant === \"donation\" ? (\n <LauncherDonationOption\n {...controlProps}\n key={product.id}\n product={product}\n />\n ) : (\n <LauncherProductOption\n {...controlProps}\n key={product.id}\n product={product}\n variant={variant}\n />\n )\n )}\n </div>\n );\n}\n\nfunction getSelectionSummary(\n catalog: LockerverseCatalog,\n selection: LockerversePaymentSelectionItem[]\n) {\n let itemCount = 0;\n let amountCents = 0;\n for (const item of selection) {\n const product = catalog.products.find(\n (candidate) => candidate.slug === item.productSlug\n );\n if (!product) {\n continue;\n }\n if (\"quantity\" in item) {\n itemCount += item.quantity;\n amountCents += (product.amountCents ?? 0) * item.quantity;\n continue;\n }\n itemCount += 1;\n amountCents +=\n \"amountCents\" in item ? item.amountCents : (product.amountCents ?? 0);\n }\n const shipping = catalog.widget.requiredShipping;\n const needsShipping =\n shipping &&\n selection.some((item) =>\n catalog.products.some(\n (product) =>\n product.slug === item.productSlug &&\n shipping.triggerProductIds.includes(product.id)\n )\n );\n if (needsShipping) {\n amountCents +=\n catalog.products.find((product) => product.id === shipping.productId)\n ?.amountCents ?? 0;\n }\n return { amountCents, itemCount, needsShipping };\n}\n\nfunction LauncherLoading() {\n return (\n <div\n aria-label=\"Loading donation options\"\n className=\"lockerverse-launcher__loading\"\n role=\"status\"\n >\n {[0, 1, 2].map((item) => (\n <span\n aria-hidden=\"true\"\n className=\"lockerverse-launcher__loading-row\"\n key={item}\n />\n ))}\n </div>\n );\n}\n\nfunction createLauncherSelection(\n catalog: LockerverseCatalog,\n quantities: Record<string, number>,\n customAmounts: Record<string, string>,\n recurringProductId: string | null\n): LockerversePaymentSelectionItem[] {\n if (recurringProductId) {\n const product = catalog.products.find(\n (candidate) =>\n candidate.id === recurringProductId &&\n candidate.paymentOption !== \"one-time\"\n );\n return product ? [{ productSlug: product.slug }] : [];\n }\n\n return catalog.products.flatMap(\n (product): LockerversePaymentSelectionItem[] => {\n const quantity = quantities[product.id] ?? 0;\n if (\n product.pricingMode === \"fixed\" &&\n product.paymentOption === \"one-time\" &&\n quantity > 0\n ) {\n return [{ productSlug: product.slug, quantity }];\n }\n const amountCents = parseAmountCents(customAmounts[product.id] ?? \"\");\n if (\n product.pricingMode === \"custom\" &&\n product.paymentOption === \"one-time\" &&\n amountCents !== null &&\n amountCents >= getLockerverseMinimumCustomAmountCents(product)\n ) {\n return [{ amountCents, productSlug: product.slug }];\n }\n return [];\n }\n );\n}\n\ntype LauncherSelectionStateProps = Omit<LauncherProductControlProps, \"product\">;\n\ntype LauncherCatalogProps = LauncherSelectionStateProps & {\n catalog: LockerverseCatalog;\n onContinue: (selection: LockerversePaymentSelectionItem[]) => void;\n};\n\nfunction LauncherCatalog({\n catalog,\n onContinue,\n ...selectionState\n}: LauncherCatalogProps) {\n const draftSelection = createLauncherSelection(\n catalog,\n selectionState.quantities,\n selectionState.customAmounts,\n selectionState.recurringProductId\n );\n const summary = getSelectionSummary(catalog, draftSelection);\n const donationProducts = catalog.products.filter(\n (product) =>\n product.paymentOption === \"one-time\" && product.pricingMode === \"custom\"\n );\n const orderProducts = catalog.products.filter(\n (product) =>\n !donationProducts.includes(product) &&\n product.id !== catalog.widget.requiredShipping?.productId\n );\n\n return (\n <form\n className=\"lockerverse-launcher__products\"\n onSubmit={(event) => {\n event.preventDefault();\n if (draftSelection.length > 0) {\n onContinue(draftSelection);\n }\n }}\n >\n {orderProducts.length > 0 ? (\n <section className=\"lockerverse-launcher__section\">\n <LauncherProductList {...selectionState} products={orderProducts} />\n </section>\n ) : null}\n {donationProducts.length > 0 ? (\n <section className=\"lockerverse-launcher__donation\">\n <header className=\"lockerverse-launcher__section-header\">\n <h3>Add a donation</h3>\n <p>Choose an amount to add to this order.</p>\n </header>\n <LauncherProductList\n {...selectionState}\n products={donationProducts}\n variant=\"donation\"\n />\n </section>\n ) : null}\n {catalog.products.length > 0 ? (\n <footer className=\"lockerverse-launcher__footer\">\n <p aria-live=\"polite\" className=\"lockerverse-launcher__summary\">\n <span>\n {summary.itemCount === 0\n ? \"No items selected\"\n : `${summary.itemCount} ${summary.itemCount === 1 ? \"item\" : \"items\"} selected`}\n </span>\n {summary.itemCount === 0 ? null : (\n <strong>{usd.format(summary.amountCents / 100)}</strong>\n )}\n </p>\n {summary.needsShipping ? (\n <p>Shipping is included once per order.</p>\n ) : null}\n <button\n className=\"lockerverse-launcher__continue\"\n disabled={draftSelection.length === 0}\n type=\"submit\"\n >\n Continue\n </button>\n </footer>\n ) : null}\n </form>\n );\n}\n\ntype LauncherPaymentProps = Omit<\n LockerversePaymentProps,\n \"selection\" | \"widget\"\n>;\n\ntype LauncherCheckoutProps = {\n onEdit: () => void;\n paymentProps: LauncherPaymentProps;\n selection: LockerversePaymentSelectionItem[];\n style: LockerversePaymentStyle;\n widget: UseLockerverseWidgetResult;\n};\n\nfunction LauncherCheckout({\n onEdit,\n paymentProps,\n selection,\n style,\n widget,\n}: LauncherCheckoutProps) {\n return (\n <div className=\"lockerverse-launcher__checkout\">\n <header className=\"lockerverse-launcher__checkout-toolbar\">\n <button\n className=\"lockerverse-launcher__back\"\n onClick={onEdit}\n type=\"button\"\n >\n Edit order\n </button>\n </header>\n <LockerversePayment\n {...paymentProps}\n selection={selection}\n style={style}\n widget={widget}\n />\n </div>\n );\n}\n\nfunction LauncherDialogHeading({\n catalog,\n checkout,\n}: {\n catalog: LockerverseCatalog | null;\n checkout: boolean;\n}) {\n if (checkout) {\n return (\n <>\n <Dialog.Title className=\"lockerverse-launcher__sr-only\">\n Checkout\n </Dialog.Title>\n <Dialog.Description className=\"lockerverse-launcher__sr-only\">\n Review the order and complete payment.\n </Dialog.Description>\n </>\n );\n }\n\n if (!catalog) {\n return (\n <header className=\"lockerverse-launcher__header\">\n <Dialog.Title className=\"lockerverse-launcher__title\">\n Donate\n </Dialog.Title>\n <Dialog.Description className=\"lockerverse-launcher__description\">\n Choose your options, then continue to checkout.\n </Dialog.Description>\n </header>\n );\n }\n\n return (\n <header className=\"lockerverse-launcher__header\">\n {catalog.community ? (\n <div className=\"lockerverse-launcher__brand\">\n {catalog.community.imageUrl ? (\n <img\n alt={`${catalog.community.name} logo`}\n height=\"28\"\n src={catalog.community.imageUrl}\n width=\"28\"\n />\n ) : null}\n <span>{catalog.community.name}</span>\n </div>\n ) : null}\n <Dialog.Title className=\"lockerverse-launcher__title\">\n {catalog.widget.title ?? catalog.widget.name}\n </Dialog.Title>\n <Dialog.Description className=\"lockerverse-launcher__description\">\n {catalog.widget.description ??\n \"Choose your options, then continue to checkout.\"}\n </Dialog.Description>\n </header>\n );\n}\n\nexport function LockerverseDonateLauncher({\n buttonLabel = \"Donate\",\n position = \"inline\",\n widget,\n ...paymentProps\n}: LockerverseDonateLauncherProps) {\n const [selection, setSelection] = useState<\n LockerversePaymentSelectionItem[] | null\n >(null);\n const [customAmounts, setCustomAmounts] = useState<Record<string, string>>(\n {}\n );\n const [quantities, setQuantities] = useState<Record<string, number>>({});\n const [recurringProductId, setRecurringProductId] = useState<string | null>(\n null\n );\n const { catalog, error, loading } = widget;\n const accent = normalizeAccentColor(\n paymentProps.style?.[\"--lockerverse-accent\"] ??\n catalog?.community?.accentColor ??\n \"#38d77a\"\n );\n const accentContrast = getAccentContrast(accent);\n const launcherStyle: LockerversePaymentStyle = { ...paymentProps.style };\n if (\n paymentProps.style?.[\"--lockerverse-accent\"] !== undefined ||\n catalog?.community?.accentColor\n ) {\n launcherStyle[\"--lockerverse-accent\"] = accent;\n }\n if (\n accentContrast &&\n paymentProps.style?.[\"--lockerverse-accent-contrast\"] === undefined\n ) {\n launcherStyle[\"--lockerverse-accent-contrast\"] = accentContrast;\n }\n\n let content: ReactNode;\n if (loading) {\n content = <LauncherLoading />;\n } else if (error) {\n content = (\n <div role=\"alert\">\n <p>Unable to load donation options.</p>\n <button onClick={widget.refresh} type=\"button\">\n Retry\n </button>\n </div>\n );\n } else if (catalog) {\n content = (\n <LauncherCatalog\n catalog={catalog}\n customAmounts={customAmounts}\n onContinue={setSelection}\n quantities={quantities}\n recurringProductId={recurringProductId}\n setCustomAmounts={setCustomAmounts}\n setQuantities={setQuantities}\n setRecurringProductId={setRecurringProductId}\n />\n );\n } else {\n content = <LauncherLoading />;\n }\n if (!(loading || error) && selection && catalog) {\n content = (\n <LauncherCheckout\n onEdit={() => setSelection(null)}\n paymentProps={paymentProps}\n selection={selection}\n style={launcherStyle}\n widget={widget}\n />\n );\n }\n\n return (\n <Dialog.Root\n onOpenChange={(open) => {\n if (open && catalog && paymentProps.stripeLoader === undefined) {\n requestAnimationFrame(() => {\n preloadLockerversePayment(catalog);\n });\n }\n }}\n >\n <Dialog.Trigger\n className={`lockerverse-launcher lockerverse-launcher--${position}`}\n data-lockerverse-theme={paymentProps.theme ?? \"dark\"}\n style={launcherStyle}\n >\n {buttonLabel}\n </Dialog.Trigger>\n <Dialog.Portal>\n <Dialog.Backdrop className=\"lockerverse-launcher__backdrop\" />\n <Dialog.Viewport className=\"lockerverse-launcher__viewport\">\n <Dialog.Popup\n className=\"lockerverse-launcher__dialog\"\n data-lockerverse-theme={paymentProps.theme ?? \"dark\"}\n style={launcherStyle}\n >\n <LauncherDialogHeading\n catalog={catalog}\n checkout={selection !== null}\n />\n <Dialog.Close\n aria-label=\"Close donation dialog\"\n className=\"lockerverse-launcher__close\"\n >\n <span aria-hidden=\"true\">×</span>\n </Dialog.Close>\n {content}\n </Dialog.Popup>\n </Dialog.Viewport>\n </Dialog.Portal>\n </Dialog.Root>\n );\n}\n"],"mappings":"gVAuBA,MAAM,EAAM,IAAI,KAAK,aAAa,QAAS,CACzC,SAAU,MACV,MAAO,UACT,CAAC,EACK,EAAuB,iCACvB,EAAgC,CAAC,IAAM,KAAM,IAAM,GAAM,EAE/D,SAAS,EAAiB,EAAe,CACvC,GAAI,CAAC,EAAqB,KAAK,CAAK,EAClC,OAAO,KAET,IAAM,EAAc,KAAK,MAAM,OAAO,CAAK,EAAI,GAA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,CACW,GACC,CAAA,CACJ,CAAA,CAAA,CACJ,GAEjB"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{t as e}from"./format-money.js";import{t}from"./host-callback.js";import{n,t as r}from"./accent-contrast.js";import{d as i,i as a,n as o,p as s,t as c,u as l}from"./phone-field.js";import{a as u,i as d,n as f,r as p,s as m}from"./custom-fields.js";import{t as h}from"./form-skeleton.js";import{t as g}from"./payment-summary.js";import{i as _,n as v,r as y,t as b}from"./stripe-loader.js";import{useCallback as x,useEffect as S,useId as C,useLayoutEffect as w,useMemo as T,useReducer as E,useRef as D,useState as O}from"react";import{Fragment as k,jsx as A,jsxs as j}from"react/jsx-runtime";import{LockerverseSdkError as M,estimateLockerverseCheckout as N}from"@lockerverse/sdk/checkout";import{AddressElement as P,Elements as ee,PaymentElement as F,useElements as I,useStripe as L}from"@stripe/react-stripe-js";import{array as te,literal as R,minLength as z,minValue as B,nonEmpty as V,nullable as ne,number as re,object as H,optional as U,pipe as W,regex as G,safeInteger as ie,safeParse as ae,strictObject as oe,string as K,trim as q,union as se}from"valibot";function ce({ariaDescribedBy:e,ariaLabel:t,ariaLabelledBy:n,className:r,id:i,invalid:a=!1,name:o,onValueChange:s,options:c,value:l}){return A(`select`,{"aria-describedby":e,"aria-invalid":a||void 0,"aria-label":t,"aria-labelledby":n,className:[`lockerverse-form__control`,`lockerverse-form__select`,r].filter(Boolean).join(` `),id:i,name:o,onChange:e=>s(e.currentTarget.value),value:l,children:c.map(e=>A(`option`,{value:e.value,children:e.label},e.value))})}const le=[`XS`,`S`,`M`,`L`,`XL`,`XXL`,`XXXL`],ue=[`15`,`12`,`10`,`5`],J=[...ue,`custom`];function de({enabled:e,error:t,errorId:n,onChange:r,values:i}){if(!e)return null;let a=e=>r({...i,...e}),o=(e,t)=>{let n=J.indexOf(t),r;switch(e.key){case`ArrowDown`:case`ArrowRight`:r=(n+1)%J.length;break;case`ArrowLeft`:case`ArrowUp`:r=(n-1+J.length)%J.length;break;case`Home`:r=0;break;case`End`:r=J.length-1;break;default:return}e.preventDefault();let i=J[r];i&&((e.currentTarget.closest(`[role="radiogroup"]`)?.querySelectorAll(`input[type="radio"]`))?.[r]?.focus(),a({tipPercent:i}))};return j(`div`,{className:`lockerverse-payment__tip-box`,children:[A(`p`,{children:`Add a tip to support the Lockerverse platform`}),j(`div`,{"aria-label":`Tip amount`,role:`radiogroup`,children:[ue.map(e=>j(`label`,{className:`lockerverse-payment__tip-choice`,children:[A(`input`,{checked:i.tipPercent===e,name:`tipPercent`,onChange:()=>a({tipPercent:e}),onKeyDown:t=>o(t,e),tabIndex:i.tipPercent===e?0:-1,type:`radio`,value:e}),j(`span`,{children:[e,`%`]})]},e)),j(`label`,{className:`lockerverse-payment__tip-choice`,children:[A(`input`,{checked:i.tipPercent===`custom`,name:`tipPercent`,onChange:()=>a({tipPercent:`custom`}),onKeyDown:e=>o(e,`custom`),tabIndex:i.tipPercent===`custom`?0:-1,type:`radio`,value:`custom`}),A(`span`,{children:`Other`})]})]}),i.tipPercent===`custom`?j(`label`,{children:[A(`span`,{children:`Custom tip`}),j(`span`,{className:`lockerverse-payment__money-input`,children:[A(`span`,{"aria-hidden":`true`,children:`$`}),A(`input`,{"aria-describedby":t?n:void 0,"aria-invalid":t?`true`:void 0,inputMode:`decimal`,name:`tip`,onChange:e=>a({customTip:e.currentTarget.value}),placeholder:`0.00`,value:i.customTip})]}),t?A(`span`,{className:`lockerverse-payment__field-message`,id:n,children:t}):null]}):A(`input`,{name:`tip`,type:`hidden`,value:i.tipPercent})]})}function fe({checked:e,children:t,name:n,onChange:r}){let i=C();return j(`label`,{className:`lockerverse-payment__check-row`,htmlFor:i,children:[A(l,{checked:e,id:i,name:n,onChange:e=>r(e.currentTarget.checked)}),A(`span`,{children:t})]})}function pe({customFields:e,errors:t,fields:n,idPrefix:r,isPromoApplying:i,memberIdLabel:a,onChange:o,onApplyPromo:s,promoError:c,values:l}){let u=e=>o({...l,...e});return j(`div`,{className:`lockerverse-payment__additional-fields`,children:[n.memberId?j(`label`,{children:[A(`span`,{children:a?.trim()||`Member ID`}),A(`input`,{name:`memberId`,onChange:e=>u({memberId:e.currentTarget.value}),placeholder:`Optional`,value:l.memberId})]}):null,n.merchSize?j(`div`,{className:`lockerverse-payment__field`,children:[A(`span`,{id:`${r}-merch-size-label`,children:`Size`}),A(ce,{ariaLabelledBy:`${r}-merch-size-label`,name:`merchSize`,onValueChange:e=>{let t=le.find(t=>t===e);t&&u({merchSize:t})},options:le.map(e=>({label:e,value:e})),value:l.merchSize})]}):null,n.promoCode?j(`div`,{className:`lockerverse-payment__field`,children:[A(`span`,{id:`${r}-promo-code-label`,children:`Promo code`}),j(`div`,{className:`lockerverse-payment__promo-control`,children:[A(`input`,{"aria-describedby":c?`${r}-promo-code-error`:void 0,"aria-invalid":c?`true`:void 0,"aria-labelledby":`${r}-promo-code-label`,name:`promoCode`,onChange:e=>u({promoCode:e.currentTarget.value}),placeholder:`Optional`,value:l.promoCode}),A(`button`,{disabled:!l.promoCode.trim()||i,onClick:s,type:`button`,children:i?`Applying…`:`Apply`})]}),c?A(`p`,{className:`lockerverse-payment__field-message`,id:`${r}-promo-code-error`,role:`alert`,children:c}):null]}):null,A(f,{choiceClassName:`lockerverse-payment__check-row`,errorClassName:`lockerverse-payment__field-message`,errors:t,fields:e,idPrefix:r,onChange:e=>u({customFields:e}),values:l.customFields})]})}function me({amountCents:t,enabled:n,onChange:r,values:i}){return n?j(fe,{checked:i.includeServiceFee,name:`includeServiceFee`,onChange:e=>r({...i,includeServiceFee:e}),children:[`Add `,e(t),` to help cover processing fees`]}):null}function he(e){return{error:void 0,message:void 0,status:e?`recovering`:`editing`}}function Y(e,t,n){return t.includes(e.status)?{...e,...n}:e}function ge(e,t){if(t.type===`recovery_started`&&e.status===`unresolved`)return{...e,message:void 0,status:`recovering`};if(e.status===`sold_out`||e.status===`succeeded`||e.status===`unresolved`)return e;switch(t.type){case`field_changed`:return Y(e,[`editing`,`invalid`,`refreshing_quote`],{error:void 0,status:`editing`});case`validation_failed`:return Y(e,[`editing`],{status:`invalid`});case`quote_refresh_started`:return Y(e,[`editing`,`invalid`],{status:`refreshing_quote`});case`quote_refresh_succeeded`:return Y(e,[`refreshing_quote`],{error:void 0,status:`editing`});case`quote_refresh_failed`:return Y(e,[`refreshing_quote`],{error:t.error??e.error,status:`editing`});case`submission_started`:return Y(e,[`editing`,`invalid`,`refreshing_quote`],{error:void 0,status:`submitting`});case`submission_validation_failed`:return Y(e,[`submitting`],{error:void 0,status:`invalid`});case`quote_changed`:return Y(e,[`submitting`],{status:`editing`});case`retryable_failure`:return Y(e,[`editing`,`invalid`,`submitting`],{error:t.error,status:`editing`});case`recovery_failed`:return Y(e,[`recovering`],{error:t.error,retryUrl:void 0,status:`editing`});case`sold_out`:return{error:void 0,message:void 0,status:`sold_out`};case`succeeded`:return Y(e,[`recovering`,`submitting`],{message:t.message,retryUrl:void 0,status:`succeeded`});case`unresolved`:return Y(e,[`recovering`,`submitting`],{message:t.message,retryUrl:t.retryUrl,status:`unresolved`});default:return e}}function X(e){return e.status===`editing`||e.status===`invalid`||e.status===`refreshing_quote`?e.error:void 0}function Z(e){return e.status===`sold_out`?`sold_out`:e.status===`succeeded`?`success`:e.status===`unresolved`?`unresolved`:e.status===`submitting`||e.status===`recovering`?`submitting`:e.status===`invalid`?`invalid`:X(e)?`error`:`idle`}function Q(e){return e.status===`submitting`}function _e(e){return e.widget.fields.shipping||!!e.widget.liveShipping?.enabled}function ve(e){if(!e?.complete)return;let{line2:t,...n}=e.value.address,r={address:n,name:e.value.name};return t&&(r.address.line2=t),r}function ye(e,t){let n=e.widget.liveShipping;return!!n?.enabled&&t.some(e=>n.productIds.includes(e.productId))}function $(e,t,n,r,i){if(!ye(e,t))return{};let a=`shippingQuote`in i?i.shippingQuote:null,o=ve(r?n.billing:n.shipping);if(!(o&&a)||Date.parse(a.expiresAt)<=Date.now())throw Error(`Calculate shipping before payment.`);return{shipping:o,shippingQuoteToken:a.token}}function be(e,t){return e&&t}function xe(e){if(!e)throw Error(`Calculate shipping before payment.`)}function Se({shipping:t,disabled:n,onCalculate:r}){if(!t.required)return null;let i=`Calculate shipping`;return t.loading?i=`Calculating shipping…`:t.valid&&(i=`Shipping calculated`),j(`section`,{"aria-label":`Shipping quote`,className:`lockerverse-payment__shipping-quote`,children:[A(`h3`,{children:`Delivery`}),A(`p`,{children:`Enter your complete US shipping address, then calculate shipping.`}),A(`button`,{disabled:!t.canCalculate||t.loading||t.valid||n,onClick:r,type:`button`,children:i}),j(`div`,{"aria-live":`polite`,children:[t.rate?j(`p`,{children:[t.rate.carrier,` `,t.rate.service,` ·`,` `,e(t.rate.amountCents),t.rate.estimatedDays===null?``:` · Estimated transit: ${t.rate.estimatedDays} business days`]}):null,t.expired?A(`p`,{children:`Your shipping quote has expired. Calculate shipping again.`}):null,t.error?A(`p`,{role:`alert`,children:t.error}):null]})]})}const Ce=[`amountCents`,`discountableSubtotalCents`,`discountCents`,`serviceFeeCents`,`subtotalCents`,`tipCents`,`totalCents`],we=[`discountableSubtotalCents`,`discountCents`,`subtotalCents`];function Te(e,t,n,r){return(n===t.totalCents?we:Ce).some(n=>e[n]!==t[n])||r!==t.payment.connectedAccountId||e.authoritative&&(e.payment.connectedAccountId!==r||e.payment.currency!==t.payment.currency)||JSON.stringify(e.appliedDiscount)!==JSON.stringify(t.appliedDiscount)||JSON.stringify(e.lineItems)!==JSON.stringify(t.lineItems)}function Ee(e){if(e.checkoutStatus===`success`)return{kind:`success`,payment:e};if(e.checkoutStatus===`failed`)return{kind:`failed`,payment:e};let t={kind:`unresolved`,paymentReference:e.paymentReference,reason:e.checkoutStatus===`action_required`?`action_required`:`pending`};return e.retryUrl&&(t.retryUrl=e.retryUrl),t}async function De(e,t,n){if(t.checkoutStatus!==`action_required`||!t.requiresAction)return Ee(t);if(!n)return{kind:`unresolved`,paymentReference:t.paymentReference,reason:`action_required`};if(t.clientSecret)try{await n.handleNextAction({clientSecret:t.clientSecret})}catch{}try{return Ee(await e.getPaymentStatus(t.paymentReference))}catch{return{kind:`unresolved`,paymentReference:t.paymentReference,reason:`action_required`}}}async function Oe(e,t,n){let r;try{r=await e.submitPayment(t)}catch(n){if(!(n instanceof M&&n.recoveryRecommended))throw n;try{r=await e.getPaymentStatus(t.checkout.paymentReference)}catch{return{kind:`unresolved`,paymentReference:t.checkout.paymentReference,reason:`recovery_failed`}}}return De(e,r,n)}async function ke(e,t,n){try{return De(e,await e.getPaymentStatus(t),n)}catch{return{kind:`unresolved`,paymentReference:t,reason:`recovery_failed`}}}const Ae=W(K(),q(),V()),je=W(re(),ie(),B(1)),Me=W(te(se([oe({amountCents:je,productSlug:Ae}),oe({productSlug:Ae,quantity:je}),oe({productSlug:Ae})])),z(1)),Ne=W(K(),q(),G(/^(?:0|[1-9]\d*)(?:\.\d{1,2})?$/,`Enter a valid tip amount.`));function Pe(e){let t=ae(Ne,e);if(!t.success)return{message:t.issues[0]?.message??`Enter a valid tip amount.`,success:!1};let[n=`0`,r=``]=t.output.split(`.`),i=BigInt(n)*100n+BigInt(r.padEnd(2,`0`));return i>BigInt(2**53-1)?{message:`Enter a valid tip amount.`,success:!1}:{cents:Number(i),success:!0}}function Fe(e){let t=ae(Me,e);return t.success?{success:!0,value:t.output}:{message:`Lockerverse payment configuration is invalid.`,success:!1}}const Ie=`This promo code is invalid or cannot be applied.`;function Le(e,t){return t.tipPercent===`custom`?t.customTip.trim()?Pe(t.customTip):{cents:0,success:!0}:{cents:Math.round(e*Number(t.tipPercent)/100),success:!0}}function Re(e,t,n,r){let i={};return n&&(i.email=n),e.widget.fields.serviceFee&&(i.includeServiceFee=t.includeServiceFee),e.widget.fields.promoCode&&t.promoCode.trim()&&(i.promoCode=t.promoCode.trim()),e.widget.fields.tipping&&(i.tipCents=r),i}function ze(e,t,n){let r=e.widget.fields.tipping?Le(n.subtotalCents,t):{cents:0,success:!0};if(!r.success)return{parsedTip:r,totalCents:null};let i=e.widget.fields.serviceFee&&t.includeServiceFee?n.serviceFeeCents||Math.round(n.subtotalCents*e.pricingPolicy.serviceFeeRateBasisPoints/1e4):0;return{parsedTip:r,totalCents:n.totalCents-n.serviceFeeCents-n.tipCents+i+r.cents}}function Be(e,t){return{displayedTotalCents:e.totalCents,promoError:t&&e.appliedDiscount?.source!==`promo_code`?Ie:void 0}}function Ve(e,t){let n;return t||(n=e instanceof Error?e.message:`The order total could not be updated.`),{paymentError:n,promoError:t?Ie:void 0}}function He(e,t){if(!e?.complete)throw Error(`${t} address is required.`);return e.value}function Ue(e,t,n,r){if(e.widget.fields.shipping||e.widget.liveShipping?.enabled)return t.shippingMatchesBilling?n:He(r.shipping,`Shipping`)}function We({billingAddress:e,catalog:t,email:n,phone:r,shippingAddress:i}){let a={payment_method_data:{billing_details:t.widget.fields.phone?{address:e.address,email:n,name:e.name,phone:r}:{address:e.address,email:n,name:e.name}}};return i?{...a,shipping:{address:i.address,name:i.name,phone:t.widget.fields.phone?r:i.phone??null}}:a}function Ge({catalog:e,checkoutItems:t,confirmationToken:n,email:r,fieldValues:i,metadata:a,phone:o,shippingAddress:s}){let c={customFieldAnswers:p(u(e,t),i.customFields),email:r};if(n&&(c.confirmationToken=n,c.paymentMethodConfiguration=`explicit`),a&&(c.metadata=a),e.widget.fields.memberId&&i.memberId.trim()&&(c.memberId=i.memberId.trim()),e.widget.fields.merchSize&&(c.merchSize=i.merchSize),e.widget.fields.phone&&(c.phone=o),s){let e={city:s.address.city??``,country:s.address.country,line1:s.address.line1??``,postal_code:s.address.postal_code??``,state:s.address.state??``};s.address.line2&&(e.line2=s.address.line2),c.shipping={address:e,name:s.name}}return c}function Ke(e){if(!e())throw Error(`Payment component is no longer active.`)}function qe(e,n){t(e,n)}function Je(e,t,n,r){return e.kind===`failed`?{kind:`payment_failed`,message:r}:e.kind===`unresolved`?{kind:`payment_unresolved`,paymentReference:e.paymentReference,reason:e.reason,retryUrl:e.retryUrl}:{email:n,kind:`payment`,payment:e.payment,quote:t}}async function Ye({addresses:e,catalog:t,checkoutItems:n,client:r,elements:i,email:a,fieldValues:o,isAttemptActive:s,locallyPreviewedTotalCents:c,metadata:l,onPaymentRecoveryChange:u,phone:d,quote:f,stripe:p,stripeConnectedAccountId:m}){let h=a.trim().toLowerCase(),g=y(d),_=Le(f.subtotalCents,o);if(!_.success)throw Error(_.message);let v=await r.calculateTotal({...$(t,n,e,o.shippingMatchesBilling,f),...Re(t,o,h,_.cents),catalog:t,items:n});if(Ke(s),v.totalCents>0&&Te(f,v,c,m))return{kind:`quote_changed`,quote:v};let b,x;if(v.totalCents===0)(t.widget.fields.shipping||t.widget.liveShipping?.enabled)&&(b=Ue(t,o,He(e.billing,`Billing`),e));else{if(!(i&&p))throw Error(`Payment form is still loading.`);await i.update({amount:v.totalCents}),Ke(s);let n=await i.submit();if(Ke(s),n.error)throw Error(n.error.message);let r=He(e.billing,`Billing`);b=Ue(t,o,r,e);let a=await p.createConfirmationToken({elements:i,params:We({billingAddress:r,catalog:t,email:h,phone:g,shippingAddress:b})});if(Ke(s),a.error)throw Error(a.error.message);x=a.confirmationToken.id}qe(u,{connectedAccountId:v.payment.connectedAccountId,paymentReference:v.paymentReference});let S=await Oe(r,{checkout:v,submission:Ge({catalog:t,checkoutItems:n,confirmationToken:x,email:h,fieldValues:o,metadata:l,phone:g,shippingAddress:b})},p);return Ke(s),Je(S,v,h,v.totalCents===0?`Order could not be completed. Review the details and try again.`:`Payment was declined. Check your payment details and try again.`)}function Xe(e,n){t(e,n)}function Ze(e,n){t(e,n)}function Qe(e,t){return{...e,...t}}function $e(e){let t={message:e.reason===`action_required`?`Payment needs your attention. Keep this checkout open.`:`Payment is not complete. Check its status before you try again.`,type:`unresolved`};return e.retryUrl&&(t.retryUrl=e.retryUrl),t}function et(e,t,n){return e.kind===`unresolved`&&e.reason===`action_required`&&!e.retryUrl&&!t&&!n}function tt(e){return e instanceof M&&e.serverCode===`PAYMENT_WIDGET_SALES_LIMIT_REACHED`}function nt({nextQuote:e,onQuoteChange:t,setDisplayedTotalCents:n,setPromoError:r,updateState:i,validatePromo:a}){let o=Be(e,a);i({type:`quote_refresh_succeeded`}),n(o.displayedTotalCents),t(e),a&&r(o.promoError)}function rt({error:e,setPromoError:t,updateState:n,validatePromo:r}){let i=Ve(e,r);r&&t(i.promoError),n(i.paymentError===void 0?{type:`quote_refresh_failed`}:{error:i.paymentError,type:`quote_refresh_failed`})}function it({onPaymentComplete:n,onPaymentRecoveryChange:r,onPaymentUncertain:i,onQuoteChange:a,result:o,setDisplayedTotalCents:s,dispatchState:c,unresolvedReferenceRef:l}){if(o.kind===`quote_changed`){let t=`The total changed to ${e(o.quote.totalCents)}. Review it and pay again.`;a(o.quote,t),s(o.quote.totalCents),c({type:`quote_changed`});return}if(o.kind===`payment_failed`){Xe(r,null),c({error:o.message,type:`retryable_failure`});return}if(o.kind===`payment_unresolved`){l.current=o.paymentReference,c($e(o)),Ze(i,{paymentReference:o.paymentReference,reason:o.reason});return}a(o.quote),Xe(r,null),c({message:o.payment.paymentRequired?`Payment completed successfully.`:`Order confirmed. No payment was required.`,type:`succeeded`}),t(n,Qe(o.payment,{email:o.email,lineItems:o.quote.lineItems}))}function at(e){let{shipping:n,catalog:r,checkoutItems:i,client:o,elements:s,email:c,fieldValues:l,metadata:u,onPaymentComplete:d,onResumePaymentFailed:f,onPaymentRecoveryChange:p,onPaymentUncertain:m,onQuoteChange:h,onStateChange:g,quote:v,resumePayment:y,stripe:b,stripeConnectedAccountId:C,stripeLoadFailed:w,paymentState:T,updateState:E}=e,[k,A]=O(v.totalCents),[j,N]=O(),P=D(!1),ee=D(void 0),F=D(0),I=D(0),L=x(e=>E(e,!0),[E]),te=x(()=>{let e=I.current+1;return I.current=e,()=>I.current===e},[]);S(()=>()=>{I.current+=1,F.current+=1},[]);let{parsedTip:R,totalCents:z}=ze(r,l,v),B=z===null?null:z-(n.required&&!n.valid&&`shippingCents`in v?v.shippingCents??0:0);S(()=>{B!==null&&(A(B),B>0&&s?.update({amount:B}))},[r.pricingPolicy.serviceFeeRateBasisPoints,r.widget.fields.serviceFee,s,l.includeServiceFee,B,v.serviceFeeCents,v.tipCents,v.totalCents,v.subtotalCents]),S(()=>{let e=y?.paymentReference??ee.current;if(!e||P.current||T.status!==`recovering`)return;P.current=!0;let n=te();return g(Z(T)),ke(o,e,b).then(e=>{if(n()&&!et(e,b,w)){if(e.kind===`failed`){Xe(p,null),f(),L({error:`The previous payment failed. Check your details and try again.`,type:`recovery_failed`});return}if(e.kind===`unresolved`){L($e(e)),Ze(m,{paymentReference:e.paymentReference,reason:e.reason});return}Xe(p,null),L({message:e.payment.paymentRequired?`Payment completed successfully.`:`Order confirmed. No payment was required.`,type:`succeeded`}),t(d,Qe(e.payment,{email:null,lineItems:null}))}}),()=>{n()&&(I.current+=1),P.current=!1}},[o,d,f,p,m,g,y,b,w,te,L,T]);let V=x((e=!1,t=!1)=>{t||(F.current+=1),e&&N(void 0),E({type:`field_changed`})},[E]);async function ne(e=!1,t=!1){if(n.loading)return;let a=c.trim().toLowerCase(),s=_({email:a,phone:``},!1);if(!(R.success&&(s.value||e)))return;F.current+=1;let u=F.current;E({type:`quote_refresh_started`});try{let e=await o.calculateTotal({...Re(r,l,s.value?.email??``,R.cents),catalog:r,items:i,...n.request});if(u!==F.current)return;nt({nextQuote:e,onQuoteChange:h,setDisplayedTotalCents:A,setPromoError:N,updateState:E,validatePromo:t})}catch(e){if(u!==F.current)return;if(tt(e)){E({type:`sold_out`});return}rt({error:e,setPromoError:N,updateState:E,validatePromo:t})}}async function re(){N(void 0),await ne(!0,!0)}async function H({addresses:e,phone:t}){L({type:`submission_started`});let f=te();try{xe(n.ready);let a=await Ye({addresses:e,catalog:r,checkoutItems:i,client:o,elements:s,email:c,fieldValues:l,isAttemptActive:f,locallyPreviewedTotalCents:k,metadata:u,onPaymentRecoveryChange:p,phone:t,quote:v,stripe:b,stripeConnectedAccountId:C});if(!f())return;it({dispatchState:L,onPaymentComplete:d,onPaymentRecoveryChange:p,onPaymentUncertain:m,onQuoteChange:h,result:a,setDisplayedTotalCents:A,unresolvedReferenceRef:ee})}catch(e){if(!f())return;if(Xe(p,null),tt(e)){L({type:`sold_out`});return}let t=e instanceof M?a(e.serverCode):void 0;if(t)return L({type:`submission_validation_failed`}),{phoneError:t};L({error:e instanceof Error?e.message:`Payment could not be completed.`,type:`retryable_failure`})}}let U=T.status===`succeeded`||T.status===`unresolved`?T.message:void 0;return{commands:{applyPromo:re,checkPaymentStatus:()=>L({type:`recovery_started`}),fieldChanged:V,refreshAuthoritativeTotal:ne,reportValidationFailure:()=>L({type:`validation_failed`}),submit:H},state:{displayedTotalCents:k,isRecovering:T.status===`recovering`,isRefreshingQuote:T.status===`refreshing_quote`,isSubmitting:Q(T),isUnresolved:T.status===`unresolved`,parsedTip:R,paymentError:X(T),promoError:j,retryUrl:T.retryUrl,terminalMessage:U}}}async function ot({catalog:e,client:t,checkoutItems:n,fieldValues:r,email:i,quote:a,shipping:o,shippingQuoteToken:s}){if(o.address.country!==`US`)throw Error(`Shipping is available only to US addresses.`);let c=Le(a.subtotalCents,r);if(!c.success)throw Error(c.message);let l={...Re(e,r,i.trim().toLowerCase(),c.cents),catalog:e,items:n,shipping:o};s&&(l.shippingQuoteToken=s);let u=await t.calculateTotal(l);if(!u.shippingQuote)throw Error(`Shipping is not available for this order. Check the address and try again.`);return{...u,shippingQuote:u.shippingQuote}}function st({catalog:e,checkoutItems:t,client:n,addresses:r,fieldValues:i,email:a,quote:o,onQuoteChange:s}){let c=ye(e,t),l=ve(i.shippingMatchesBilling?r.billing:r.shipping),u=JSON.stringify({checkoutItems:t,config:e.widget.liveShipping,shipping:l,subtotalCents:o.subtotalCents}),d=D(u);d.current=u;let f=JSON.stringify({customTip:i.customTip,email:a,includeServiceFee:i.includeServiceFee,promoCode:i.promoCode,tipPercent:i.tipPercent}),p=D(f);p.current=f;let m=D(0),[h,g]=O(),[_,v]=O(!1),[y,b]=O(),[x,C]=O(Date.now),w=`shippingQuote`in o?o.shippingQuote:null,T=!!w&&h?.key===u&&h.token===w.token&&Date.parse(w.expiresAt)>x;S(()=>(m.current+=1,v(!1),b(void 0),()=>{m.current+=1}),[u,f]),S(()=>{if(!w)return;let e=setTimeout(()=>C(Date.now()),Math.max(0,Date.parse(w.expiresAt)-Date.now())+50);return()=>clearTimeout(e)},[w]);async function E(){if(!(c&&l)||_||T)return;m.current+=1;let r=m.current,y=()=>d.current===u&&p.current===f&&r===m.current,x=h?.key===u?w?.token:void 0;v(!0),b(void 0);try{let r=await ot({catalog:e,checkoutItems:t,client:n,email:a,fieldValues:i,quote:o,shipping:l,shippingQuoteToken:x});if(!y())return;C(Date.now()),g({key:u,token:r.shippingQuote.token}),s(r)}catch(e){y()&&b(e instanceof Error?e.message:`Shipping could not be calculated. Please try again.`)}finally{r===m.current&&v(!1)}}return{calculate:E,canCalculate:!!l,error:y,expired:!!w&&h?.key===u&&Date.parse(w.expiresAt)<=x,loading:_,pending:c&&!T,rate:T?w:null,ready:!c||T,request:T&&l&&w?{shipping:l,shippingQuoteToken:w.token}:void 0,required:c,valid:T}}const ct=b;function lt(e){let{connectedAccountId:t,publishableKey:n}=e.payment;return ct(n,t?{stripeAccount:t}:void 0)}function ut(e){return e===`monthly`?{interval:`month`,label:`Monthly`}:e===`annually`?{interval:`year`,label:`Annual`}:e===`every-six-months`?{interval:`6 months`,label:`Every 6 months`}:null}function dt(e,t,n){if(n){let{connectedAccountId:e}=n;return e}if(`payment`in t){let{connectedAccountId:e}=t.payment;return e}let{connectedAccountId:r}=e.payment;return r}function ft({accentColor:e,catalog:t,checkoutItems:n,client:r,appearanceRoot:i,initialCustomFieldValues:a,metadata:o,onPaymentComplete:s,onResumePaymentFailed:c,onPaymentRecoveryChange:l,onPaymentUncertain:u,onQuoteChange:d,quote:f,resumePayment:p,onStateChange:m,stripeLoader:g,theme:_,visualStyle:y}){let[b,C]=O(()=>he(!!p)),w=D(b);w.current=b;let E=x((e,t=!1)=>{let n=ge(w.current,e);n!==w.current&&(w.current=n,C(n),t&&m(Z(n)))},[m]),k=dt(t,f,p),j=D({connectedAccountId:k,paymentOption:f.paymentOption});b.status!==`submitting`&&b.status!==`recovering`&&(j.current={connectedAccountId:k,paymentOption:f.paymentOption});let{connectedAccountId:M,paymentOption:N}=j.current,P=T(()=>g(t.payment.publishableKey,M?{stripeAccount:M}:void 0).catch(()=>null),[t.payment.publishableKey,M,g]),[F,I]=O(!1);S(()=>{let e=!0;return I(!1),P.then(t=>{e&&t===null&&I(!0)}),()=>{e=!1}},[P]);let L=v(i,_,y,b.status===`submitting`||b.status===`recovering`,e);return L?A(ee,{options:{amount:Math.max(f.totalCents,100),appearance:L,currency:t.payment.currency,mode:N===`one-time`?`payment`:`subscription`,paymentMethodTypes:t.community?.widgetAchEnabled?[`card`,`link`,`us_bank_account`]:[`card`,`link`],syncAddressCheckbox:`none`},stripe:P,children:A(wt,{catalog:t,checkoutItems:n,client:r,initialCustomFieldValues:a,metadata:o,onPaymentComplete:s,onPaymentRecoveryChange:l,onPaymentUncertain:u,onQuoteChange:d,onResumePaymentFailed:c,onStateChange:m,paymentState:b,quote:f,resumePayment:p,stripeConnectedAccountId:M,stripeLoadFailed:F,updateState:E})},`${t.payment.publishableKey}:${M??`platform`}:${N}`):A(h,{fieldCount:3,label:`Loading payment form`})}function pt({label:e}){return j(`div`,{className:`lockerverse-payment__stripe-loader`,role:`status`,children:[A(`p`,{children:e}),j(`div`,{"aria-hidden":`true`,children:[A(`span`,{}),A(`span`,{}),A(`span`,{})]})]})}function mt({onError:e,onReady:t,ready:n}){return j(`div`,{className:`lockerverse-payment__stripe-element`,"data-ready":n,children:[n?null:A(pt,{label:`Loading payment form...`}),A(`div`,{className:`lockerverse-payment__stripe-mount`,children:A(F,{onLoadError:({error:t})=>e(t.message??`Payment form failed to load.`),onReady:t,options:{business:{name:`Lockerverse`},fields:{billingDetails:{address:`never`,email:`never`,name:`never`,phone:`never`}},layout:`tabs`,terms:{applePay:`auto`,auBecsDebit:`never`,bancontact:`never`,card:`always`,cashapp:`never`,googlePay:`never`,ideal:`never`,paypal:`auto`,sepaDebit:`never`,sofort:`never`,usBankAccount:`auto`},wallets:{applePay:`auto`,googlePay:`never`}}})})]})}function ht({label:e,mode:t,onChange:n,onError:r,onReady:i,ready:a}){return j(`div`,{className:`lockerverse-payment__address`,children:[A(`h2`,{children:e}),j(`div`,{className:`lockerverse-payment__stripe-element lockerverse-payment__stripe-element--address`,"data-ready":a,children:[a?null:A(pt,{label:`Loading ${e.toLowerCase()}...`}),A(`div`,{className:`lockerverse-payment__stripe-mount`,children:A(P,{onChange:n,onLoadError:({error:t})=>r(t.message??`${e} failed to load.`),onReady:i,options:{autocomplete:{mode:`automatic`},mode:t}})})]})]})}function gt({message:e}){return e?A(`p`,{className:`lockerverse-payment__field-message`,role:`alert`,children:e}):null}function _t({catalog:e,displayedTotalCents:t,fieldValues:n,isBillingAddressReady:r,isPaymentReady:i,isShippingAddressReady:a,onAddressChange:o,onFieldValuesChange:s,onStripeLoadError:c,setIsBillingAddressReady:l,setIsPaymentReady:u,setIsShippingAddressReady:d}){let f=t>0;return j(k,{children:[f?A(mt,{onError:c,onReady:()=>u(!0),ready:i}):null,f||e.widget.fields.shipping||e.widget.liveShipping?.enabled?A(ht,{label:f?`Billing address`:`Shipping address`,mode:`billing`,onChange:e=>o(`billing`,e),onError:c,onReady:()=>l(!0),ready:r}):null,e.widget.fields.shipping||e.widget.liveShipping?.enabled?j(`div`,{className:`lockerverse-payment__shipping`,children:[A(fe,{checked:n.shippingMatchesBilling,name:`shippingMatchesBilling`,onChange:e=>{s({...n,shippingMatchesBilling:e}),e?o(`shipping`,null):d(!1)},children:`Shipping is same as billing information`}),n.shippingMatchesBilling?null:A(ht,{label:`Shipping address`,mode:`shipping`,onChange:e=>o(`shipping`,e),onError:c,onReady:()=>d(!0),ready:a})]}):null]})}function vt({catalog:t,displayedTotalCents:n,fieldValues:r,isBillingAddressReady:i,isPaymentReady:a,isRequiredShippingReady:o,isSubmitting:s,onFieldValuesChange:c,quote:l}){let u=n===0,d=u?!(t.widget.fields.shipping||t.widget.liveShipping?.enabled)||i&&o:a&&i&&o,f=ut(l.paymentOption),p=u?`Complete order`:`Pay ${e(n)}`;!u&&f&&(p=`Subscribe for ${e(n)}/${f.interval}`),s&&(p=u?`Completing…`:`Processing…`);let m=`Process payment for ${e(n)} total`;return u?m=`Complete order`:f&&(m=`Start ${f.label.toLowerCase()} subscription for ${e(n)}`),j(`div`,{className:`lockerverse-payment__actions`,children:[A(me,{amountCents:l.serviceFeeCents||Math.round(l.subtotalCents*t.pricingPolicy.serviceFeeRateBasisPoints/1e4),enabled:t.widget.fields.serviceFee,onChange:c,values:r}),A(`button`,{"aria-busy":s,"aria-label":m,disabled:s||!d,type:`submit`,children:p})]})}function yt(e,t){let n=e.elements.namedItem(t);if(n instanceof HTMLElement){n.focus();return}n instanceof RadioNodeList&&Array.from(n).find(e=>e instanceof HTMLElement)?.focus()}function bt({customFieldErrors:e,emailRef:t,form:n,parsedTipSuccess:r,phoneRef:i,validationErrors:a}){if(a.email){t.current?.focus();return}if(a.phone){i.current?.focus();return}if(!r){n.querySelector(`[name="tip"]`)?.focus();return}let[o]=Object.keys(e);o&&yt(n,`custom:${o}`)}function xt({email:e,emailDiscountPercentOff:t,emailErrorId:n,emailId:r,emailRef:a,errors:o,onEmailBlur:l,onEmailChange:u,onPhoneChange:d,phone:f,phoneCountry:p,phoneEnabled:m,phoneErrorId:h,phoneId:g,phoneRef:_}){return j(`div`,{className:`lockerverse-payment__contact`,children:[A(i,{error:o.email,errorId:n,id:r,label:`Email`,name:`email`,onBlur:l,onChange:e=>u(e.currentTarget.value),ref:a,required:!0,value:e}),t===void 0?null:j(`p`,{className:`lockerverse-payment__discount-message`,role:`status`,children:[`Your email qualifies for `,t,`% off.`]}),m?A(s,{error:o.phone,errorId:h,id:g,label:`Phone`,children:A(c,{country:p,error:o.phone,errorId:h,id:g,inputRef:_,name:`phone`,onChange:d,required:!0,value:f})}):null]})}function St({message:e}){return e?j(`div`,{className:`lockerverse-payment__actions`,children:[A(`p`,{className:`lockerverse-payment__field-message`,role:`alert`,children:e}),A(`button`,{className:`lockerverse-payment__status-check`,onClick:()=>window.location.reload(),type:`button`,children:`Reload checkout`})]}):null}function Ct({paymentRequired:e,shippingRequired:t,isPaymentReady:n,isBillingAddressReady:r,isRequiredShippingReady:i,isSubmitting:a,scriptFailed:o,elementError:s,clearElementError:c}){let[l,u]=O(!1),d=e||t,f=(!e||n)&&(!d||r)&&i;if(S(()=>{if(u(!1),f&&c(void 0),!d||f||a)return;let e=window.setTimeout(()=>u(!0),3e4);return()=>window.clearTimeout(e)},[d,f,a,c]),!(!d||f||a)){if(o||s)return`The secure checkout fields could not load. Check your connection, then reload the checkout.`;if(l)return`The secure checkout fields are taking longer than expected. You can wait or reload the checkout.`}}function wt({catalog:e,checkoutItems:t,client:n,initialCustomFieldValues:r,metadata:i,onPaymentComplete:a,onResumePaymentFailed:s,onPaymentRecoveryChange:c,onPaymentUncertain:l,onQuoteChange:f,onStateChange:p,quote:h,resumePayment:v,stripeConnectedAccountId:y,stripeLoadFailed:b,paymentState:x,updateState:w}){let T=_e(e),E=u(e,t),[M,N]=O(``),[P,ee]=O(``),[F,te]=O(`US`),[R,z]=O({}),[B,V]=O({}),[ne,re]=O(),[H,U]=O(),[W,G]=O(!1),[ie,ae]=O(!1),[oe,K]=O(!1),[q,se]=O(()=>({customFields:d(E,r),customTip:``,includeServiceFee:e.widget.fields.serviceFee,memberId:``,merchSize:`M`,promoCode:``,shippingMatchesBilling:!0,tipPercent:`10`})),[ce,le]=O({billing:null,shipping:null}),ue=D(null),J=D(null),fe=D(null),me=D(h.totalCents>0),he=I(),Y=L(),ge=st({addresses:ce,catalog:e,checkoutItems:t,client:n,email:M,fieldValues:q,onQuoteChange:f,quote:h}),X=at({catalog:e,checkoutItems:t,client:n,elements:he,email:M,fieldValues:q,metadata:i,onPaymentComplete:a,onPaymentRecoveryChange:c,onPaymentUncertain:l,onQuoteChange:f,onResumePaymentFailed:s,onStateChange:p,paymentState:x,quote:h,resumePayment:v,shipping:ge,stripe:Y,stripeConnectedAccountId:y,stripeLoadFailed:b,updateState:w}),{displayedTotalCents:Z,isRecovering:Q,isUnresolved:ve,isRefreshingQuote:ye,isSubmitting:$,parsedTip:xe,paymentError:Ce,promoError:we,terminalMessage:Te,retryUrl:Ee}=X.state,De=`lockerverse-${C()}`,Oe=`${De}-email`,ke=`${Oe}-error`,Ae=`${De}-phone`,je=`${Ae}-error`,Me=`${De}-tip-error`,Ne=(xe.success?xe.cents:null)??0,Pe=Z-Ne,Fe=!T||q.shippingMatchesBilling||oe,Ie=Ct({clearElementError:U,elementError:H,isBillingAddressReady:ie,isPaymentReady:W,isRequiredShippingReady:Fe,isSubmitting:$,paymentRequired:Z>0,scriptFailed:b,shippingRequired:T});S(()=>{$&&fe.current?.focus({preventScroll:!0})},[$]),S(()=>{$||R.email||!R.phone||J.current?.focus()},[R.email,R.phone,$]),S(()=>{let e=Z>0;e&&!me.current&&(G(!1),ae(!1)),me.current=e},[Z]);function Le(e){X.commands.fieldChanged(!1,e!==`email`),z(t=>{let n={...t};return delete n[e],n})}function Re(e){let t=e.promoCode!==q.promoCode,n=e.includeServiceFee!==q.includeServiceFee;X.commands.fieldChanged(t,!(t||n)),se(e),V({}),re(void 0)}async function ze(t){t.preventDefault();let n=e.widget.fields.phone?o(P,F):``,r=_({email:M,phone:n},e.widget.fields.phone),i=m(E,q.customFields);if(!(r.value&&xe.success)||Object.keys(i).length>0){z(r.errors),V(i),re(xe.success?void 0:xe.message),X.commands.reportValidationFailure();let e=t.currentTarget;queueMicrotask(()=>{bt({customFieldErrors:i,emailRef:ue,form:e,parsedTipSuccess:xe.success,phoneRef:J,validationErrors:r.errors})});return}z({}),V({});let a=await X.commands.submit({addresses:ce,phone:n});a?.phoneError&&z({phone:a.phoneError})}return Te||Q?j(`div`,{className:`lockerverse-payment__actions`,children:[j(`p`,{className:`lockerverse-payment__payment-status`,ref:fe,role:`status`,tabIndex:-1,children:[Q?`Recovering payment…`:Te,Ee?j(k,{children:[` `,A(`a`,{href:Ee,rel:`noopener noreferrer`,target:`_blank`,children:`Complete payment`})]}):null]}),ve||Q?A(`button`,{"aria-busy":Q,className:`lockerverse-payment__status-check`,disabled:Q,onClick:X.commands.checkPaymentStatus,type:`button`,children:Q?`Checking payment status…`:`Check payment status`}):null]}):j(`form`,{"aria-busy":$,className:`lockerverse-payment__form`,noValidate:!0,onSubmit:ze,children:[A(`div`,{"data-lockerverse-input-region":``,inert:$?!0:void 0,children:j(`fieldset`,{className:`lockerverse-payment__input-fieldset`,disabled:$,children:[A(g,{displayedBaseCents:Pe,displayedTipCents:Ne,displayedTotalCents:Z,quote:h,shippingPending:ge.pending}),A(de,{enabled:e.widget.fields.tipping,error:ne,errorId:Me,onChange:Re,values:q}),A(xt,{email:M,emailDiscountPercentOff:h.appliedDiscount?.source===`email_list`?h.appliedDiscount.percentageOff:void 0,emailErrorId:ke,emailId:Oe,emailRef:ue,errors:R,onEmailBlur:()=>X.commands.refreshAuthoritativeTotal(),onEmailChange:e=>{N(e),Le(`email`)},onPhoneChange:({value:e,country:t})=>{ee(e),te(t),Le(`phone`)},phone:P,phoneCountry:F,phoneEnabled:e.widget.fields.phone,phoneErrorId:je,phoneId:Ae,phoneRef:J}),A(St,{message:Ie}),A(_t,{catalog:e,displayedTotalCents:Z,fieldValues:q,isBillingAddressReady:ie,isPaymentReady:W,isShippingAddressReady:oe,onAddressChange:(e,t)=>{le(n=>({...n,[e]:t}))},onFieldValuesChange:Re,onStripeLoadError:U,setIsBillingAddressReady:ae,setIsPaymentReady:G,setIsShippingAddressReady:K}),A(Se,{disabled:$,onCalculate:()=>{X.commands.fieldChanged(),ge.calculate()},shipping:ge}),A(pe,{customFields:E,errors:B,fields:e.widget.fields,idPrefix:De,isPromoApplying:ye,memberIdLabel:e.community?.memberIdLabel,onApplyPromo:X.commands.applyPromo,onChange:Re,promoError:we,values:q}),A(vt,{catalog:e,displayedTotalCents:Z,fieldValues:q,isBillingAddressReady:ie,isPaymentReady:W,isRequiredShippingReady:be(Fe,ge.ready),isSubmitting:$,onFieldValuesChange:Re,quote:h})]})}),$?A(`p`,{className:`lockerverse-payment__sr-only`,ref:fe,role:`status`,tabIndex:-1,children:Z===0?`Completing order…`:`Processing payment…`}):null,A(gt,{message:Ce})]})}function Tt(){return A(h,{fieldCount:2,label:`Loading payment…`,sectionCount:2,showCheckbox:!0})}function Et(e,t){switch(t.type){case`loading`:return{phase:`loading`,revision:e.revision};case`ready`:return At(t.displayedQuote,e.revision+1);case`error`:return{failure:t.failure,phase:`error`,revision:e.revision};case`checkout`:return e.phase===`ready`?{...e,displayedQuote:t.checkout,quoteFailure:void 0}:e;case`quote-error`:return e.phase===`ready`?{...e,quoteFailure:t.failure}:e;default:return e}}function Dt(e,t,n){return e?.catalog===t&&e.selectionKey===n}function Ot({checkout:e}){return{displayedQuote:e,type:`ready`}}function kt(e){return e instanceof Error?e.message:`Lockerverse payment could not load.`}function At(e,t){return{checkoutItems:[...e.items],displayedQuote:e,phase:`ready`,quoteFailure:void 0,revision:t}}function jt(e,t){let n=e.widget.fields.serviceFee;return N(e,{includeServiceFee:n,selection:t})}function Mt(e,t){try{return At(jt(e,t),1)}catch(e){return{failure:kt(e),phase:`error`,revision:0}}}function Nt({catalog:e,client:t,paymentState:n,selection:r}){let i=Fe(r),a=i.success?JSON.stringify(i.value):`invalid-selection`,o=T(()=>i.success?i.value:[],[i.success,a]),[s,c]=E(Et,void 0,()=>i.success?Mt(e,o):{phase:`loading`,revision:0}),l=D(void 0),u=D(0),d=D(s.phase===`ready`?{catalog:e,selectionKey:a}:void 0),f=D(s.phase===`error`?{catalog:e,selectionKey:a}:void 0),p=n===`submitting`||n===`success`||n===`unresolved`;S(()=>{if(!i.success||p||Dt(f.current,e,a)||Dt(l.current,e,a))return;let n=!0;l.current={catalog:e,selectionKey:a};let r=Dt(d.current,e,a);r||c({type:`loading`});function s(e){n&&c(e)}function m(){n&&(l.current=void 0,f.current={catalog:e,selectionKey:a})}let h;function g(t){if(!n||(l.current=void 0,f.current={catalog:e,selectionKey:a},r&&h!==void 0&&u.current!==h))return;let i=kt(t);if(i===`This option is sold out.`){c({failure:i,type:`error`});return}c(r?{failure:i,type:`quote-error`}:{failure:i,type:`error`})}async function _(){try{h=u.current;let n=e.widget.fields.serviceFee;if(!r){let t=jt(e,o);r=!0,d.current={catalog:e,selectionKey:a},s(Ot({checkout:t}))}let i=await t.calculateTotal({catalog:e,includeServiceFee:n,selection:o});m(),u.current===h&&s({checkout:i,type:`checkout`})}catch(e){g(e)}}return _(),()=>{n=!1,Dt(l.current,e,a)&&(l.current=void 0)}},[e,t,i.success,p,a,o]);let m=Dt(d.current,e,a)||Dt(f.current,e,a)||Dt(l.current,e,a),h=p||m?s:{phase:`loading`,revision:s.revision};return{selectionError:i.success?void 0:i.message,session:h,updateCheckout:e=>{u.current+=1,c({checkout:e,type:`checkout`})}}}const Pt=H({recovery:H({connectedAccountId:ne(K()),paymentReference:W(K(),q(),V())}),selectionFingerprint:K(),version:se([R(1),R(2)]),widgetId:U(K())});function Ft(e){let t=Fe(e);return t.success?JSON.stringify(t.value.map(e=>{let t=e.productSlug.trim();return`quantity`in e?[`quantity`,t,e.quantity]:`amountCents`in e?[`amount`,t,e.amountCents]:[`product`,t]})):null}const It=`A previous payment uses different checkout details. Return to its original checkout to check the payment before you pay again.`;function Lt(e,t,n){let r;try{r=window.sessionStorage.getItem(e)}catch{return{recovery:null}}if(!r)return{recovery:null};try{let e=ae(Pt,JSON.parse(r));if(!e.success)throw Error(`Invalid recovery record`);let i=e.output;return i.selectionFingerprint!==t||i.version===2&&i.widgetId!==n?{error:It,recovery:null}:{recovery:{connectedAccountId:i.recovery.connectedAccountId,paymentReference:i.recovery.paymentReference}}}catch{return{error:`The saved payment could not be read. Contact support to check it before you pay again.`,recovery:null}}}function Rt({selection:e,storageKey:t,widgetId:n}){let r=Ft(e),i=JSON.stringify([t,r,n]),[a,o]=O(null),s=D(null);S(()=>{if(!t)return;let e=s.current,a={recovery:null};e?.recovery?a=e.identity===i?{recovery:e.recovery}:{error:It,recovery:null}:r!==null&&(a=Lt(t,r,n)),a.recovery&&(s.current={identity:i,recovery:a.recovery}),o({identity:i,...a})},[r,i,t,n]);let c=x(e=>{if(!(!t||r===null)){s.current=e?{identity:i,recovery:e}:null;try{e?window.sessionStorage.setItem(t,JSON.stringify({recovery:e,selectionFingerprint:r,version:2,widgetId:n})):window.sessionStorage.removeItem(t)}catch{}}},[r,i,t,n]);return{error:t&&a?.identity===i?a.error:void 0,ready:!t||a?.identity===i,recovery:t&&a?.identity===i?a.recovery:null,remember:c}}const zt={annually:`/year`,"every-six-months":` every 6 months`,monthly:`/month`,"one-time":``};function Bt({branding:e,catalog:t}){return j(`header`,{children:[t.widget.showCommunityBranding&&e?j(`div`,{className:`lockerverse-payment__branding`,children:[e.imageUrl?A(`img`,{alt:e.name,height:`48`,src:e.imageUrl,width:`48`}):null,A(`strong`,{children:e.name})]}):null,A(`h1`,{children:t.widget.title??t.widget.name}),t.widget.description?A(`p`,{children:t.widget.description}):null]})}function Vt({catalog:t,selection:n}){let r=n?.length?t.products.filter(e=>n.some(t=>t.productSlug===e.slug)):t.products;return r.length===0?null:j(`div`,{className:`lockerverse-payment__payment-summary`,children:[A(`h2`,{children:`Products`}),A(`div`,{className:`lockerverse-payment__payment-summary-items`,children:r.map(t=>{let n=t.pricingMode===`fixed`?t.amountCents:t.minimumAmountCents,r=zt[t.paymentOption];return j(`div`,{className:`lockerverse-payment__payment-summary-row`,children:[A(`span`,{children:t.name}),A(`strong`,{children:n===null?`Choose amount`:`${t.pricingMode===`custom`?`From `:``}${e(n)}${r}`})]},t.id)})}),A(`p`,{children:`Base prices. Final total is checked at checkout.`})]})}function Ht(e,t){let i=n(e?.[`--lockerverse-accent`]??t?.accentColor??`#38d77a`),a=r(i),o={...e};return(e?.[`--lockerverse-accent`]!==void 0||t?.accentColor)&&(o[`--lockerverse-accent`]=i),a&&e?.[`--lockerverse-accent-contrast`]===void 0&&(o[`--lockerverse-accent-contrast`]=a),{accent:i,rootStyle:o}}function Ut({catalog:e,client:n,loadError:r,onRetry:i,...a}){let{branding:o,className:s,completionView:c,recoveryStorageKey:l,initialCustomFieldValues:u,metadata:d,onPaymentComplete:f,onPaymentRecoveryChange:p,onPaymentUncertain:m,resumePayment:h,selection:g,style:_,stripeLoader:v=ct,theme:y=`dark`,...b}=a,[C,T]=O(h),E=D(null),[k,M]=O(null),N=x(e=>{M(e),t(f,e)},[f]),[P,ee]=O(),[F,I]=O(`idle`),L=D(void 0),{selectionError:te,session:R,updateCheckout:z}=Nt({catalog:e,client:n,paymentState:F,selection:g}),B=R.phase===`ready`?R.revision:void 0,V=x(e=>{B!==void 0&&(L.current=B),I(e)},[B]),ne=x(e=>p?.(e),[p]),re=x(()=>{T(void 0)},[]);S(()=>{R.phase===`loading`&&ee(void 0)},[R.phase]),w(()=>{R.phase===`ready`&&L.current!==R.revision&&I(e=>e===`success`||e===`unresolved`?e:`idle`)},[R.phase,R.revision]);let H=[`lockerverse-payment`,s].filter(Boolean).join(` `),U=o??e.community,{accent:W,rootStyle:G}=Ht(_,U);return k&&c===`summary`?A(`section`,{...b,className:H,"data-lockerverse-theme":y,"data-payment-state":`success`,style:G,children:j(`div`,{className:`lockerverse-payment__completion`,role:`status`,children:[A(`span`,{"aria-hidden":`true`,className:`lockerverse-payment__completion-icon`,children:A(`svg`,{"aria-hidden":`true`,fill:`none`,height:`28`,stroke:`currentColor`,strokeWidth:`2`,viewBox:`0 0 24 24`,width:`28`,children:A(`path`,{d:`m5 12 4 4L19 6`})})}),A(`h1`,{children:k.paymentRequired?`Thank you`:`Order confirmed`}),A(`p`,{children:k.paymentRequired?`Your payment has been received.`:`Your order is confirmed. No payment was required.`})]})}):te?A(`section`,{...b,className:H,"data-lockerverse-theme":y,role:`alert`,style:G,children:te}):R.phase===`error`&&R.failure===`This option is sold out.`||F===`sold_out`?j(`section`,{...b,className:H,"data-lockerverse-theme":y,role:`alert`,style:G,children:[A(`h1`,{children:`Sold out`}),A(`p`,{children:`This option is sold out.`})]}):R.phase===`error`?A(`section`,{...b,className:H,"data-lockerverse-theme":y,style:G,children:A(`p`,{role:`alert`,children:R.failure})}):R.phase===`ready`?j(`section`,{...b,"aria-label":`Payment`,className:H,"data-lockerverse-theme":y,"data-payment-state":F,ref:E,style:G,children:[A(Bt,{branding:U,catalog:e}),r?j(`div`,{role:`alert`,children:[A(`p`,{children:r.message}),A(`button`,{onClick:i,type:`button`,children:`Retry`})]}):null,P?A(`p`,{className:`lockerverse-payment__payment-status`,role:`status`,children:P}):null,R.quoteFailure?j(`div`,{className:`lockerverse-payment__payment-status`,role:`alert`,children:[A(`span`,{children:R.quoteFailure}),A(`span`,{children:` The final total will be checked when you submit.`})]}):null,A(ft,{accentColor:W,appearanceRoot:E,catalog:e,checkoutItems:R.checkoutItems,client:n,initialCustomFieldValues:u,metadata:d,onPaymentComplete:N,onPaymentRecoveryChange:ne,onPaymentUncertain:m,onQuoteChange:(e,t)=>{ee(t),z(e)},onResumePaymentFailed:re,onStateChange:V,quote:R.displayedQuote,resumePayment:C,stripeLoader:v,theme:y,visualStyle:G},R.revision)]}):j(`section`,{...b,"aria-busy":`true`,"aria-label":`Payment`,className:H,"data-lockerverse-theme":y,style:G,children:[A(Bt,{branding:U,catalog:e}),r?j(`div`,{role:`alert`,children:[A(`p`,{children:r.message}),A(`button`,{onClick:i,type:`button`,children:`Retry`})]}):null,A(Tt,{})]})}function Wt({children:e,loading:t=!1,viewProps:i}){let{branding:a,className:o,completionView:s,recoveryStorageKey:c,initialCustomFieldValues:l,metadata:u,onPaymentComplete:d,onPaymentRecoveryChange:f,onPaymentUncertain:p,resumePayment:m,selection:h,stripeLoader:g,style:_,theme:v=`dark`,...y}=i,b=n(_?.[`--lockerverse-accent`]??a?.accentColor??`#38d77a`),x=r(b),S={..._};return(_?.[`--lockerverse-accent`]!==void 0||a?.accentColor)&&(S[`--lockerverse-accent`]=b),x&&_?.[`--lockerverse-accent-contrast`]===void 0&&(S[`--lockerverse-accent-contrast`]=x),A(`section`,{...y,...t?{"aria-busy":!0,"aria-label":`Payment`}:{},className:[`lockerverse-payment`,o].filter(Boolean).join(` `),"data-lockerverse-theme":v,style:S,children:e})}function Gt(e){let{catalog:n,client:r,loadError:i,onRetry:a,...o}=e,{onPaymentRecoveryChange:s,recoveryStorageKey:c,resumePayment:l,selection:u}=o,d=Rt({selection:u,storageKey:c,widgetId:n.widget.id}),f=x(e=>{d.remember(e),t(s,e)},[s,d.remember]);return!d.ready||d.error?A(Wt,{loading:!d.ready,viewProps:o,children:d.error?A(`p`,{role:`alert`,children:d.error}):A(Tt,{})}):A(Ut,{...e,onPaymentRecoveryChange:f,resumePayment:l??d.recovery})}function Kt({widget:e,...t}){return e.error&&!e.catalog?j(Wt,{viewProps:t,children:[A(`p`,{role:`alert`,children:e.error.message}),A(`button`,{onClick:e.refresh,type:`button`,children:`Retry`})]}):e.loading?j(Wt,{loading:!0,viewProps:t,children:[e.catalog?j(k,{children:[A(Bt,{branding:t.branding??e.catalog.community,catalog:e.catalog}),A(Vt,{catalog:e.catalog,selection:t.selection})]}):null,A(Tt,{})]}):e.catalog?A(Gt,{catalog:e.catalog,client:e.client,loadError:e.error,onRetry:e.refresh,...t}):A(Wt,{loading:!0,viewProps:t,children:A(Tt,{})})}export{lt as n,Kt as t};
|
|
1
|
+
import{t as e}from"./format-money.js";import{t}from"./host-callback.js";import{n,t as r}from"./accent-contrast.js";import{d as i,i as a,n as o,p as s,t as c,u as l}from"./phone-field.js";import{a as u,i as d,n as f,r as p,s as m}from"./custom-fields.js";import{t as h}from"./form-skeleton.js";import{t as g}from"./payment-summary.js";import{i as _,n as v,r as y,t as b}from"./stripe-loader.js";import{useCallback as x,useEffect as S,useId as ee,useLayoutEffect as C,useMemo as w,useReducer as T,useRef as E,useState as D}from"react";import{Fragment as O,jsx as k,jsxs as A}from"react/jsx-runtime";import{LockerverseSdkError as j,estimateLockerverseCheckout as M}from"@lockerverse/sdk/checkout";import{AddressElement as N,Elements as P,PaymentElement as F,useElements as I,useStripe as L}from"@stripe/react-stripe-js";import{array as R,literal as z,minLength as te,minValue as B,nonEmpty as ne,nullable as re,number as ie,object as V,optional as H,pipe as U,regex as W,safeInteger as ae,safeParse as oe,strictObject as se,string as G,trim as ce,union as le}from"valibot";function ue({ariaDescribedBy:e,ariaLabel:t,ariaLabelledBy:n,className:r,id:i,invalid:a=!1,name:o,onValueChange:s,options:c,value:l}){return k(`select`,{"aria-describedby":e,"aria-invalid":a||void 0,"aria-label":t,"aria-labelledby":n,className:[`lockerverse-form__control`,`lockerverse-form__select`,r].filter(Boolean).join(` `),id:i,name:o,onChange:e=>s(e.currentTarget.value),value:l,children:c.map(e=>k(`option`,{value:e.value,children:e.label},e.value))})}const de=[`XS`,`S`,`M`,`L`,`XL`,`XXL`,`XXXL`],fe=[`15`,`12`,`10`,`5`],K=[...fe,`custom`];function pe({enabled:e,error:t,errorId:n,onChange:r,values:i}){if(!e)return null;let a=e=>r({...i,...e}),o=(e,t)=>{let n=K.indexOf(t),r;switch(e.key){case`ArrowDown`:case`ArrowRight`:r=(n+1)%K.length;break;case`ArrowLeft`:case`ArrowUp`:r=(n-1+K.length)%K.length;break;case`Home`:r=0;break;case`End`:r=K.length-1;break;default:return}e.preventDefault();let i=K[r];i&&((e.currentTarget.closest(`[role="radiogroup"]`)?.querySelectorAll(`input[type="radio"]`))?.[r]?.focus(),a({tipPercent:i}))};return A(`div`,{className:`lockerverse-payment__tip-box`,children:[k(`p`,{children:`Add a tip to support the Lockerverse platform`}),A(`div`,{"aria-label":`Tip amount`,role:`radiogroup`,children:[fe.map(e=>A(`label`,{className:`lockerverse-payment__tip-choice`,children:[k(`input`,{checked:i.tipPercent===e,name:`tipPercent`,onChange:()=>a({tipPercent:e}),onKeyDown:t=>o(t,e),tabIndex:i.tipPercent===e?0:-1,type:`radio`,value:e}),A(`span`,{children:[e,`%`]})]},e)),A(`label`,{className:`lockerverse-payment__tip-choice`,children:[k(`input`,{checked:i.tipPercent===`custom`,name:`tipPercent`,onChange:()=>a({tipPercent:`custom`}),onKeyDown:e=>o(e,`custom`),tabIndex:i.tipPercent===`custom`?0:-1,type:`radio`,value:`custom`}),k(`span`,{children:`Other`})]})]}),i.tipPercent===`custom`?A(`label`,{children:[k(`span`,{children:`Custom tip`}),A(`span`,{className:`lockerverse-payment__money-input`,children:[k(`span`,{"aria-hidden":`true`,children:`$`}),k(`input`,{"aria-describedby":t?n:void 0,"aria-invalid":t?`true`:void 0,inputMode:`decimal`,name:`tip`,onChange:e=>a({customTip:e.currentTarget.value}),placeholder:`0.00`,value:i.customTip})]}),t?k(`span`,{className:`lockerverse-payment__field-message`,id:n,children:t}):null]}):k(`input`,{name:`tip`,type:`hidden`,value:i.tipPercent})]})}function q({checked:e,children:t,name:n,onChange:r}){let i=ee();return A(`label`,{className:`lockerverse-payment__check-row`,htmlFor:i,children:[k(l,{checked:e,id:i,name:n,onChange:e=>r(e.currentTarget.checked)}),k(`span`,{children:t})]})}function me({customFields:e,errors:t,fields:n,idPrefix:r,isPromoApplying:i,memberIdLabel:a,onChange:o,onApplyPromo:s,promoError:c,values:l}){let u=e=>o({...l,...e});return A(`div`,{className:`lockerverse-payment__additional-fields`,children:[n.memberId?A(`label`,{children:[k(`span`,{children:a?.trim()||`Member ID`}),k(`input`,{name:`memberId`,onChange:e=>u({memberId:e.currentTarget.value}),placeholder:`Optional`,value:l.memberId})]}):null,n.merchSize?A(`div`,{className:`lockerverse-payment__field`,children:[k(`span`,{id:`${r}-merch-size-label`,children:`Size`}),k(ue,{ariaLabelledBy:`${r}-merch-size-label`,name:`merchSize`,onValueChange:e=>{let t=de.find(t=>t===e);t&&u({merchSize:t})},options:de.map(e=>({label:e,value:e})),value:l.merchSize})]}):null,n.promoCode?A(`div`,{className:`lockerverse-payment__field`,children:[k(`span`,{id:`${r}-promo-code-label`,children:`Promo code`}),A(`div`,{className:`lockerverse-payment__promo-control`,children:[k(`input`,{"aria-describedby":c?`${r}-promo-code-error`:void 0,"aria-invalid":c?`true`:void 0,"aria-labelledby":`${r}-promo-code-label`,name:`promoCode`,onChange:e=>u({promoCode:e.currentTarget.value}),placeholder:`Optional`,value:l.promoCode}),k(`button`,{disabled:!l.promoCode.trim()||i,onClick:s,type:`button`,children:i?`Applying…`:`Apply`})]}),c?k(`p`,{className:`lockerverse-payment__field-message`,id:`${r}-promo-code-error`,role:`alert`,children:c}):null]}):null,k(f,{choiceClassName:`lockerverse-payment__check-row`,errorClassName:`lockerverse-payment__field-message`,errors:t,fields:e,idPrefix:r,onChange:e=>u({customFields:e}),values:l.customFields})]})}function J({amountCents:t,enabled:n,onChange:r,values:i}){return n?A(q,{checked:i.includeServiceFee,name:`includeServiceFee`,onChange:e=>r({...i,includeServiceFee:e}),children:[`Add `,e(t),` to help cover processing fees`]}):null}function Y(e){return{error:void 0,message:void 0,status:e?`recovering`:`editing`}}function X(e,t,n){return t.includes(e.status)?{...e,...n}:e}function he(e,t){if(t.type===`recovery_started`&&e.status===`unresolved`)return{...e,message:void 0,status:`recovering`};if(e.status===`sold_out`||e.status===`succeeded`||e.status===`unresolved`)return e;switch(t.type){case`field_changed`:return X(e,[`editing`,`invalid`,`refreshing_quote`],{error:void 0,status:`editing`});case`validation_failed`:return X(e,[`editing`],{status:`invalid`});case`quote_refresh_started`:return X(e,[`editing`,`invalid`],{status:`refreshing_quote`});case`quote_refresh_succeeded`:return X(e,[`refreshing_quote`],{error:void 0,status:`editing`});case`quote_refresh_failed`:return X(e,[`refreshing_quote`],{error:t.error??e.error,status:`editing`});case`submission_started`:return X(e,[`editing`,`invalid`,`refreshing_quote`],{error:void 0,status:`submitting`});case`submission_validation_failed`:return X(e,[`submitting`],{error:void 0,status:`invalid`});case`quote_changed`:return X(e,[`submitting`],{status:`editing`});case`retryable_failure`:return X(e,[`editing`,`invalid`,`submitting`],{error:t.error,status:`editing`});case`recovery_failed`:return X(e,[`recovering`],{error:t.error,retryUrl:void 0,status:`editing`});case`sold_out`:return{error:void 0,message:void 0,status:`sold_out`};case`succeeded`:return X(e,[`recovering`,`submitting`],{message:t.message,retryUrl:void 0,status:`succeeded`});case`unresolved`:return X(e,[`recovering`,`submitting`],{message:t.message,retryUrl:t.retryUrl,status:`unresolved`});default:return e}}function Z(e){return e.status===`editing`||e.status===`invalid`||e.status===`refreshing_quote`?e.error:void 0}function Q(e){return e.status===`sold_out`?`sold_out`:e.status===`succeeded`?`success`:e.status===`unresolved`?`unresolved`:e.status===`submitting`||e.status===`recovering`?`submitting`:e.status===`invalid`?`invalid`:Z(e)?`error`:`idle`}function ge(e){return e.status===`submitting`}const _e=[`amountCents`,`discountableSubtotalCents`,`discountCents`,`serviceFeeCents`,`subtotalCents`,`tipCents`,`totalCents`],ve=[`discountableSubtotalCents`,`discountCents`,`subtotalCents`];function ye(e,t,n,r){return(n===t.totalCents?ve:_e).some(n=>e[n]!==t[n])||r!==t.payment.connectedAccountId||e.authoritative&&(e.payment.connectedAccountId!==r||e.payment.currency!==t.payment.currency)||JSON.stringify(e.appliedDiscount)!==JSON.stringify(t.appliedDiscount)||JSON.stringify(e.lineItems)!==JSON.stringify(t.lineItems)}function be(e){if(e.checkoutStatus===`success`)return{kind:`success`,payment:e};if(e.checkoutStatus===`failed`)return{kind:`failed`,payment:e};let t={kind:`unresolved`,paymentReference:e.paymentReference,reason:e.checkoutStatus===`action_required`?`action_required`:`pending`};return e.retryUrl&&(t.retryUrl=e.retryUrl),t}async function xe(e,t,n){if(t.checkoutStatus!==`action_required`||!t.requiresAction)return be(t);if(!n)return{kind:`unresolved`,paymentReference:t.paymentReference,reason:`action_required`};if(t.clientSecret)try{await n.handleNextAction({clientSecret:t.clientSecret})}catch{}try{return be(await e.getPaymentStatus(t.paymentReference))}catch{return{kind:`unresolved`,paymentReference:t.paymentReference,reason:`action_required`}}}async function Se(e,t,n){let r;try{r=await e.submitPayment(t)}catch(n){if(!(n instanceof j&&n.recoveryRecommended))throw n;try{r=await e.getPaymentStatus(t.checkout.paymentReference)}catch{return{kind:`unresolved`,paymentReference:t.checkout.paymentReference,reason:`recovery_failed`}}}return xe(e,r,n)}async function Ce(e,t,n){try{return xe(e,await e.getPaymentStatus(t),n)}catch{return{kind:`unresolved`,paymentReference:t,reason:`recovery_failed`}}}const we=U(G(),ce(),ne()),Te=U(ie(),ae(),B(1)),Ee=U(R(le([se({amountCents:Te,productSlug:we}),se({productSlug:we,quantity:Te}),se({productSlug:we})])),te(1)),De=U(G(),ce(),W(/^(?:0|[1-9]\d*)(?:\.\d{1,2})?$/,`Enter a valid tip amount.`));function Oe(e){let t=oe(De,e);if(!t.success)return{message:t.issues[0]?.message??`Enter a valid tip amount.`,success:!1};let[n=`0`,r=``]=t.output.split(`.`),i=BigInt(n)*100n+BigInt(r.padEnd(2,`0`));return i>BigInt(2**53-1)?{message:`Enter a valid tip amount.`,success:!1}:{cents:Number(i),success:!0}}function ke(e){let t=oe(Ee,e);return t.success?{success:!0,value:t.output}:{message:`Lockerverse payment configuration is invalid.`,success:!1}}const Ae=`This promo code is invalid or cannot be applied.`;function je(e,t){return t.tipPercent===`custom`?t.customTip.trim()?Oe(t.customTip):{cents:0,success:!0}:{cents:Math.round(e*Number(t.tipPercent)/100),success:!0}}function Me(e,t,n,r){let i={};return n&&(i.email=n),e.widget.fields.serviceFee&&(i.includeServiceFee=t.includeServiceFee),e.widget.fields.promoCode&&t.promoCode.trim()&&(i.promoCode=t.promoCode.trim()),e.widget.fields.tipping&&(i.tipCents=r),i}function Ne(e,t,n){let r=e.widget.fields.tipping?je(n.subtotalCents,t):{cents:0,success:!0};if(!r.success)return{parsedTip:r,totalCents:null};let i=e.widget.fields.serviceFee&&t.includeServiceFee?n.serviceFeeCents||Math.round(n.subtotalCents*e.pricingPolicy.serviceFeeRateBasisPoints/1e4):0;return{parsedTip:r,totalCents:n.totalCents-n.serviceFeeCents-n.tipCents+i+r.cents}}function Pe(e,t){return{displayedTotalCents:e.totalCents,promoError:t&&e.appliedDiscount?.source!==`promo_code`?Ae:void 0}}function Fe(e,t){let n;return t||(n=e instanceof Error?e.message:`The order total could not be updated.`),{paymentError:n,promoError:t?Ae:void 0}}function Ie(e,t){if(!e?.complete)throw Error(`${t} address is required.`);return e.value}function Le(e,t,n,r){if(e.widget.fields.shipping)return t.shippingMatchesBilling?n:Ie(r.shipping,`Shipping`)}function Re({billingAddress:e,catalog:t,email:n,phone:r,shippingAddress:i}){let a={payment_method_data:{billing_details:t.widget.fields.phone?{address:e.address,email:n,name:e.name,phone:r}:{address:e.address,email:n,name:e.name}}};return i?{...a,shipping:{address:i.address,name:i.name,phone:t.widget.fields.phone?r:i.phone??null}}:a}function ze({catalog:e,checkoutItems:t,confirmationToken:n,email:r,fieldValues:i,metadata:a,phone:o,shippingAddress:s}){let c={customFieldAnswers:p(u(e,t),i.customFields),email:r};if(n&&(c.confirmationToken=n,c.paymentMethodConfiguration=`explicit`),a&&(c.metadata=a),e.widget.fields.memberId&&i.memberId.trim()&&(c.memberId=i.memberId.trim()),e.widget.fields.merchSize&&(c.merchSize=i.merchSize),e.widget.fields.phone&&(c.phone=o),s){let e={city:s.address.city??``,country:s.address.country,line1:s.address.line1??``,postal_code:s.address.postal_code??``,state:s.address.state??``};s.address.line2&&(e.line2=s.address.line2),c.shipping={address:e,name:s.name}}return c}function Be(e){if(!e())throw Error(`Payment component is no longer active.`)}function Ve(e,n){t(e,n)}function He(e,t,n,r){return e.kind===`failed`?{kind:`payment_failed`,message:r}:e.kind===`unresolved`?{kind:`payment_unresolved`,paymentReference:e.paymentReference,reason:e.reason,retryUrl:e.retryUrl}:{email:n,kind:`payment`,payment:e.payment,quote:t}}async function Ue({addresses:e,catalog:t,checkoutItems:n,client:r,elements:i,email:a,fieldValues:o,isAttemptActive:s,locallyPreviewedTotalCents:c,metadata:l,onPaymentRecoveryChange:u,phone:d,quote:f,stripe:p,stripeConnectedAccountId:m}){let h=a.trim().toLowerCase(),g=y(d),_=je(f.subtotalCents,o);if(!_.success)throw Error(_.message);let v=await r.calculateTotal({...Me(t,o,h,_.cents),catalog:t,items:n});if(Be(s),v.totalCents>0&&ye(f,v,c,m))return{kind:`quote_changed`,quote:v};let b,x;if(v.totalCents===0)t.widget.fields.shipping&&(b=Le(t,o,Ie(e.billing,`Billing`),e));else{if(!(i&&p))throw Error(`Payment form is still loading.`);await i.update({amount:v.totalCents}),Be(s);let n=await i.submit();if(Be(s),n.error)throw Error(n.error.message);let r=Ie(e.billing,`Billing`);b=Le(t,o,r,e);let a=await p.createConfirmationToken({elements:i,params:Re({billingAddress:r,catalog:t,email:h,phone:g,shippingAddress:b})});if(Be(s),a.error)throw Error(a.error.message);x=a.confirmationToken.id}Ve(u,{connectedAccountId:v.payment.connectedAccountId,paymentReference:v.paymentReference});let S=await Se(r,{checkout:v,submission:ze({catalog:t,checkoutItems:n,confirmationToken:x,email:h,fieldValues:o,metadata:l,phone:g,shippingAddress:b})},p);return Be(s),He(S,v,h,v.totalCents===0?`Order could not be completed. Review the details and try again.`:`Payment was declined. Check your payment details and try again.`)}function We(e,n){t(e,n)}function Ge(e,n){t(e,n)}function Ke(e,t){return{...e,...t}}function qe(e){let t={message:e.reason===`action_required`?`Payment needs your attention. Keep this checkout open.`:`Payment is not complete. Check its status before you try again.`,type:`unresolved`};return e.retryUrl&&(t.retryUrl=e.retryUrl),t}function Je(e,t,n){return e.kind===`unresolved`&&e.reason===`action_required`&&!e.retryUrl&&!t&&!n}function Ye(e){return e instanceof j&&e.serverCode===`PAYMENT_WIDGET_SALES_LIMIT_REACHED`}function Xe({nextQuote:e,onQuoteChange:t,setDisplayedTotalCents:n,setPromoError:r,updateState:i,validatePromo:a}){let o=Pe(e,a);i({type:`quote_refresh_succeeded`}),n(o.displayedTotalCents),t(e),a&&r(o.promoError)}function Ze({error:e,setPromoError:t,updateState:n,validatePromo:r}){let i=Fe(e,r);r&&t(i.promoError),n(i.paymentError===void 0?{type:`quote_refresh_failed`}:{error:i.paymentError,type:`quote_refresh_failed`})}function Qe({onPaymentComplete:n,onPaymentRecoveryChange:r,onPaymentUncertain:i,onQuoteChange:a,result:o,setDisplayedTotalCents:s,dispatchState:c,unresolvedReferenceRef:l}){if(o.kind===`quote_changed`){let t=`The total changed to ${e(o.quote.totalCents)}. Review it and pay again.`;a(o.quote,t),s(o.quote.totalCents),c({type:`quote_changed`});return}if(o.kind===`payment_failed`){We(r,null),c({error:o.message,type:`retryable_failure`});return}if(o.kind===`payment_unresolved`){l.current=o.paymentReference,c(qe(o)),Ge(i,{paymentReference:o.paymentReference,reason:o.reason});return}a(o.quote),We(r,null),c({message:o.payment.paymentRequired?`Payment completed successfully.`:`Order confirmed. No payment was required.`,type:`succeeded`}),t(n,Ke(o.payment,{email:o.email,lineItems:o.quote.lineItems}))}function $e(e){let{catalog:n,checkoutItems:r,client:i,elements:o,email:s,fieldValues:c,metadata:l,onPaymentComplete:u,onResumePaymentFailed:d,onPaymentRecoveryChange:f,onPaymentUncertain:p,onQuoteChange:m,onStateChange:h,quote:g,resumePayment:v,stripe:y,stripeConnectedAccountId:b,stripeLoadFailed:ee,paymentState:C,updateState:w}=e,[T,O]=D(g.totalCents),[k,A]=D(),M=E(!1),N=E(void 0),P=E(0),F=E(0),I=x(e=>w(e,!0),[w]),L=x(()=>{let e=F.current+1;return F.current=e,()=>F.current===e},[]);S(()=>()=>{F.current+=1,P.current+=1},[]);let{parsedTip:R,totalCents:z}=Ne(n,c,g);S(()=>{z!==null&&(O(z),z>0&&o?.update({amount:z}))},[n.pricingPolicy.serviceFeeRateBasisPoints,n.widget.fields.serviceFee,o,c.includeServiceFee,z,g.serviceFeeCents,g.tipCents,g.totalCents,g.subtotalCents]),S(()=>{let e=v?.paymentReference??N.current;if(!e||M.current||C.status!==`recovering`)return;M.current=!0;let n=L();return h(Q(C)),Ce(i,e,y).then(e=>{if(n()&&!Je(e,y,ee)){if(e.kind===`failed`){We(f,null),d(),I({error:`The previous payment failed. Check your details and try again.`,type:`recovery_failed`});return}if(e.kind===`unresolved`){I(qe(e)),Ge(p,{paymentReference:e.paymentReference,reason:e.reason});return}We(f,null),I({message:e.payment.paymentRequired?`Payment completed successfully.`:`Order confirmed. No payment was required.`,type:`succeeded`}),t(u,Ke(e.payment,{email:null,lineItems:null}))}}),()=>{n()&&(F.current+=1),M.current=!1}},[i,u,d,f,p,h,v,y,ee,L,I,C]);let te=x((e=!1,t=!1)=>{t||(P.current+=1),e&&A(void 0),w({type:`field_changed`})},[w]);async function B(e=!1,t=!1){let a=s.trim().toLowerCase(),o=_({email:a,phone:``},!1);if(!(R.success&&(o.value||e)))return;P.current+=1;let l=P.current;w({type:`quote_refresh_started`});try{let e=await i.calculateTotal({...Me(n,c,o.value?.email??``,R.cents),catalog:n,items:r});if(l!==P.current)return;Xe({nextQuote:e,onQuoteChange:m,setDisplayedTotalCents:O,setPromoError:A,updateState:w,validatePromo:t})}catch(e){if(l!==P.current)return;if(Ye(e)){w({type:`sold_out`});return}Ze({error:e,setPromoError:A,updateState:w,validatePromo:t})}}async function ne(){A(void 0),await B(!0,!0)}async function re({addresses:e,phone:t}){I({type:`submission_started`});let d=L();try{let a=await Ue({addresses:e,catalog:n,checkoutItems:r,client:i,elements:o,email:s,fieldValues:c,isAttemptActive:d,locallyPreviewedTotalCents:T,metadata:l,onPaymentRecoveryChange:f,phone:t,quote:g,stripe:y,stripeConnectedAccountId:b});if(!d())return;Qe({dispatchState:I,onPaymentComplete:u,onPaymentRecoveryChange:f,onPaymentUncertain:p,onQuoteChange:m,result:a,setDisplayedTotalCents:O,unresolvedReferenceRef:N})}catch(e){if(!d())return;if(We(f,null),Ye(e)){I({type:`sold_out`});return}let t=e instanceof j?a(e.serverCode):void 0;if(t)return I({type:`submission_validation_failed`}),{phoneError:t};I({error:e instanceof Error?e.message:`Payment could not be completed.`,type:`retryable_failure`})}}let ie=C.status===`succeeded`||C.status===`unresolved`?C.message:void 0;return{commands:{applyPromo:ne,checkPaymentStatus:()=>I({type:`recovery_started`}),fieldChanged:te,refreshAuthoritativeTotal:B,reportValidationFailure:()=>I({type:`validation_failed`}),submit:re},state:{displayedTotalCents:T,isRecovering:C.status===`recovering`,isRefreshingQuote:C.status===`refreshing_quote`,isSubmitting:ge(C),isUnresolved:C.status===`unresolved`,parsedTip:R,paymentError:Z(C),promoError:k,retryUrl:C.retryUrl,terminalMessage:ie}}}const et=b;function tt(e){let{connectedAccountId:t,publishableKey:n}=e.payment;return et(n,t?{stripeAccount:t}:void 0)}function nt(e){return e===`monthly`?{interval:`month`,label:`Monthly`}:e===`annually`?{interval:`year`,label:`Annual`}:e===`every-six-months`?{interval:`6 months`,label:`Every 6 months`}:null}function rt(e,t,n){if(n){let{connectedAccountId:e}=n;return e}if(`payment`in t){let{connectedAccountId:e}=t.payment;return e}let{connectedAccountId:r}=e.payment;return r}function it({accentColor:e,catalog:t,checkoutItems:n,client:r,appearanceRoot:i,initialCustomFieldValues:a,metadata:o,onPaymentComplete:s,onResumePaymentFailed:c,onPaymentRecoveryChange:l,onPaymentUncertain:u,onQuoteChange:d,quote:f,resumePayment:p,onStateChange:m,stripeLoader:g,theme:_,visualStyle:y}){let[b,ee]=D(()=>Y(!!p)),C=E(b);C.current=b;let T=x((e,t=!1)=>{let n=he(C.current,e);n!==C.current&&(C.current=n,ee(n),t&&m(Q(n)))},[m]),O=rt(t,f,p),A=E({connectedAccountId:O,paymentOption:f.paymentOption});b.status!==`submitting`&&b.status!==`recovering`&&(A.current={connectedAccountId:O,paymentOption:f.paymentOption});let{connectedAccountId:j,paymentOption:M}=A.current,N=w(()=>g(t.payment.publishableKey,j?{stripeAccount:j}:void 0).catch(()=>null),[t.payment.publishableKey,j,g]),[F,I]=D(!1);S(()=>{let e=!0;return I(!1),N.then(t=>{e&&t===null&&I(!0)}),()=>{e=!1}},[N]);let L=v(i,_,y,b.status===`submitting`||b.status===`recovering`,e);return L?k(P,{options:{amount:Math.max(f.totalCents,100),appearance:L,currency:t.payment.currency,mode:M===`one-time`?`payment`:`subscription`,paymentMethodTypes:t.community?.widgetAchEnabled?[`card`,`link`,`us_bank_account`]:[`card`,`link`],syncAddressCheckbox:`none`},stripe:N,children:k(_t,{catalog:t,checkoutItems:n,client:r,initialCustomFieldValues:a,metadata:o,onPaymentComplete:s,onPaymentRecoveryChange:l,onPaymentUncertain:u,onQuoteChange:d,onResumePaymentFailed:c,onStateChange:m,paymentState:b,quote:f,resumePayment:p,stripeConnectedAccountId:j,stripeLoadFailed:F,updateState:T})},`${t.payment.publishableKey}:${j??`platform`}:${M}`):k(h,{fieldCount:3,label:`Loading payment form`})}function at({label:e}){return A(`div`,{className:`lockerverse-payment__stripe-loader`,role:`status`,children:[k(`p`,{children:e}),A(`div`,{"aria-hidden":`true`,children:[k(`span`,{}),k(`span`,{}),k(`span`,{})]})]})}function ot({onError:e,onReady:t,ready:n}){return A(`div`,{className:`lockerverse-payment__stripe-element`,"data-ready":n,children:[n?null:k(at,{label:`Loading payment form...`}),k(`div`,{className:`lockerverse-payment__stripe-mount`,children:k(F,{onLoadError:({error:t})=>e(t.message??`Payment form failed to load.`),onReady:t,options:{business:{name:`Lockerverse`},fields:{billingDetails:{address:`never`,email:`never`,name:`never`,phone:`never`}},layout:`tabs`,terms:{applePay:`auto`,auBecsDebit:`never`,bancontact:`never`,card:`always`,cashapp:`never`,googlePay:`never`,ideal:`never`,paypal:`auto`,sepaDebit:`never`,sofort:`never`,usBankAccount:`auto`},wallets:{applePay:`auto`,googlePay:`never`}}})})]})}function st({label:e,mode:t,onChange:n,onError:r,onReady:i,ready:a}){return A(`div`,{className:`lockerverse-payment__address`,children:[k(`h2`,{children:e}),A(`div`,{className:`lockerverse-payment__stripe-element lockerverse-payment__stripe-element--address`,"data-ready":a,children:[a?null:k(at,{label:`Loading ${e.toLowerCase()}...`}),k(`div`,{className:`lockerverse-payment__stripe-mount`,children:k(N,{onChange:n,onLoadError:({error:t})=>r(t.message??`${e} failed to load.`),onReady:i,options:{autocomplete:{mode:`automatic`},mode:t}})})]})]})}function ct({message:e}){return e?k(`p`,{className:`lockerverse-payment__field-message`,role:`alert`,children:e}):null}function lt({catalog:e,displayedTotalCents:t,fieldValues:n,isBillingAddressReady:r,isPaymentReady:i,isShippingAddressReady:a,onAddressChange:o,onFieldValuesChange:s,onStripeLoadError:c,setIsBillingAddressReady:l,setIsPaymentReady:u,setIsShippingAddressReady:d}){let f=t>0;return A(O,{children:[f?k(ot,{onError:c,onReady:()=>u(!0),ready:i}):null,f||e.widget.fields.shipping?k(st,{label:f?`Billing address`:`Shipping address`,mode:`billing`,onChange:e=>o(`billing`,e),onError:c,onReady:()=>l(!0),ready:r}):null,e.widget.fields.shipping?A(`div`,{className:`lockerverse-payment__shipping`,children:[k(q,{checked:n.shippingMatchesBilling,name:`shippingMatchesBilling`,onChange:e=>{s({...n,shippingMatchesBilling:e}),e?o(`shipping`,null):d(!1)},children:`Shipping is same as billing information`}),n.shippingMatchesBilling?null:k(st,{label:`Shipping address`,mode:`shipping`,onChange:e=>o(`shipping`,e),onError:c,onReady:()=>d(!0),ready:a})]}):null]})}function ut({catalog:t,displayedTotalCents:n,fieldValues:r,isBillingAddressReady:i,isPaymentReady:a,isRequiredShippingReady:o,isSubmitting:s,onFieldValuesChange:c,quote:l}){let u=n===0,d=u?!t.widget.fields.shipping||i&&o:a&&i&&o,f=nt(l.paymentOption),p=u?`Complete order`:`Pay ${e(n)}`;!u&&f&&(p=`Subscribe for ${e(n)}/${f.interval}`),s&&(p=u?`Completing…`:`Processing…`);let m=`Process payment for ${e(n)} total`;return u?m=`Complete order`:f&&(m=`Start ${f.label.toLowerCase()} subscription for ${e(n)}`),A(`div`,{className:`lockerverse-payment__actions`,children:[k(J,{amountCents:l.serviceFeeCents||Math.round(l.subtotalCents*t.pricingPolicy.serviceFeeRateBasisPoints/1e4),enabled:t.widget.fields.serviceFee,onChange:c,values:r}),k(`button`,{"aria-busy":s,"aria-label":m,disabled:s||!d,type:`submit`,children:p})]})}function dt(e,t){let n=e.elements.namedItem(t);if(n instanceof HTMLElement){n.focus();return}n instanceof RadioNodeList&&Array.from(n).find(e=>e instanceof HTMLElement)?.focus()}function ft({customFieldErrors:e,emailRef:t,form:n,parsedTipSuccess:r,phoneRef:i,validationErrors:a}){if(a.email){t.current?.focus();return}if(a.phone){i.current?.focus();return}if(!r){n.querySelector(`[name="tip"]`)?.focus();return}let[o]=Object.keys(e);o&&dt(n,`custom:${o}`)}function pt(t){let n=t.appliedDiscount;if(n?.source!==`email_list`)return;let r=n.percentageOff===void 0?e(t.discountCents):`${n.percentageOff}%`;return n.message??`Your email qualifies for ${r} off.`}function mt({email:e,emailDiscountMessage:t,emailErrorId:n,emailId:r,emailRef:a,errors:o,onEmailBlur:l,onEmailChange:u,onPhoneChange:d,phone:f,phoneCountry:p,phoneEnabled:m,phoneErrorId:h,phoneId:g,phoneRef:_}){return A(`div`,{className:`lockerverse-payment__contact`,children:[k(i,{error:o.email,errorId:n,id:r,label:`Email`,name:`email`,onBlur:l,onChange:e=>u(e.currentTarget.value),ref:a,required:!0,value:e}),t===void 0?null:k(`p`,{className:`lockerverse-payment__discount-message`,role:`status`,children:t}),m?k(s,{error:o.phone,errorId:h,id:g,label:`Phone`,children:k(c,{country:p,error:o.phone,errorId:h,id:g,inputRef:_,name:`phone`,onChange:d,required:!0,value:f})}):null]})}function ht({message:e}){return e?A(`div`,{className:`lockerverse-payment__actions`,children:[k(`p`,{className:`lockerverse-payment__field-message`,role:`alert`,children:e}),k(`button`,{className:`lockerverse-payment__status-check`,onClick:()=>window.location.reload(),type:`button`,children:`Reload checkout`})]}):null}function gt({paymentRequired:e,shippingRequired:t,isPaymentReady:n,isBillingAddressReady:r,isRequiredShippingReady:i,isSubmitting:a,scriptFailed:o,elementError:s,clearElementError:c}){let[l,u]=D(!1),d=e||t,f=(!e||n)&&(!d||r)&&i;if(S(()=>{if(u(!1),f&&c(void 0),!d||f||a)return;let e=window.setTimeout(()=>u(!0),3e4);return()=>window.clearTimeout(e)},[d,f,a,c]),!(!d||f||a)){if(o||s)return`The secure checkout fields could not load. Check your connection, then reload the checkout.`;if(l)return`The secure checkout fields are taking longer than expected. You can wait or reload the checkout.`}}function _t({catalog:e,checkoutItems:t,client:n,initialCustomFieldValues:r,metadata:i,onPaymentComplete:a,onResumePaymentFailed:s,onPaymentRecoveryChange:c,onPaymentUncertain:l,onQuoteChange:f,onStateChange:p,quote:h,resumePayment:v,stripeConnectedAccountId:y,stripeLoadFailed:b,paymentState:x,updateState:C}){let w=u(e,t),[T,j]=D(``),[M,N]=D(``),[P,F]=D(`US`),[R,z]=D({}),[te,B]=D({}),[ne,re]=D(),[ie,V]=D(),[H,U]=D(!1),[W,ae]=D(!1),[oe,se]=D(!1),[G,ce]=D(()=>({customFields:d(w,r),customTip:``,includeServiceFee:e.widget.fields.serviceFee,memberId:``,merchSize:`M`,promoCode:``,shippingMatchesBilling:!0,tipPercent:`10`})),le=E({billing:null,shipping:null}),ue=E(null),de=E(null),fe=E(null),K=E(h.totalCents>0),q=$e({catalog:e,checkoutItems:t,client:n,elements:I(),email:T,fieldValues:G,metadata:i,onPaymentComplete:a,onPaymentRecoveryChange:c,onPaymentUncertain:l,onQuoteChange:f,onResumePaymentFailed:s,onStateChange:p,paymentState:x,quote:h,resumePayment:v,stripe:L(),stripeConnectedAccountId:y,stripeLoadFailed:b,updateState:C}),{displayedTotalCents:J,isRecovering:Y,isUnresolved:X,isRefreshingQuote:he,isSubmitting:Z,parsedTip:Q,paymentError:ge,promoError:_e,terminalMessage:ve,retryUrl:ye}=q.state,be=`lockerverse-${ee()}`,xe=`${be}-email`,Se=`${xe}-error`,Ce=`${be}-phone`,we=`${Ce}-error`,Te=`${be}-tip-error`,Ee=(Q.success?Q.cents:null)??0,De=J-Ee,Oe=!e.widget.fields.shipping||G.shippingMatchesBilling||oe,ke=gt({clearElementError:V,elementError:ie,isBillingAddressReady:W,isPaymentReady:H,isRequiredShippingReady:Oe,isSubmitting:Z,paymentRequired:J>0,scriptFailed:b,shippingRequired:e.widget.fields.shipping});S(()=>{Z&&fe.current?.focus({preventScroll:!0})},[Z]),S(()=>{Z||R.email||!R.phone||de.current?.focus()},[R.email,R.phone,Z]),S(()=>{let e=J>0;e&&!K.current&&(U(!1),ae(!1)),K.current=e},[J]);function Ae(e){q.commands.fieldChanged(!1,e!==`email`),z(t=>{let n={...t};return delete n[e],n})}function je(e){let t=e.promoCode!==G.promoCode,n=e.includeServiceFee!==G.includeServiceFee;q.commands.fieldChanged(t,!(t||n)),ce(e),B({}),re(void 0)}async function Me(t){t.preventDefault();let n=e.widget.fields.phone?o(M,P):``,r=_({email:T,phone:n},e.widget.fields.phone),i=m(w,G.customFields);if(!(r.value&&Q.success)||Object.keys(i).length>0){z(r.errors),B(i),re(Q.success?void 0:Q.message),q.commands.reportValidationFailure();let e=t.currentTarget;queueMicrotask(()=>{ft({customFieldErrors:i,emailRef:ue,form:e,parsedTipSuccess:Q.success,phoneRef:de,validationErrors:r.errors})});return}z({}),B({});let a=await q.commands.submit({addresses:le.current,phone:n});a?.phoneError&&z({phone:a.phoneError})}return ve||Y?A(`div`,{className:`lockerverse-payment__actions`,children:[A(`p`,{className:`lockerverse-payment__payment-status`,ref:fe,role:`status`,tabIndex:-1,children:[Y?`Recovering payment…`:ve,ye?A(O,{children:[` `,k(`a`,{href:ye,rel:`noopener noreferrer`,target:`_blank`,children:`Complete payment`})]}):null]}),X||Y?k(`button`,{"aria-busy":Y,className:`lockerverse-payment__status-check`,disabled:Y,onClick:q.commands.checkPaymentStatus,type:`button`,children:Y?`Checking payment status…`:`Check payment status`}):null]}):A(`form`,{"aria-busy":Z,className:`lockerverse-payment__form`,noValidate:!0,onSubmit:Me,children:[k(`div`,{"data-lockerverse-input-region":``,inert:Z?!0:void 0,children:A(`fieldset`,{className:`lockerverse-payment__input-fieldset`,disabled:Z,children:[k(g,{displayedBaseCents:De,displayedTipCents:Ee,displayedTotalCents:J,quote:h}),k(pe,{enabled:e.widget.fields.tipping,error:ne,errorId:Te,onChange:je,values:G}),k(mt,{email:T,emailDiscountMessage:pt(h),emailErrorId:Se,emailId:xe,emailRef:ue,errors:R,onEmailBlur:()=>q.commands.refreshAuthoritativeTotal(),onEmailChange:e=>{j(e),Ae(`email`)},onPhoneChange:({value:e,country:t})=>{N(e),F(t),Ae(`phone`)},phone:M,phoneCountry:P,phoneEnabled:e.widget.fields.phone,phoneErrorId:we,phoneId:Ce,phoneRef:de}),k(ht,{message:ke}),k(lt,{catalog:e,displayedTotalCents:J,fieldValues:G,isBillingAddressReady:W,isPaymentReady:H,isShippingAddressReady:oe,onAddressChange:(e,t)=>{le.current[e]=t},onFieldValuesChange:je,onStripeLoadError:V,setIsBillingAddressReady:ae,setIsPaymentReady:U,setIsShippingAddressReady:se}),k(me,{customFields:w,errors:te,fields:e.widget.fields,idPrefix:be,isPromoApplying:he,memberIdLabel:e.community?.memberIdLabel,onApplyPromo:q.commands.applyPromo,onChange:je,promoError:_e,values:G}),k(ut,{catalog:e,displayedTotalCents:J,fieldValues:G,isBillingAddressReady:W,isPaymentReady:H,isRequiredShippingReady:Oe,isSubmitting:Z,onFieldValuesChange:je,quote:h})]})}),Z?k(`p`,{className:`lockerverse-payment__sr-only`,ref:fe,role:`status`,tabIndex:-1,children:J===0?`Completing order…`:`Processing payment…`}):null,k(ct,{message:ge})]})}function vt(){return k(h,{fieldCount:2,label:`Loading payment…`,sectionCount:2,showCheckbox:!0})}function yt(e,t){switch(t.type){case`loading`:return{phase:`loading`,revision:e.revision};case`ready`:return St(t.displayedQuote,e.revision+1);case`error`:return{failure:t.failure,phase:`error`,revision:e.revision};case`checkout`:return e.phase===`ready`?{...e,displayedQuote:t.checkout,quoteFailure:void 0}:e;case`quote-error`:return e.phase===`ready`?{...e,quoteFailure:t.failure}:e;default:return e}}function $(e,t,n){return e?.catalog===t&&e.selectionKey===n}function bt({checkout:e}){return{displayedQuote:e,type:`ready`}}function xt(e){return e instanceof Error?e.message:`Lockerverse payment could not load.`}function St(e,t){return{checkoutItems:[...e.items],displayedQuote:e,phase:`ready`,quoteFailure:void 0,revision:t}}function Ct(e,t){let n=e.widget.fields.serviceFee;return M(e,{includeServiceFee:n,selection:t})}function wt(e,t){try{return St(Ct(e,t),1)}catch(e){return{failure:xt(e),phase:`error`,revision:0}}}function Tt({catalog:e,client:t,paymentState:n,selection:r}){let i=ke(r),a=i.success?JSON.stringify(i.value):`invalid-selection`,o=w(()=>i.success?i.value:[],[i.success,a]),[s,c]=T(yt,void 0,()=>i.success?wt(e,o):{phase:`loading`,revision:0}),l=E(void 0),u=E(0),d=E(s.phase===`ready`?{catalog:e,selectionKey:a}:void 0),f=E(s.phase===`error`?{catalog:e,selectionKey:a}:void 0),p=n===`submitting`||n===`success`||n===`unresolved`;S(()=>{if(!i.success||p||$(f.current,e,a)||$(l.current,e,a))return;let n=!0;l.current={catalog:e,selectionKey:a};let r=$(d.current,e,a);r||c({type:`loading`});function s(e){n&&c(e)}function m(){n&&(l.current=void 0,f.current={catalog:e,selectionKey:a})}let h;function g(t){if(!n||(l.current=void 0,f.current={catalog:e,selectionKey:a},r&&h!==void 0&&u.current!==h))return;let i=xt(t);if(i===`This option is sold out.`){c({failure:i,type:`error`});return}c(r?{failure:i,type:`quote-error`}:{failure:i,type:`error`})}async function _(){try{h=u.current;let n=e.widget.fields.serviceFee;if(!r){let t=Ct(e,o);r=!0,d.current={catalog:e,selectionKey:a},s(bt({checkout:t}))}let i=await t.calculateTotal({catalog:e,includeServiceFee:n,selection:o});m(),u.current===h&&s({checkout:i,type:`checkout`})}catch(e){g(e)}}return _(),()=>{n=!1,$(l.current,e,a)&&(l.current=void 0)}},[e,t,i.success,p,a,o]);let m=$(d.current,e,a)||$(f.current,e,a)||$(l.current,e,a),h=p||m?s:{phase:`loading`,revision:s.revision};return{selectionError:i.success?void 0:i.message,session:h,updateCheckout:e=>{u.current+=1,c({checkout:e,type:`checkout`})}}}const Et=V({recovery:V({connectedAccountId:re(G()),paymentReference:U(G(),ce(),ne())}),selectionFingerprint:G(),version:le([z(1),z(2)]),widgetId:H(G())});function Dt(e){let t=ke(e);return t.success?JSON.stringify(t.value.map(e=>{let t=e.productSlug.trim();return`quantity`in e?[`quantity`,t,e.quantity]:`amountCents`in e?[`amount`,t,e.amountCents]:[`product`,t]})):null}const Ot=`A previous payment uses different checkout details. Return to its original checkout to check the payment before you pay again.`;function kt(e,t,n){let r;try{r=window.sessionStorage.getItem(e)}catch{return{recovery:null}}if(!r)return{recovery:null};try{let e=oe(Et,JSON.parse(r));if(!e.success)throw Error(`Invalid recovery record`);let i=e.output;return i.selectionFingerprint!==t||i.version===2&&i.widgetId!==n?{error:Ot,recovery:null}:{recovery:{connectedAccountId:i.recovery.connectedAccountId,paymentReference:i.recovery.paymentReference}}}catch{return{error:`The saved payment could not be read. Contact support to check it before you pay again.`,recovery:null}}}function At({selection:e,storageKey:t,widgetId:n}){let r=Dt(e),i=JSON.stringify([t,r,n]),[a,o]=D(null),s=E(null);S(()=>{if(!t)return;let e=s.current,a={recovery:null};e?.recovery?a=e.identity===i?{recovery:e.recovery}:{error:Ot,recovery:null}:r!==null&&(a=kt(t,r,n)),a.recovery&&(s.current={identity:i,recovery:a.recovery}),o({identity:i,...a})},[r,i,t,n]);let c=x(e=>{if(!(!t||r===null)){s.current=e?{identity:i,recovery:e}:null;try{e?window.sessionStorage.setItem(t,JSON.stringify({recovery:e,selectionFingerprint:r,version:2,widgetId:n})):window.sessionStorage.removeItem(t)}catch{}}},[r,i,t,n]);return{error:t&&a?.identity===i?a.error:void 0,ready:!t||a?.identity===i,recovery:t&&a?.identity===i?a.recovery:null,remember:c}}const jt={annually:`/year`,"every-six-months":` every 6 months`,monthly:`/month`,"one-time":``};function Mt({branding:e,catalog:t}){return A(`header`,{children:[t.widget.showCommunityBranding&&e?A(`div`,{className:`lockerverse-payment__branding`,children:[e.imageUrl?k(`img`,{alt:e.name,height:`48`,src:e.imageUrl,width:`48`}):null,k(`strong`,{children:e.name})]}):null,k(`h1`,{children:t.widget.title??t.widget.name}),t.widget.description?k(`p`,{children:t.widget.description}):null]})}function Nt({catalog:t,selection:n}){let r=n?.length?t.products.filter(e=>n.some(t=>t.productSlug===e.slug)):t.products.filter(e=>e.id!==t.widget.requiredShipping?.productId);return r.length===0?null:A(`div`,{className:`lockerverse-payment__payment-summary`,children:[k(`h2`,{children:`Products`}),k(`div`,{className:`lockerverse-payment__payment-summary-items`,children:r.map(t=>{let n=t.pricingMode===`fixed`?t.amountCents:t.minimumAmountCents,r=jt[t.paymentOption];return A(`div`,{className:`lockerverse-payment__payment-summary-row`,children:[k(`span`,{children:t.name}),k(`strong`,{children:n===null?`Choose amount`:`${t.pricingMode===`custom`?`From `:``}${e(n)}${r}`})]},t.id)})}),k(`p`,{children:`Base prices. Final total is checked at checkout.`})]})}function Pt(e,t){let i=n(e?.[`--lockerverse-accent`]??t?.accentColor??`#38d77a`),a=r(i),o={...e};return(e?.[`--lockerverse-accent`]!==void 0||t?.accentColor)&&(o[`--lockerverse-accent`]=i),a&&e?.[`--lockerverse-accent-contrast`]===void 0&&(o[`--lockerverse-accent-contrast`]=a),{accent:i,rootStyle:o}}function Ft({catalog:e,client:n,loadError:r,onRetry:i,...a}){let{branding:o,className:s,completionView:c,recoveryStorageKey:l,initialCustomFieldValues:u,metadata:d,onPaymentComplete:f,onPaymentRecoveryChange:p,onPaymentUncertain:m,resumePayment:h,selection:g,style:_,stripeLoader:v=et,theme:y=`dark`,...b}=a,[ee,w]=D(h),T=E(null),[O,j]=D(null),M=x(e=>{j(e),t(f,e)},[f]),[N,P]=D(),[F,I]=D(`idle`),L=E(void 0),{selectionError:R,session:z,updateCheckout:te}=Tt({catalog:e,client:n,paymentState:F,selection:g}),B=z.phase===`ready`?z.revision:void 0,ne=x(e=>{B!==void 0&&(L.current=B),I(e)},[B]),re=x(e=>p?.(e),[p]),ie=x(()=>{w(void 0)},[]);S(()=>{z.phase===`loading`&&P(void 0)},[z.phase]),C(()=>{z.phase===`ready`&&L.current!==z.revision&&I(e=>e===`success`||e===`unresolved`?e:`idle`)},[z.phase,z.revision]);let V=[`lockerverse-payment`,s].filter(Boolean).join(` `),H=o??e.community,{accent:U,rootStyle:W}=Pt(_,H);return O&&c===`summary`?k(`section`,{...b,className:V,"data-lockerverse-theme":y,"data-payment-state":`success`,style:W,children:A(`div`,{className:`lockerverse-payment__completion`,role:`status`,children:[k(`span`,{"aria-hidden":`true`,className:`lockerverse-payment__completion-icon`,children:k(`svg`,{"aria-hidden":`true`,fill:`none`,height:`28`,stroke:`currentColor`,strokeWidth:`2`,viewBox:`0 0 24 24`,width:`28`,children:k(`path`,{d:`m5 12 4 4L19 6`})})}),k(`h1`,{children:O.paymentRequired?`Thank you`:`Order confirmed`}),k(`p`,{children:O.paymentRequired?`Your payment has been received.`:`Your order is confirmed. No payment was required.`})]})}):R?k(`section`,{...b,className:V,"data-lockerverse-theme":y,role:`alert`,style:W,children:R}):z.phase===`error`&&z.failure===`This option is sold out.`||F===`sold_out`?A(`section`,{...b,className:V,"data-lockerverse-theme":y,role:`alert`,style:W,children:[k(`h1`,{children:`Sold out`}),k(`p`,{children:`This option is sold out.`})]}):z.phase===`error`?k(`section`,{...b,className:V,"data-lockerverse-theme":y,style:W,children:k(`p`,{role:`alert`,children:z.failure})}):z.phase===`ready`?A(`section`,{...b,"aria-label":`Payment`,className:V,"data-lockerverse-theme":y,"data-payment-state":F,ref:T,style:W,children:[k(Mt,{branding:H,catalog:e}),r?A(`div`,{role:`alert`,children:[k(`p`,{children:r.message}),k(`button`,{onClick:i,type:`button`,children:`Retry`})]}):null,N?k(`p`,{className:`lockerverse-payment__payment-status`,role:`status`,children:N}):null,z.quoteFailure?A(`div`,{className:`lockerverse-payment__payment-status`,role:`alert`,children:[k(`span`,{children:z.quoteFailure}),k(`span`,{children:` The final total will be checked when you submit.`})]}):null,k(it,{accentColor:U,appearanceRoot:T,catalog:e,checkoutItems:z.checkoutItems,client:n,initialCustomFieldValues:u,metadata:d,onPaymentComplete:M,onPaymentRecoveryChange:re,onPaymentUncertain:m,onQuoteChange:(e,t)=>{P(t),te(e)},onResumePaymentFailed:ie,onStateChange:ne,quote:z.displayedQuote,resumePayment:ee,stripeLoader:v,theme:y,visualStyle:W},z.revision)]}):A(`section`,{...b,"aria-busy":`true`,"aria-label":`Payment`,className:V,"data-lockerverse-theme":y,style:W,children:[k(Mt,{branding:H,catalog:e}),r?A(`div`,{role:`alert`,children:[k(`p`,{children:r.message}),k(`button`,{onClick:i,type:`button`,children:`Retry`})]}):null,k(vt,{})]})}function It({children:e,loading:t=!1,viewProps:i}){let{branding:a,className:o,completionView:s,recoveryStorageKey:c,initialCustomFieldValues:l,metadata:u,onPaymentComplete:d,onPaymentRecoveryChange:f,onPaymentUncertain:p,resumePayment:m,selection:h,stripeLoader:g,style:_,theme:v=`dark`,...y}=i,b=n(_?.[`--lockerverse-accent`]??a?.accentColor??`#38d77a`),x=r(b),S={..._};return(_?.[`--lockerverse-accent`]!==void 0||a?.accentColor)&&(S[`--lockerverse-accent`]=b),x&&_?.[`--lockerverse-accent-contrast`]===void 0&&(S[`--lockerverse-accent-contrast`]=x),k(`section`,{...y,...t?{"aria-busy":!0,"aria-label":`Payment`}:{},className:[`lockerverse-payment`,o].filter(Boolean).join(` `),"data-lockerverse-theme":v,style:S,children:e})}function Lt(e){let{catalog:n,client:r,loadError:i,onRetry:a,...o}=e,{onPaymentRecoveryChange:s,recoveryStorageKey:c,resumePayment:l,selection:u}=o,d=At({selection:u,storageKey:c,widgetId:n.widget.id}),f=x(e=>{d.remember(e),t(s,e)},[s,d.remember]);return!d.ready||d.error?k(It,{loading:!d.ready,viewProps:o,children:d.error?k(`p`,{role:`alert`,children:d.error}):k(vt,{})}):k(Ft,{...e,onPaymentRecoveryChange:f,resumePayment:l??d.recovery})}function Rt({widget:e,...t}){return e.error&&!e.catalog?A(It,{viewProps:t,children:[k(`p`,{role:`alert`,children:e.error.message}),k(`button`,{onClick:e.refresh,type:`button`,children:`Retry`})]}):e.loading?A(It,{loading:!0,viewProps:t,children:[e.catalog?A(O,{children:[k(Mt,{branding:t.branding??e.catalog.community,catalog:e.catalog}),k(Nt,{catalog:e.catalog,selection:t.selection})]}):null,k(vt,{})]}):e.catalog?k(Lt,{catalog:e.catalog,client:e.client,loadError:e.error,onRetry:e.refresh,...t}):k(It,{loading:!0,viewProps:t,children:k(vt,{})})}export{tt as n,Rt as t};
|
|
2
2
|
//# sourceMappingURL=lockerverse-payment.js.map
|