@lockerverse/react 0.2.88 → 0.2.90
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/dist/host-callback.js +1 -1
- package/dist/host-callback.js.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.d.ts +2 -1
- package/dist/signup.d.ts.map +1 -1
- package/dist/signup.js +1 -1
- package/dist/signup.js.map +1 -1
- package/dist/types.d.ts +2 -2
- package/dist/use-lockerverse-widget.js.map +1 -1
- package/package.json +2 -2
package/dist/host-callback.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{array as e,email as t,minLength as n,nonEmpty as r,pipe as i,regex as a,safeParse as o,string as s,transform as c,trim as l}from"valibot";import{jsx as u,jsxs as d}from"react/jsx-runtime";const f=/^#([\da-f]{3}|[\da-f]{6})$/i,p=/^([\da-f]{3}|[\da-f]{6})$/i;function m(e){let t=e.trim();return p.test(t)?`#${t}`:t}function h(e){let t=f.exec(m(e));if(!t)return;let[,n]=t;if(!n)return;let r=n.length===3?Array.from(n,e=>`${e}${e}`).join(``):n;return[0,2,4].map(e=>Number.parseInt(r.slice(e,e+2),16))}function g([e,t,n]){let[r=0,i=0,a=0]=[e,t,n].map((e=0)=>{let t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4});return .2126*r+.7152*i+.0722*a}function _(e){let t=h(e);if(!t)return;let n=g(t);return(n+.05)/.05>=1.05/(n+.05)?`#000`:`#fff`}function v(e){return e.type===`checkbox`?!1:e.type===`checkboxes`||e.type===`multi_select`?[]:``}function y(e){
|
|
1
|
+
import{array as e,email as t,minLength as n,nonEmpty as r,pipe as i,regex as a,safeParse as o,string as s,transform as c,trim as l}from"valibot";import{jsx as u,jsxs as d}from"react/jsx-runtime";const f=/^#([\da-f]{3}|[\da-f]{6})$/i,p=/^([\da-f]{3}|[\da-f]{6})$/i;function m(e){let t=e.trim();return p.test(t)?`#${t}`:t}function h(e){let t=f.exec(m(e));if(!t)return;let[,n]=t;if(!n)return;let r=n.length===3?Array.from(n,e=>`${e}${e}`).join(``):n;return[0,2,4].map(e=>Number.parseInt(r.slice(e,e+2),16))}function g([e,t,n]){let[r=0,i=0,a=0]=[e,t,n].map((e=0)=>{let t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4});return .2126*r+.7152*i+.0722*a}function _(e){let t=h(e);if(!t)return;let n=g(t);return(n+.05)/.05>=1.05/(n+.05)?`#000`:`#fff`}function v(e){return e.type===`checkbox`?!1:e.type===`checkboxes`||e.type===`multi_select`?[]:``}function y(e){let t={};for(let n of e)t[n.id]=v(n);return t}function b(e){let t=o(s(),e);return t.success?t.output:``}function x(e,t){return e.map(e=>{let n=t[e.id];return e.type===`checkbox`?{fieldId:e.id,value:n===!0}:e.type===`checkboxes`||e.type===`multi_select`?{fieldId:e.id,value:Array.isArray(n)?n:[]}:{fieldId:e.id,value:b(n)}})}function S(t,a){let c={};for(let u of t){if(!u.required)continue;let t=`${u.label} is required.`,d=a[u.id];if(u.type===`checkbox`){d!==!0&&(c[u.id]=t);continue}let f=u.type===`checkboxes`||u.type===`multi_select`?o(i(e(s()),n(1,t)),d??[]):o(i(s(),l(),r(t)),b(d));f.success||(c[u.id]=f.issues[0]?.message??t)}return c}function C({choiceClassName:e,errorClassName:t,errors:n,fields:r,idPrefix:i,onChange:a,values:o}){return r.map(r=>u(w,{choiceClassName:e,error:n[r.id],errorClassName:t,field:r,idPrefix:i,onChange:e=>a({...o,[r.id]:e}),value:o[r.id]},r.id))}function w(e){let{field:t,idPrefix:n}=e,r=`${n}-custom-${t.id}`,i=`${r}-error`,a={...e,controlId:r,errorId:i};switch(t.type){case`checkbox`:return u(T,{...a,field:t});case`text`:case`textarea`:return u(D,{...a,field:t});case`select`:case`multi_select`:return u(O,{...a,field:t});case`radio`:case`checkboxes`:return u(k,{...a,field:t});default:return null}}function T({choiceClassName:e,controlId:t,error:n,errorClassName:r,errorId:i,field:a,onChange:o,value:s}){return d(`label`,{className:e,htmlFor:t,children:[u(`input`,{"aria-describedby":n?i:void 0,"aria-invalid":n?`true`:void 0,checked:s===!0,id:t,name:`custom:${a.id}`,onChange:e=>o(e.currentTarget.checked),required:a.required,type:`checkbox`}),u(`span`,{children:a.label}),u(E,{className:r,error:n,id:i})]})}function E({className:e,error:t,id:n}){return t?u(`span`,{className:e,id:n,role:`alert`,children:t}):null}function D({controlId:e,error:t,errorClassName:n,errorId:r,field:i,onChange:a,value:o}){let s={"aria-describedby":t?r:void 0,"aria-invalid":t?`true`:void 0,id:e,name:`custom:${i.id}`,onChange:e=>a(e.currentTarget.value),required:i.required,value:b(o)};return d(`label`,{htmlFor:e,children:[u(`span`,{children:i.label}),i.type===`textarea`?u(`textarea`,{...s}):u(`input`,{...s}),u(E,{className:n,error:t,id:r})]})}function O({controlId:e,error:t,errorClassName:n,errorId:r,field:i,onChange:a,value:o}){return d(`label`,{htmlFor:e,children:[u(`span`,{children:i.label}),d(`select`,{"aria-describedby":t?r:void 0,"aria-invalid":t?`true`:void 0,id:e,multiple:i.type===`multi_select`,name:`custom:${i.id}`,onChange:e=>a(i.type===`multi_select`?[...e.currentTarget.selectedOptions].map(e=>e.value):e.currentTarget.value),required:i.required,value:o===!0||o===!1?``:o??(i.type===`multi_select`?[]:``),children:[i.type===`select`?u(`option`,{value:``,children:`Select…`}):null,i.options.map(e=>u(`option`,{value:e.id,children:e.label},e.id))]}),u(E,{className:n,error:t,id:r})]})}function k({choiceClassName:e,controlId:t,error:n,errorClassName:r,errorId:i,field:a,onChange:o,value:s}){let c=Array.isArray(s)?s:[];return d(`fieldset`,{"aria-describedby":n?i:void 0,"aria-invalid":n?`true`:void 0,children:[u(`legend`,{children:a.label}),a.options.map((n,r)=>d(`label`,{className:e,children:[u(`input`,{checked:Array.isArray(s)?s.includes(n.id):s===n.id,id:`${t}-${r}`,name:`custom:${a.id}`,onChange:e=>{if(a.type===`radio`){o(n.id);return}o(e.currentTarget.checked?[...c,n.id]:c.filter(e=>e!==n.id))},required:a.required&&a.type===`radio`,type:a.type===`radio`?`radio`:`checkbox`,value:n.id}),u(`span`,{children:n.label})]},n.id)),u(E,{className:r,error:n,id:i})]})}function A({fieldCount:e,label:t,sectionCount:n=0,showCheckbox:r=!1}){return d(`div`,{className:`lockerverse-form-skeleton__loading`,children:[u(`span`,{className:`lockerverse-form-skeleton__sr-only`,role:`status`,children:t}),d(`div`,{"aria-hidden":`true`,className:`lockerverse-form-skeleton`,children:[d(`div`,{className:`lockerverse-form-skeleton__branding`,children:[u(`span`,{className:`lockerverse-form-skeleton__avatar`}),u(`span`,{className:`lockerverse-form-skeleton__community`})]}),u(`div`,{className:`lockerverse-form-skeleton__fields`,children:Array.from({length:e},(e,t)=>d(`div`,{className:`lockerverse-form-skeleton__field`,children:[u(`span`,{className:`lockerverse-form-skeleton__label`}),u(`span`,{className:`lockerverse-form-skeleton__input`})]},t))}),Array.from({length:n},(e,t)=>d(`div`,{className:`lockerverse-form-skeleton__section`,children:[u(`span`,{className:`lockerverse-form-skeleton__section-label`}),d(`div`,{className:`lockerverse-form-skeleton__section-content`,children:[u(`span`,{className:`lockerverse-form-skeleton__section-full`}),d(`div`,{className:`lockerverse-form-skeleton__section-grid`,children:[u(`span`,{className:`lockerverse-form-skeleton__section-half`}),u(`span`,{className:`lockerverse-form-skeleton__section-half`})]})]})]},t)),d(`div`,{className:`lockerverse-form-skeleton__actions`,children:[r?u(`span`,{className:`lockerverse-form-skeleton__check-line`}):null,u(`span`,{className:`lockerverse-form-skeleton__button`})]})]})]})}const j=`Enter a valid email address.`,M=`Enter a valid phone number.`,N=/^(?:$|[^\s@]+@[^\s@]+\.[^\s@]+)$/,P=/^\+[1-9]\d{6,14}$/,F=/^(?:$|\+[1-9]\d{6,14})$/;function I(e){return e.trim().replace(/[().\s-]/g,``)}const L=i(s(),l(),a(N,j)),R=i(s(),l(),r(`Email is required.`),t(j)),z=i(s(),l(),c(I),a(F,M)),B=i(s(),l(),r(`Phone is required.`),c(I),a(P,M));function V(e,t){if(e)try{Promise.resolve(e(t)).catch(()=>void 0)}catch{}}export{R as a,C as c,S as d,_ as f,z as i,x as l,I as n,B as o,m as p,L as r,A as s,V as t,y as u};
|
|
2
2
|
//# sourceMappingURL=host-callback.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"host-callback.js","names":[],"sources":["../src/accent-contrast.ts","../src/custom-fields.tsx","../src/form-skeleton.tsx","../src/contact-validation.ts","../src/host-callback.ts"],"sourcesContent":["const HEX_COLOR = /^#([\\da-f]{3}|[\\da-f]{6})$/i;\nconst UNPREFIXED_HEX_COLOR = /^([\\da-f]{3}|[\\da-f]{6})$/i;\n\nexport function normalizeAccentColor(color: string) {\n const trimmedColor = color.trim();\n return UNPREFIXED_HEX_COLOR.test(trimmedColor)\n ? `#${trimmedColor}`\n : trimmedColor;\n}\n\nfunction parseHexColor(color: string) {\n const match = HEX_COLOR.exec(normalizeAccentColor(color));\n if (!match) {\n return;\n }\n const [, value] = match;\n if (!value) {\n return;\n }\n const expanded =\n value.length === 3\n ? Array.from(value, (character) => `${character}${character}`).join(\"\")\n : value;\n return [0, 2, 4].map((offset) =>\n Number.parseInt(expanded.slice(offset, offset + 2), 16)\n );\n}\n\nfunction relativeLuminance([red, green, blue]: number[]) {\n const [linearRed = 0, linearGreen = 0, linearBlue = 0] = [\n red,\n green,\n blue,\n ].map((channel = 0) => {\n const normalized = channel / 255;\n return normalized <= 0.040_45\n ? normalized / 12.92\n : ((normalized + 0.055) / 1.055) ** 2.4;\n });\n return 0.2126 * linearRed + 0.7152 * linearGreen + 0.0722 * linearBlue;\n}\n\nexport function getAccentContrast(color: string) {\n const parsed = parseHexColor(color);\n if (!parsed) {\n return;\n }\n const luminance = relativeLuminance(parsed);\n const blackContrast = (luminance + 0.05) / 0.05;\n const whiteContrast = 1.05 / (luminance + 0.05);\n return blackContrast >= whiteContrast ? \"#000\" : \"#fff\";\n}\n","import type {\n LockerverseBooleanCustomField,\n LockerverseCustomField,\n LockerverseCustomFieldAnswer,\n LockerverseMultiOptionCustomField,\n LockerverseSingleOptionCustomField,\n} from \"@lockerverse/sdk/checkout\";\nimport {\n array,\n minLength,\n nonEmpty,\n pipe,\n safeParse,\n string,\n trim,\n} from \"valibot\";\n\nexport type CustomFieldValues = Record<string, boolean | string | string[]>;\n\nfunction createCustomFieldValue(field: LockerverseCustomField) {\n if (field.type === \"checkbox\") {\n return false;\n }\n if (field.type === \"checkboxes\" || field.type === \"multi_select\") {\n return [];\n }\n return \"\";\n}\n\nexport function createCustomFieldValues(fields: LockerverseCustomField[]) {\n return Object.fromEntries(\n fields.map((field) => [field.id, createCustomFieldValue(field)])\n ) as CustomFieldValues;\n}\n\nexport function buildCustomFieldAnswers(\n fields: LockerverseCustomField[],\n values: CustomFieldValues\n): LockerverseCustomFieldAnswer[] {\n return fields.map((field): LockerverseCustomFieldAnswer => {\n const value = values[field.id];\n if (field.type === \"checkbox\") {\n return { fieldId: field.id, value: value === true };\n }\n if (field.type === \"checkboxes\" || field.type === \"multi_select\") {\n return { fieldId: field.id, value: Array.isArray(value) ? value : [] };\n }\n return {\n fieldId: field.id,\n value: typeof value === \"string\" ? value : \"\",\n };\n });\n}\n\nexport function validateCustomFields(\n fields: LockerverseCustomField[],\n values: CustomFieldValues\n) {\n const errors: Record<string, string> = {};\n for (const field of fields) {\n if (!field.required) {\n continue;\n }\n const message = `${field.label} is required.`;\n const value = values[field.id];\n if (field.type === \"checkbox\") {\n if (value !== true) {\n errors[field.id] = message;\n }\n continue;\n }\n const result =\n field.type === \"checkboxes\" || field.type === \"multi_select\"\n ? safeParse(pipe(array(string()), minLength(1, message)), value ?? [])\n : safeParse(\n pipe(string(), trim(), nonEmpty(message)),\n typeof value === \"string\" ? value : \"\"\n );\n if (!result.success) {\n errors[field.id] = result.issues[0]?.message ?? message;\n }\n }\n return errors;\n}\n\nexport function CustomFields({\n choiceClassName,\n errorClassName,\n errors,\n fields,\n idPrefix,\n onChange,\n values,\n}: {\n choiceClassName: string;\n errorClassName: string;\n errors: Record<string, string>;\n fields: LockerverseCustomField[];\n idPrefix: string;\n onChange: (values: CustomFieldValues) => void;\n values: CustomFieldValues;\n}) {\n return fields.map((field) => (\n <CustomField\n choiceClassName={choiceClassName}\n error={errors[field.id]}\n errorClassName={errorClassName}\n field={field}\n idPrefix={idPrefix}\n key={field.id}\n onChange={(value) => onChange({ ...values, [field.id]: value })}\n value={values[field.id]}\n />\n ));\n}\n\ntype CustomFieldProps = {\n choiceClassName: string;\n error: string | undefined;\n errorClassName: string;\n field: LockerverseCustomField;\n idPrefix: string;\n onChange: (value: boolean | string | string[]) => void;\n value: boolean | string | string[] | undefined;\n};\n\nfunction CustomField(props: CustomFieldProps) {\n const { field, idPrefix } = props;\n const controlId = `${idPrefix}-custom-${field.id}`;\n const errorId = `${controlId}-error`;\n const controlProps = { ...props, controlId, errorId };\n switch (field.type) {\n case \"checkbox\":\n return <BooleanCustomField {...controlProps} field={field} />;\n case \"text\":\n case \"textarea\":\n return <TextCustomField {...controlProps} field={field} />;\n case \"select\":\n case \"multi_select\":\n return <SelectCustomField {...controlProps} field={field} />;\n case \"radio\":\n case \"checkboxes\":\n return <ChoiceCustomField {...controlProps} field={field} />;\n default:\n return null;\n }\n}\n\nfunction BooleanCustomField({\n choiceClassName,\n controlId,\n error,\n errorClassName,\n errorId,\n field,\n onChange,\n value,\n}: ControlProps & { field: LockerverseBooleanCustomField }) {\n return (\n <label className={choiceClassName} htmlFor={controlId}>\n <input\n aria-describedby={error ? errorId : undefined}\n aria-invalid={error ? \"true\" : undefined}\n checked={value === true}\n id={controlId}\n name={`custom:${field.id}`}\n onChange={(event) => onChange(event.currentTarget.checked)}\n required={field.required}\n type=\"checkbox\"\n />\n <span>{field.label}</span>\n <FieldError className={errorClassName} error={error} id={errorId} />\n </label>\n );\n}\n\ntype ControlProps = CustomFieldProps & {\n controlId: string;\n errorId: string;\n};\n\nfunction FieldError({\n className,\n error,\n id,\n}: {\n className: string;\n error: string | undefined;\n id: string;\n}) {\n return error ? (\n <span className={className} id={id} role=\"alert\">\n {error}\n </span>\n ) : null;\n}\n\nfunction TextCustomField({\n controlId,\n error,\n errorClassName,\n errorId,\n field,\n onChange,\n value,\n}: ControlProps & {\n field: Extract<LockerverseCustomField, { type: \"text\" | \"textarea\" }>;\n}) {\n const commonProps = {\n \"aria-describedby\": error ? errorId : undefined,\n \"aria-invalid\": error ? (\"true\" as const) : undefined,\n id: controlId,\n name: `custom:${field.id}`,\n onChange: (\n event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>\n ) => onChange(event.currentTarget.value),\n required: field.required,\n value: typeof value === \"string\" ? value : \"\",\n };\n return (\n <label htmlFor={controlId}>\n <span>{field.label}</span>\n {field.type === \"textarea\" ? (\n <textarea {...commonProps} />\n ) : (\n <input {...commonProps} />\n )}\n <FieldError className={errorClassName} error={error} id={errorId} />\n </label>\n );\n}\n\nfunction SelectCustomField({\n controlId,\n error,\n errorClassName,\n errorId,\n field,\n onChange,\n value,\n}: ControlProps & {\n field: LockerverseMultiOptionCustomField | LockerverseSingleOptionCustomField;\n}) {\n return (\n <label htmlFor={controlId}>\n <span>{field.label}</span>\n <select\n aria-describedby={error ? errorId : undefined}\n aria-invalid={error ? \"true\" : undefined}\n id={controlId}\n multiple={field.type === \"multi_select\"}\n name={`custom:${field.id}`}\n onChange={(event) =>\n onChange(\n field.type === \"multi_select\"\n ? [...event.currentTarget.selectedOptions].map(\n (option) => option.value\n )\n : event.currentTarget.value\n )\n }\n required={field.required}\n value={\n typeof value === \"boolean\"\n ? \"\"\n : (value ?? (field.type === \"multi_select\" ? [] : \"\"))\n }\n >\n {field.type === \"select\" ? <option value=\"\">Select…</option> : null}\n {field.options.map((option) => (\n <option key={option.id} value={option.id}>\n {option.label}\n </option>\n ))}\n </select>\n <FieldError className={errorClassName} error={error} id={errorId} />\n </label>\n );\n}\n\nfunction ChoiceCustomField({\n choiceClassName,\n controlId,\n error,\n errorClassName,\n errorId,\n field,\n onChange,\n value,\n}: ControlProps & {\n field: LockerverseMultiOptionCustomField | LockerverseSingleOptionCustomField;\n}) {\n const selectedValues = Array.isArray(value) ? value : [];\n return (\n <fieldset\n aria-describedby={error ? errorId : undefined}\n aria-invalid={error ? \"true\" : undefined}\n >\n <legend>{field.label}</legend>\n {field.options.map((option, index) => (\n <label className={choiceClassName} key={option.id}>\n <input\n checked={\n Array.isArray(value)\n ? value.includes(option.id)\n : value === option.id\n }\n id={`${controlId}-${index}`}\n name={`custom:${field.id}`}\n onChange={(event) => {\n if (field.type === \"radio\") {\n onChange(option.id);\n return;\n }\n onChange(\n event.currentTarget.checked\n ? [...selectedValues, option.id]\n : selectedValues.filter((id) => id !== option.id)\n );\n }}\n required={field.required && field.type === \"radio\"}\n type={field.type === \"radio\" ? \"radio\" : \"checkbox\"}\n value={option.id}\n />\n <span>{option.label}</span>\n </label>\n ))}\n <FieldError className={errorClassName} error={error} id={errorId} />\n </fieldset>\n );\n}\n","export function FormSkeleton({\n fieldCount,\n label,\n sectionCount = 0,\n showCheckbox = false,\n}: {\n fieldCount: number;\n label: string;\n sectionCount?: number;\n showCheckbox?: boolean;\n}) {\n return (\n <div className=\"lockerverse-form-skeleton__loading\">\n <span className=\"lockerverse-form-skeleton__sr-only\" role=\"status\">\n {label}\n </span>\n <div aria-hidden=\"true\" className=\"lockerverse-form-skeleton\">\n <div className=\"lockerverse-form-skeleton__branding\">\n <span className=\"lockerverse-form-skeleton__avatar\" />\n <span className=\"lockerverse-form-skeleton__community\" />\n </div>\n <div className=\"lockerverse-form-skeleton__fields\">\n {Array.from({ length: fieldCount }, (_, index) => (\n <div className=\"lockerverse-form-skeleton__field\" key={index}>\n <span className=\"lockerverse-form-skeleton__label\" />\n <span className=\"lockerverse-form-skeleton__input\" />\n </div>\n ))}\n </div>\n {Array.from({ length: sectionCount }, (_, index) => (\n <div className=\"lockerverse-form-skeleton__section\" key={index}>\n <span className=\"lockerverse-form-skeleton__section-label\" />\n <div className=\"lockerverse-form-skeleton__section-content\">\n <span className=\"lockerverse-form-skeleton__section-full\" />\n <div className=\"lockerverse-form-skeleton__section-grid\">\n <span className=\"lockerverse-form-skeleton__section-half\" />\n <span className=\"lockerverse-form-skeleton__section-half\" />\n </div>\n </div>\n </div>\n ))}\n <div className=\"lockerverse-form-skeleton__actions\">\n {showCheckbox ? (\n <span className=\"lockerverse-form-skeleton__check-line\" />\n ) : null}\n <span className=\"lockerverse-form-skeleton__button\" />\n </div>\n </div>\n </div>\n );\n}\n","import { email, nonEmpty, pipe, regex, string, transform, trim } from \"valibot\";\n\nexport const EMAIL_REQUIRED_MESSAGE = \"Email is required.\";\nexport const EMAIL_INVALID_MESSAGE = \"Enter a valid email address.\";\nexport const PHONE_REQUIRED_MESSAGE = \"Phone is required.\";\nexport const PHONE_INVALID_MESSAGE = \"Enter a valid phone number.\";\n\nconst OPTIONAL_EMAIL_PATTERN = /^(?:$|[^\\s@]+@[^\\s@]+\\.[^\\s@]+)$/;\nconst INTERNATIONAL_PHONE_PATTERN = /^\\+[1-9]\\d{6,14}$/;\nconst OPTIONAL_INTERNATIONAL_PHONE_PATTERN = /^(?:$|\\+[1-9]\\d{6,14})$/;\n\nexport function normalizePhone(input: string) {\n return input.trim().replace(/[().\\s-]/g, \"\");\n}\n\nexport const optionalEmailSchema = pipe(\n string(),\n trim(),\n regex(OPTIONAL_EMAIL_PATTERN, EMAIL_INVALID_MESSAGE)\n);\n\nexport const requiredEmailSchema = pipe(\n string(),\n trim(),\n nonEmpty(EMAIL_REQUIRED_MESSAGE),\n email(EMAIL_INVALID_MESSAGE)\n);\n\nexport const optionalPhoneSchema = pipe(\n string(),\n trim(),\n transform(normalizePhone),\n regex(OPTIONAL_INTERNATIONAL_PHONE_PATTERN, PHONE_INVALID_MESSAGE)\n);\n\nexport const requiredPhoneSchema = pipe(\n string(),\n trim(),\n nonEmpty(PHONE_REQUIRED_MESSAGE),\n transform(normalizePhone),\n regex(INTERNATIONAL_PHONE_PATTERN, PHONE_INVALID_MESSAGE)\n);\n","export function notifyHostCallback<Value>(\n callback: ((value: Value) => unknown) | undefined,\n value: Value\n) {\n if (!callback) {\n return;\n }\n try {\n Promise.resolve(callback(value)).catch(() => undefined);\n } catch {\n // Host callback failures must not change completed SDK state.\n }\n}\n"],"mappings":"mMAAA,MAAM,EAAY,8BACZ,EAAuB,6BAE7B,SAAgB,EAAqB,EAAe,CAClD,IAAM,EAAe,EAAM,KAAK,EAChC,OAAO,EAAqB,KAAK,CAAY,EACzC,IAAI,IACJ,CACN,CAEA,SAAS,EAAc,EAAe,CACpC,IAAM,EAAQ,EAAU,KAAK,EAAqB,CAAK,CAAC,EACxD,GAAI,CAAC,EACH,OAEF,GAAM,EAAG,GAAS,EAClB,GAAI,CAAC,EACH,OAEF,IAAM,EACJ,EAAM,SAAW,EACb,MAAM,KAAK,EAAQ,GAAc,GAAG,IAAY,GAAW,CAAC,CAAC,KAAK,EAAE,EACpE,EACN,MAAO,CAAC,EAAG,EAAG,CAAC,CAAC,CAAC,IAAK,GACpB,OAAO,SAAS,EAAS,MAAM,EAAQ,EAAS,CAAC,EAAG,EAAE,CACxD,CACF,CAEA,SAAS,EAAkB,CAAC,EAAK,EAAO,GAAiB,CACvD,GAAM,CAAC,EAAY,EAAG,EAAc,EAAG,EAAa,GAAK,CACvD,EACA,EACA,CACF,CAAC,CAAC,KAAK,EAAU,IAAM,CACrB,IAAM,EAAa,EAAU,IAC7B,OAAO,GAAc,OACjB,EAAa,QACX,EAAa,MAAS,QAAU,GACxC,CAAC,EACD,MAAO,OAAS,EAAY,MAAS,EAAc,MAAS,CAC9D,CAEA,SAAgB,EAAkB,EAAe,CAC/C,IAAM,EAAS,EAAc,CAAK,EAClC,GAAI,CAAC,EACH,OAEF,IAAM,EAAY,EAAkB,CAAM,EAG1C,OAFuB,E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,MACa,EAAwB,+BAExB,EAAwB,8BAE/B,EAAyB,mCACzB,EAA8B,oBAC9B,EAAuC,0BAE7C,SAAgB,EAAe,EAAe,CAC5C,OAAO,EAAM,KAAK,CAAC,CAAC,QAAQ,YAAa,EAAE,CAC7C,CAEA,MAAa,EAAsB,EACjC,EAAO,EACP,EAAK,EACL,EAAM,EAAwB,CAAqB,CACrD,EAEa,EAAsB,EACjC,EAAO,EACP,EAAK,EACL,EAAS,oBAAsB,EAC/B,EAAM,CAAqB,CAC7B,EAEa,EAAsB,EACjC,EAAO,EACP,EAAK,EACL,EAAU,CAAc,EACxB,EAAM,EAAsC,CAAqB,CACnE,EAEa,EAAsB,EACjC,EAAO,EACP,EAAK,EACL,EAAS,oBAAsB,EAC/B,EAAU,CAAc,EACxB,EAAM,EAA6B,CAAqB,CAC1D,ECzCA,SAAgB,EACd,EACA,EACA,CACK,KAGL,GAAI,CACF,QAAQ,QAAQ,EAAS,CAAK,CAAC,CAAC,CAAC,UAAY,IAAA,EAAS,CACxD,MAAQ,CAER,CACF"}
|
|
1
|
+
{"version":3,"file":"host-callback.js","names":[],"sources":["../src/accent-contrast.ts","../src/custom-fields.tsx","../src/form-skeleton.tsx","../src/contact-validation.ts","../src/host-callback.ts"],"sourcesContent":["const HEX_COLOR = /^#([\\da-f]{3}|[\\da-f]{6})$/i;\nconst UNPREFIXED_HEX_COLOR = /^([\\da-f]{3}|[\\da-f]{6})$/i;\n\nexport function normalizeAccentColor(color: string) {\n const trimmedColor = color.trim();\n return UNPREFIXED_HEX_COLOR.test(trimmedColor)\n ? `#${trimmedColor}`\n : trimmedColor;\n}\n\nfunction parseHexColor(color: string) {\n const match = HEX_COLOR.exec(normalizeAccentColor(color));\n if (!match) {\n return;\n }\n const [, value] = match;\n if (!value) {\n return;\n }\n const expanded =\n value.length === 3\n ? Array.from(value, (character) => `${character}${character}`).join(\"\")\n : value;\n return [0, 2, 4].map((offset) =>\n Number.parseInt(expanded.slice(offset, offset + 2), 16)\n );\n}\n\nfunction relativeLuminance([red, green, blue]: number[]) {\n const [linearRed = 0, linearGreen = 0, linearBlue = 0] = [\n red,\n green,\n blue,\n ].map((channel = 0) => {\n const normalized = channel / 255;\n return normalized <= 0.040_45\n ? normalized / 12.92\n : ((normalized + 0.055) / 1.055) ** 2.4;\n });\n return 0.2126 * linearRed + 0.7152 * linearGreen + 0.0722 * linearBlue;\n}\n\nexport function getAccentContrast(color: string) {\n const parsed = parseHexColor(color);\n if (!parsed) {\n return;\n }\n const luminance = relativeLuminance(parsed);\n const blackContrast = (luminance + 0.05) / 0.05;\n const whiteContrast = 1.05 / (luminance + 0.05);\n return blackContrast >= whiteContrast ? \"#000\" : \"#fff\";\n}\n","import type {\n LockerverseBooleanCustomField,\n LockerverseCustomField,\n LockerverseCustomFieldAnswer,\n LockerverseMultiOptionCustomField,\n LockerverseSingleOptionCustomField,\n} from \"@lockerverse/sdk/checkout\";\nimport {\n array,\n minLength,\n nonEmpty,\n pipe,\n safeParse,\n string,\n trim,\n} from \"valibot\";\n\nexport type CustomFieldValues = Record<string, boolean | string | string[]>;\n\nfunction createCustomFieldValue(field: LockerverseCustomField) {\n if (field.type === \"checkbox\") {\n return false;\n }\n if (field.type === \"checkboxes\" || field.type === \"multi_select\") {\n return [];\n }\n return \"\";\n}\n\nexport function createCustomFieldValues(fields: LockerverseCustomField[]) {\n const values: CustomFieldValues = {};\n for (const field of fields) {\n values[field.id] = createCustomFieldValue(field);\n }\n return values;\n}\n\nfunction getStringValue(value: CustomFieldValues[string] | undefined) {\n const result = safeParse(string(), value);\n return result.success ? result.output : \"\";\n}\n\nexport function buildCustomFieldAnswers(\n fields: LockerverseCustomField[],\n values: CustomFieldValues\n): LockerverseCustomFieldAnswer[] {\n return fields.map((field): LockerverseCustomFieldAnswer => {\n const value = values[field.id];\n if (field.type === \"checkbox\") {\n return { fieldId: field.id, value: value === true };\n }\n if (field.type === \"checkboxes\" || field.type === \"multi_select\") {\n return { fieldId: field.id, value: Array.isArray(value) ? value : [] };\n }\n return {\n fieldId: field.id,\n value: getStringValue(value),\n };\n });\n}\n\nexport function validateCustomFields(\n fields: LockerverseCustomField[],\n values: CustomFieldValues\n) {\n const errors: Record<string, string> = {};\n for (const field of fields) {\n if (!field.required) {\n continue;\n }\n const message = `${field.label} is required.`;\n const value = values[field.id];\n if (field.type === \"checkbox\") {\n if (value !== true) {\n errors[field.id] = message;\n }\n continue;\n }\n const result =\n field.type === \"checkboxes\" || field.type === \"multi_select\"\n ? safeParse(pipe(array(string()), minLength(1, message)), value ?? [])\n : safeParse(\n pipe(string(), trim(), nonEmpty(message)),\n getStringValue(value)\n );\n if (!result.success) {\n errors[field.id] = result.issues[0]?.message ?? message;\n }\n }\n return errors;\n}\n\nexport function CustomFields({\n choiceClassName,\n errorClassName,\n errors,\n fields,\n idPrefix,\n onChange,\n values,\n}: {\n choiceClassName: string;\n errorClassName: string;\n errors: Record<string, string>;\n fields: LockerverseCustomField[];\n idPrefix: string;\n onChange: (values: CustomFieldValues) => void;\n values: CustomFieldValues;\n}) {\n return fields.map((field) => (\n <CustomField\n choiceClassName={choiceClassName}\n error={errors[field.id]}\n errorClassName={errorClassName}\n field={field}\n idPrefix={idPrefix}\n key={field.id}\n onChange={(value) => onChange({ ...values, [field.id]: value })}\n value={values[field.id]}\n />\n ));\n}\n\ntype CustomFieldProps = {\n choiceClassName: string;\n error: string | undefined;\n errorClassName: string;\n field: LockerverseCustomField;\n idPrefix: string;\n onChange: (value: boolean | string | string[]) => void;\n value: boolean | string | string[] | undefined;\n};\n\nfunction CustomField(props: CustomFieldProps) {\n const { field, idPrefix } = props;\n const controlId = `${idPrefix}-custom-${field.id}`;\n const errorId = `${controlId}-error`;\n const controlProps = { ...props, controlId, errorId };\n switch (field.type) {\n case \"checkbox\":\n return <BooleanCustomField {...controlProps} field={field} />;\n case \"text\":\n case \"textarea\":\n return <TextCustomField {...controlProps} field={field} />;\n case \"select\":\n case \"multi_select\":\n return <SelectCustomField {...controlProps} field={field} />;\n case \"radio\":\n case \"checkboxes\":\n return <ChoiceCustomField {...controlProps} field={field} />;\n default:\n return null;\n }\n}\n\nfunction BooleanCustomField({\n choiceClassName,\n controlId,\n error,\n errorClassName,\n errorId,\n field,\n onChange,\n value,\n}: ControlProps & { field: LockerverseBooleanCustomField }) {\n return (\n <label className={choiceClassName} htmlFor={controlId}>\n <input\n aria-describedby={error ? errorId : undefined}\n aria-invalid={error ? \"true\" : undefined}\n checked={value === true}\n id={controlId}\n name={`custom:${field.id}`}\n onChange={(event) => onChange(event.currentTarget.checked)}\n required={field.required}\n type=\"checkbox\"\n />\n <span>{field.label}</span>\n <FieldError className={errorClassName} error={error} id={errorId} />\n </label>\n );\n}\n\ntype ControlProps = CustomFieldProps & {\n controlId: string;\n errorId: string;\n};\n\nfunction FieldError({\n className,\n error,\n id,\n}: {\n className: string;\n error: string | undefined;\n id: string;\n}) {\n return error ? (\n <span className={className} id={id} role=\"alert\">\n {error}\n </span>\n ) : null;\n}\n\nfunction TextCustomField({\n controlId,\n error,\n errorClassName,\n errorId,\n field,\n onChange,\n value,\n}: ControlProps & {\n field: Extract<LockerverseCustomField, { type: \"text\" | \"textarea\" }>;\n}) {\n const commonProps = {\n \"aria-describedby\": error ? errorId : undefined,\n \"aria-invalid\": error ? (\"true\" as const) : undefined,\n id: controlId,\n name: `custom:${field.id}`,\n onChange: (\n event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>\n ) => onChange(event.currentTarget.value),\n required: field.required,\n value: getStringValue(value),\n };\n return (\n <label htmlFor={controlId}>\n <span>{field.label}</span>\n {field.type === \"textarea\" ? (\n <textarea {...commonProps} />\n ) : (\n <input {...commonProps} />\n )}\n <FieldError className={errorClassName} error={error} id={errorId} />\n </label>\n );\n}\n\nfunction SelectCustomField({\n controlId,\n error,\n errorClassName,\n errorId,\n field,\n onChange,\n value,\n}: ControlProps & {\n field: LockerverseMultiOptionCustomField | LockerverseSingleOptionCustomField;\n}) {\n return (\n <label htmlFor={controlId}>\n <span>{field.label}</span>\n <select\n aria-describedby={error ? errorId : undefined}\n aria-invalid={error ? \"true\" : undefined}\n id={controlId}\n multiple={field.type === \"multi_select\"}\n name={`custom:${field.id}`}\n onChange={(event) =>\n onChange(\n field.type === \"multi_select\"\n ? [...event.currentTarget.selectedOptions].map(\n (option) => option.value\n )\n : event.currentTarget.value\n )\n }\n required={field.required}\n value={\n value === true || value === false\n ? \"\"\n : (value ?? (field.type === \"multi_select\" ? [] : \"\"))\n }\n >\n {field.type === \"select\" ? <option value=\"\">Select…</option> : null}\n {field.options.map((option) => (\n <option key={option.id} value={option.id}>\n {option.label}\n </option>\n ))}\n </select>\n <FieldError className={errorClassName} error={error} id={errorId} />\n </label>\n );\n}\n\nfunction ChoiceCustomField({\n choiceClassName,\n controlId,\n error,\n errorClassName,\n errorId,\n field,\n onChange,\n value,\n}: ControlProps & {\n field: LockerverseMultiOptionCustomField | LockerverseSingleOptionCustomField;\n}) {\n const selectedValues = Array.isArray(value) ? value : [];\n return (\n <fieldset\n aria-describedby={error ? errorId : undefined}\n aria-invalid={error ? \"true\" : undefined}\n >\n <legend>{field.label}</legend>\n {field.options.map((option, index) => (\n <label className={choiceClassName} key={option.id}>\n <input\n checked={\n Array.isArray(value)\n ? value.includes(option.id)\n : value === option.id\n }\n id={`${controlId}-${index}`}\n name={`custom:${field.id}`}\n onChange={(event) => {\n if (field.type === \"radio\") {\n onChange(option.id);\n return;\n }\n onChange(\n event.currentTarget.checked\n ? [...selectedValues, option.id]\n : selectedValues.filter((id) => id !== option.id)\n );\n }}\n required={field.required && field.type === \"radio\"}\n type={field.type === \"radio\" ? \"radio\" : \"checkbox\"}\n value={option.id}\n />\n <span>{option.label}</span>\n </label>\n ))}\n <FieldError className={errorClassName} error={error} id={errorId} />\n </fieldset>\n );\n}\n","export function FormSkeleton({\n fieldCount,\n label,\n sectionCount = 0,\n showCheckbox = false,\n}: {\n fieldCount: number;\n label: string;\n sectionCount?: number;\n showCheckbox?: boolean;\n}) {\n return (\n <div className=\"lockerverse-form-skeleton__loading\">\n <span className=\"lockerverse-form-skeleton__sr-only\" role=\"status\">\n {label}\n </span>\n <div aria-hidden=\"true\" className=\"lockerverse-form-skeleton\">\n <div className=\"lockerverse-form-skeleton__branding\">\n <span className=\"lockerverse-form-skeleton__avatar\" />\n <span className=\"lockerverse-form-skeleton__community\" />\n </div>\n <div className=\"lockerverse-form-skeleton__fields\">\n {Array.from({ length: fieldCount }, (_, index) => (\n <div className=\"lockerverse-form-skeleton__field\" key={index}>\n <span className=\"lockerverse-form-skeleton__label\" />\n <span className=\"lockerverse-form-skeleton__input\" />\n </div>\n ))}\n </div>\n {Array.from({ length: sectionCount }, (_, index) => (\n <div className=\"lockerverse-form-skeleton__section\" key={index}>\n <span className=\"lockerverse-form-skeleton__section-label\" />\n <div className=\"lockerverse-form-skeleton__section-content\">\n <span className=\"lockerverse-form-skeleton__section-full\" />\n <div className=\"lockerverse-form-skeleton__section-grid\">\n <span className=\"lockerverse-form-skeleton__section-half\" />\n <span className=\"lockerverse-form-skeleton__section-half\" />\n </div>\n </div>\n </div>\n ))}\n <div className=\"lockerverse-form-skeleton__actions\">\n {showCheckbox ? (\n <span className=\"lockerverse-form-skeleton__check-line\" />\n ) : null}\n <span className=\"lockerverse-form-skeleton__button\" />\n </div>\n </div>\n </div>\n );\n}\n","import { email, nonEmpty, pipe, regex, string, transform, trim } from \"valibot\";\n\nexport const EMAIL_REQUIRED_MESSAGE = \"Email is required.\";\nexport const EMAIL_INVALID_MESSAGE = \"Enter a valid email address.\";\nexport const PHONE_REQUIRED_MESSAGE = \"Phone is required.\";\nexport const PHONE_INVALID_MESSAGE = \"Enter a valid phone number.\";\n\nconst OPTIONAL_EMAIL_PATTERN = /^(?:$|[^\\s@]+@[^\\s@]+\\.[^\\s@]+)$/;\nconst INTERNATIONAL_PHONE_PATTERN = /^\\+[1-9]\\d{6,14}$/;\nconst OPTIONAL_INTERNATIONAL_PHONE_PATTERN = /^(?:$|\\+[1-9]\\d{6,14})$/;\n\nexport function normalizePhone(input: string) {\n return input.trim().replace(/[().\\s-]/g, \"\");\n}\n\nexport const optionalEmailSchema = pipe(\n string(),\n trim(),\n regex(OPTIONAL_EMAIL_PATTERN, EMAIL_INVALID_MESSAGE)\n);\n\nexport const requiredEmailSchema = pipe(\n string(),\n trim(),\n nonEmpty(EMAIL_REQUIRED_MESSAGE),\n email(EMAIL_INVALID_MESSAGE)\n);\n\nexport const optionalPhoneSchema = pipe(\n string(),\n trim(),\n transform(normalizePhone),\n regex(OPTIONAL_INTERNATIONAL_PHONE_PATTERN, PHONE_INVALID_MESSAGE)\n);\n\nexport const requiredPhoneSchema = pipe(\n string(),\n trim(),\n nonEmpty(PHONE_REQUIRED_MESSAGE),\n transform(normalizePhone),\n regex(INTERNATIONAL_PHONE_PATTERN, PHONE_INVALID_MESSAGE)\n);\n","export function notifyHostCallback<Value>(\n callback: ((value: Value) => void) | undefined,\n value: Value\n) {\n if (!callback) {\n return;\n }\n try {\n Promise.resolve(callback(value)).catch(() => undefined);\n } catch {\n // Host callback failures must not change completed SDK state.\n }\n}\n"],"mappings":"mMAAA,MAAM,EAAY,8BACZ,EAAuB,6BAE7B,SAAgB,EAAqB,EAAe,CAClD,IAAM,EAAe,EAAM,KAAK,EAChC,OAAO,EAAqB,KAAK,CAAY,EACzC,IAAI,IACJ,CACN,CAEA,SAAS,EAAc,EAAe,CACpC,IAAM,EAAQ,EAAU,KAAK,EAAqB,CAAK,CAAC,EACxD,GAAI,CAAC,EACH,OAEF,GAAM,EAAG,GAAS,EAClB,GAAI,CAAC,EACH,OAEF,IAAM,EACJ,EAAM,SAAW,EACb,MAAM,KAAK,EAAQ,GAAc,GAAG,IAAY,GAAW,CAAC,CAAC,KAAK,EAAE,EACpE,EACN,MAAO,CAAC,EAAG,EAAG,CAAC,CAAC,CAAC,IAAK,GACpB,OAAO,SAAS,EAAS,MAAM,EAAQ,EAAS,CAAC,EAAG,EAAE,CACxD,CACF,CAEA,SAAS,EAAkB,CAAC,EA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CAA4C,CAAA,EAC5D,EAAC,MAAD,CAAK,UAAU,6CAAf,SAAA,CACE,EAAC,OAAD,CAAM,UAAU,yCAA2C,CAAA,EAC3D,EAAC,MAAD,CAAK,UAAU,0CAAf,SAAA,CACE,EAAC,OAAD,CAAM,UAAU,yCAA2C,CAAA,EAC3D,EAAC,OAAD,CAAM,UAAU,yCAA2C,CAAA,CACxD,CACF,CAAA,CAAA,CACF,CAAA,CAAA,CAToD,EAAA,CASpD,CACN,EACD,EAAC,MAAD,CAAK,UAAU,qCAAf,SAAA,CACG,EACC,EAAC,OAAD,CAAM,UAAU,uCAAyC,CAAA,EACvD,KACJ,EAAC,OAAD,CAAM,UAAU,mCAAqC,CAAA,CAClD,GACF,CACF,CAAA,CAAA,GAET,CChDA,MACa,EAAwB,+BAExB,EAAwB,8BAE/B,EAAyB,mCACzB,EAA8B,oBAC9B,EAAuC,0BAE7C,SAAgB,EAAe,EAAe,CAC5C,OAAO,EAAM,KAAK,CAAC,CAAC,QAAQ,YAAa,EAAE,CAC7C,CAEA,MAAa,EAAsB,EACjC,EAAO,EACP,EAAK,EACL,EAAM,EAAwB,CAAqB,CACrD,EAEa,EAAsB,EACjC,EAAO,EACP,EAAK,EACL,EAAS,oBAAsB,EAC/B,EAAM,CAAqB,CAC7B,EAEa,EAAsB,EACjC,EAAO,EACP,EAAK,EACL,EAAU,CAAc,EACxB,EAAM,EAAsC,CAAqB,CACnE,EAEa,EAAsB,EACjC,EAAO,EACP,EAAK,EACL,EAAS,oBAAsB,EAC/B,EAAU,CAAc,EACxB,EAAM,EAA6B,CAAqB,CAC1D,ECzCA,SAAgB,EACd,EACA,EACA,CACK,KAGL,GAAI,CACF,QAAQ,QAAQ,EAAS,CAAK,CAAC,CAAC,CAAC,UAAY,IAAA,EAAS,CACxD,MAAQ,CAER,CACF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{f as e,p as t}from"./host-callback.js";import{n,t as r}from"./lockerverse-payment.js";import{Dialog as i}from"@base-ui/react/dialog";import{getLockerverseMinimumCustomAmountCents as a}from"@lockerverse/sdk/checkout";import{createElement as o,useState as s}from"react";import{Fragment as c,jsx as l,jsxs as u}from"react/jsx-runtime";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`),`${d.format(e/100)}${n}`}function g({customAmounts:e,product:t,quantities:n,recurringProductId:r,setCustomAmounts:i,setQuantities:o,setRecurringProductId:s}){let c=n[t.id]??0;if(t.pricingMode===`fixed`&&t.paymentOption===`one-time`){let e=Math.min(t.maximumQuantity??1/0,t.inventoryQuantity??1/0);return u(`span`,{className:`lockerverse-launcher__quantity`,children:[l(`button`,{"aria-label":`Decrease ${t.name} quantity`,disabled:c===0,onClick:()=>{s(null),o(e=>{let n=e[t.id]??0,r=t.minimumQuantity??1;return{...e,[t.id]:n<=r?0:n-1}})},type:`button`,children:`−`}),l(`output`,{"aria-label":`${t.name} quantity`,children:c}),l(`button`,{"aria-label":`Increase ${t.name} quantity`,disabled:c>=e,onClick:()=>{s(null),o(e=>{let n=e[t.id]??0;return{...e,[t.id]:n===0?t.minimumQuantity??1:n+1}})},type:`button`,children:`+`})]})}return t.pricingMode===`custom`&&t.paymentOption===`one-time`?u(`span`,{className:`lockerverse-launcher__custom-amount`,children:[l(`span`,{"aria-hidden":`true`,children:`$`}),l(`input`,{"aria-label":`${t.name} amount`,min:a(t)/100,name:`amount-${t.slug}`,onChange:e=>{s(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:u(`small`,{children:[`Minimum `,d.format(t.minimumAmountCents/100)]})]}):l(`button`,{"aria-label":`Select ${t.name}`,"aria-pressed":r===t.id,className:`lockerverse-launcher__select`,onClick:()=>{o({}),i({}),s(e=>e===t.id?null:t.id)},type:`button`,children:`Select`})}function _({variant:e=`default`,...t}){let{customAmounts:n,product:r,quantities:i,recurringProductId:o}=t,s=m(n[r.id]??``),c=o===r.id||r.paymentOption===`one-time`&&(r.pricingMode===`fixed`&&(i[r.id]??0)>0||r.pricingMode===`custom`&&s!==null&&s>=a(r));return u(`article`,{className:`lockerverse-launcher__product lockerverse-launcher__product--${e}`,"data-selected":c||void 0,children:[u(`span`,{className:`lockerverse-launcher__product-copy`,children:[l(`strong`,{className:`lockerverse-launcher__product-name`,children:r.name}),r.description?l(`small`,{children:r.description}):null,r.amountCents===null?null:l(`span`,{className:`lockerverse-launcher__product-price`,children:h(r.amountCents,r.paymentOption)})]}),l(g,{...t})]})}function v({customAmounts:e,product:t,setCustomAmounts:n,setRecurringProductId:r}){let i=e[t.id]??``,o=m(i),s=p.filter(e=>e>=a(t)),c=s.includes(o??0),f=e=>{r(null),n(n=>({...n,[t.id]:e}))};return l(`div`,{className:`lockerverse-launcher__donation-option`,children:u(`fieldset`,{className:`lockerverse-launcher__donation-choices`,children:[u(`legend`,{className:`lockerverse-launcher__sr-only`,children:[t.name,` amount`]}),l(`button`,{"aria-pressed":i===``,onClick:()=>f(``),type:`button`,children:`No thanks`}),s.map(e=>l(`button`,{"aria-pressed":o===e,onClick:()=>f(String(e/100)),type:`button`,children:d.format(e/100).replace(`.00`,``)},e)),l(`label`,{className:`lockerverse-launcher__donation-other`,"data-selected":i!==``&&!c||void 0,children:l(`input`,{"aria-label":`${t.name} amount`,min:a(t)/100,name:`amount-${t.slug}`,onChange:e=>f(e.target.value),placeholder:`Other $`,step:`0.01`,type:`number`,value:c?``:i})})]})})}function y({products:e,variant:t=`default`,...n}){return l(`div`,{className:`lockerverse-launcher__product-list`,children:e.map(e=>t===`donation`?o(v,{...n,key:e.id,product:e}):o(_,{...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 l(`div`,{"aria-label":`Loading donation options`,className:`lockerverse-launcher__loading`,role:`status`,children:[0,1,2].map(e=>l(`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>=a(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(e=>!a.includes(e));return u(`form`,{className:`lockerverse-launcher__products`,onSubmit:e=>{e.preventDefault(),r.length>0&&t(r)},children:[o.length>0?l(`section`,{className:`lockerverse-launcher__section`,children:l(y,{...n,products:o})}):null,a.length>0?u(`section`,{className:`lockerverse-launcher__donation`,children:[u(`header`,{className:`lockerverse-launcher__section-header`,children:[l(`h3`,{children:`Add a donation`}),l(`p`,{children:`Choose an amount to add to this order.`})]}),l(y,{...n,products:a,variant:`donation`})]}):null,e.products.length>0?u(`footer`,{className:`lockerverse-launcher__footer`,children:[u(`p`,{"aria-live":`polite`,className:`lockerverse-launcher__summary`,children:[l(`span`,{children:i.itemCount===0?`No items selected`:`${i.itemCount} ${i.itemCount===1?`item`:`items`} selected`}),i.itemCount===0?null:l(`strong`,{children:d.format(i.amountCents/100)})]}),l(`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 u(`div`,{className:`lockerverse-launcher__checkout`,children:[l(`header`,{className:`lockerverse-launcher__checkout-toolbar`,children:l(`button`,{className:`lockerverse-launcher__back`,onClick:e,type:`button`,children:`Edit order`})}),l(r,{...t,selection:n,style:i,widget:a})]})}function T({catalog:e,checkout:t}){return t?u(c,{children:[l(i.Title,{className:`lockerverse-launcher__sr-only`,children:`Checkout`}),l(i.Description,{className:`lockerverse-launcher__sr-only`,children:`Review the order and complete payment.`})]}):e?u(`header`,{className:`lockerverse-launcher__header`,children:[e.community?u(`div`,{className:`lockerverse-launcher__brand`,children:[e.community.imageUrl?l(`img`,{alt:`${e.community.name} logo`,height:`28`,src:e.community.imageUrl,width:`28`}):null,l(`span`,{children:e.community.name})]}):null,l(i.Title,{className:`lockerverse-launcher__title`,children:e.widget.title??e.widget.name}),l(i.Description,{className:`lockerverse-launcher__description`,children:e.widget.description??`Choose your options, then continue to checkout.`})]}):u(`header`,{className:`lockerverse-launcher__header`,children:[l(i.Title,{className:`lockerverse-launcher__title`,children:`Donate`}),l(i.Description,{className:`lockerverse-launcher__description`,children:`Choose your options, then continue to checkout.`})]})}function E({buttonLabel:r=`Donate`,position:a=`inline`,widget:o,...c}){let[d,f]=s(null),[p,m]=s({}),[h,g]=s({}),[_,v]=s(null),{catalog:y,error:b,loading:S}=o,E=t(c.style?.[`--lockerverse-accent`]??y?.community?.accentColor??`#38d77a`),D=e(E),O={...c.style
|
|
1
|
+
import{f as e,p as t}from"./host-callback.js";import{n,t as r}from"./lockerverse-payment.js";import{Dialog as i}from"@base-ui/react/dialog";import{getLockerverseMinimumCustomAmountCents as a}from"@lockerverse/sdk/checkout";import{createElement as o,useState as s}from"react";import{Fragment as c,jsx as l,jsxs as u}from"react/jsx-runtime";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`),`${d.format(e/100)}${n}`}function g({customAmounts:e,product:t,quantities:n,recurringProductId:r,setCustomAmounts:i,setQuantities:o,setRecurringProductId:s}){let c=n[t.id]??0;if(t.pricingMode===`fixed`&&t.paymentOption===`one-time`){let e=Math.min(t.maximumQuantity??1/0,t.inventoryQuantity??1/0);return u(`span`,{className:`lockerverse-launcher__quantity`,children:[l(`button`,{"aria-label":`Decrease ${t.name} quantity`,disabled:c===0,onClick:()=>{s(null),o(e=>{let n=e[t.id]??0,r=t.minimumQuantity??1;return{...e,[t.id]:n<=r?0:n-1}})},type:`button`,children:`−`}),l(`output`,{"aria-label":`${t.name} quantity`,children:c}),l(`button`,{"aria-label":`Increase ${t.name} quantity`,disabled:c>=e,onClick:()=>{s(null),o(e=>{let n=e[t.id]??0;return{...e,[t.id]:n===0?t.minimumQuantity??1:n+1}})},type:`button`,children:`+`})]})}return t.pricingMode===`custom`&&t.paymentOption===`one-time`?u(`span`,{className:`lockerverse-launcher__custom-amount`,children:[l(`span`,{"aria-hidden":`true`,children:`$`}),l(`input`,{"aria-label":`${t.name} amount`,min:a(t)/100,name:`amount-${t.slug}`,onChange:e=>{s(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:u(`small`,{children:[`Minimum `,d.format(t.minimumAmountCents/100)]})]}):l(`button`,{"aria-label":`Select ${t.name}`,"aria-pressed":r===t.id,className:`lockerverse-launcher__select`,onClick:()=>{o({}),i({}),s(e=>e===t.id?null:t.id)},type:`button`,children:`Select`})}function _({variant:e=`default`,...t}){let{customAmounts:n,product:r,quantities:i,recurringProductId:o}=t,s=m(n[r.id]??``),c=o===r.id||r.paymentOption===`one-time`&&(r.pricingMode===`fixed`&&(i[r.id]??0)>0||r.pricingMode===`custom`&&s!==null&&s>=a(r));return u(`article`,{className:`lockerverse-launcher__product lockerverse-launcher__product--${e}`,"data-selected":c||void 0,children:[u(`span`,{className:`lockerverse-launcher__product-copy`,children:[l(`strong`,{className:`lockerverse-launcher__product-name`,children:r.name}),r.description?l(`small`,{children:r.description}):null,r.amountCents===null?null:l(`span`,{className:`lockerverse-launcher__product-price`,children:h(r.amountCents,r.paymentOption)})]}),l(g,{...t})]})}function v({customAmounts:e,product:t,setCustomAmounts:n,setRecurringProductId:r}){let i=e[t.id]??``,o=m(i),s=p.filter(e=>e>=a(t)),c=s.includes(o??0),f=e=>{r(null),n(n=>({...n,[t.id]:e}))};return l(`div`,{className:`lockerverse-launcher__donation-option`,children:u(`fieldset`,{className:`lockerverse-launcher__donation-choices`,children:[u(`legend`,{className:`lockerverse-launcher__sr-only`,children:[t.name,` amount`]}),l(`button`,{"aria-pressed":i===``,onClick:()=>f(``),type:`button`,children:`No thanks`}),s.map(e=>l(`button`,{"aria-pressed":o===e,onClick:()=>f(String(e/100)),type:`button`,children:d.format(e/100).replace(`.00`,``)},e)),l(`label`,{className:`lockerverse-launcher__donation-other`,"data-selected":i!==``&&!c||void 0,children:l(`input`,{"aria-label":`${t.name} amount`,min:a(t)/100,name:`amount-${t.slug}`,onChange:e=>f(e.target.value),placeholder:`Other $`,step:`0.01`,type:`number`,value:c?``:i})})]})})}function y({products:e,variant:t=`default`,...n}){return l(`div`,{className:`lockerverse-launcher__product-list`,children:e.map(e=>t===`donation`?o(v,{...n,key:e.id,product:e}):o(_,{...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 l(`div`,{"aria-label":`Loading donation options`,className:`lockerverse-launcher__loading`,role:`status`,children:[0,1,2].map(e=>l(`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>=a(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(e=>!a.includes(e));return u(`form`,{className:`lockerverse-launcher__products`,onSubmit:e=>{e.preventDefault(),r.length>0&&t(r)},children:[o.length>0?l(`section`,{className:`lockerverse-launcher__section`,children:l(y,{...n,products:o})}):null,a.length>0?u(`section`,{className:`lockerverse-launcher__donation`,children:[u(`header`,{className:`lockerverse-launcher__section-header`,children:[l(`h3`,{children:`Add a donation`}),l(`p`,{children:`Choose an amount to add to this order.`})]}),l(y,{...n,products:a,variant:`donation`})]}):null,e.products.length>0?u(`footer`,{className:`lockerverse-launcher__footer`,children:[u(`p`,{"aria-live":`polite`,className:`lockerverse-launcher__summary`,children:[l(`span`,{children:i.itemCount===0?`No items selected`:`${i.itemCount} ${i.itemCount===1?`item`:`items`} selected`}),i.itemCount===0?null:l(`strong`,{children:d.format(i.amountCents/100)})]}),l(`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 u(`div`,{className:`lockerverse-launcher__checkout`,children:[l(`header`,{className:`lockerverse-launcher__checkout-toolbar`,children:l(`button`,{className:`lockerverse-launcher__back`,onClick:e,type:`button`,children:`Edit order`})}),l(r,{...t,selection:n,style:i,widget:a})]})}function T({catalog:e,checkout:t}){return t?u(c,{children:[l(i.Title,{className:`lockerverse-launcher__sr-only`,children:`Checkout`}),l(i.Description,{className:`lockerverse-launcher__sr-only`,children:`Review the order and complete payment.`})]}):e?u(`header`,{className:`lockerverse-launcher__header`,children:[e.community?u(`div`,{className:`lockerverse-launcher__brand`,children:[e.community.imageUrl?l(`img`,{alt:`${e.community.name} logo`,height:`28`,src:e.community.imageUrl,width:`28`}):null,l(`span`,{children:e.community.name})]}):null,l(i.Title,{className:`lockerverse-launcher__title`,children:e.widget.title??e.widget.name}),l(i.Description,{className:`lockerverse-launcher__description`,children:e.widget.description??`Choose your options, then continue to checkout.`})]}):u(`header`,{className:`lockerverse-launcher__header`,children:[l(i.Title,{className:`lockerverse-launcher__title`,children:`Donate`}),l(i.Description,{className:`lockerverse-launcher__description`,children:`Choose your options, then continue to checkout.`})]})}function E({buttonLabel:r=`Donate`,position:a=`inline`,widget:o,...c}){let[d,f]=s(null),[p,m]=s({}),[h,g]=s({}),[_,v]=s(null),{catalog:y,error:b,loading:S}=o,E=t(c.style?.[`--lockerverse-accent`]??y?.community?.accentColor??`#38d77a`),D=e(E),O={...c.style};(c.style?.[`--lockerverse-accent`]!==void 0||y?.community?.accentColor)&&(O[`--lockerverse-accent`]=E),D&&c.style?.[`--lockerverse-accent-contrast`]===void 0&&(O[`--lockerverse-accent-contrast`]=D);let k;return k=S?l(x,{}):b?u(`div`,{role:`alert`,children:[l(`p`,{children:`Unable to load donation options.`}),l(`button`,{onClick:o.refresh,type:`button`,children:`Retry`})]}):y?l(C,{catalog:y,customAmounts:p,onContinue:f,quantities:h,recurringProductId:_,setCustomAmounts:m,setQuantities:g,setRecurringProductId:v}):l(x,{}),!(S||b)&&d&&y&&(k=l(w,{onEdit:()=>f(null),paymentProps:c,selection:d,style:O,widget:o})),u(i.Root,{onOpenChange:e=>{e&&y&&c.stripeLoader===void 0&&requestAnimationFrame(()=>{n(y)})},children:[l(i.Trigger,{className:`lockerverse-launcher lockerverse-launcher--${a}`,"data-lockerverse-theme":c.theme??`dark`,style:O,children:r}),u(i.Portal,{children:[l(i.Backdrop,{className:`lockerverse-launcher__backdrop`}),l(i.Viewport,{className:`lockerverse-launcher__viewport`,children:u(i.Popup,{className:`lockerverse-launcher__dialog`,"data-lockerverse-theme":c.theme??`dark`,style:O,children:[l(T,{catalog:y,checkout:d!==null}),l(i.Close,{"aria-label":`Close donation dialog`,className:`lockerverse-launcher__close`,children:l(`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\"\n) {\n let cadence = \"\";\n if (paymentOption === \"monthly\") {\n cadence = \"/month\";\n }\n if (paymentOption === \"annually\") {\n cadence = \"/year\";\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 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 const minimum = product.minimumQuantity ?? 1;\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={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\n ? (product.minimumQuantity ?? 1)\n : 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 = {\n ...paymentProps.style,\n ...(paymentProps.style?.[\"--lockerverse-accent\"] !== undefined ||\n catalog?.community?.accentColor\n ? { \"--lockerverse-accent\": accent }\n : {}),\n ...(accentContrast &&\n paymentProps.style?.[\"--lockerverse-accent-contrast\"] === undefined\n ? { \"--lockerverse-accent-contrast\": accentContrast }\n : {}),\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":"mVAuBA,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,GAOd,OANI,IAAkB,YACpB,EAAU,UAER,IAAkB,aACpB,EAAU,SAEL,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,KAAK,IACnB,EAAQ,iBAAmB,IAC3B,EAAQ,mBAA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UAAW,8CAA8C,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\"\n) {\n let cadence = \"\";\n if (paymentOption === \"monthly\") {\n cadence = \"/month\";\n }\n if (paymentOption === \"annually\") {\n cadence = \"/year\";\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 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 const minimum = product.minimumQuantity ?? 1;\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={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\n ? (product.minimumQuantity ?? 1)\n : 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":"mVAuBA,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,GAOd,OANI,IAAkB,YACpB,EAAU,UAER,IAAkB,aACpB,EAAU,SAEL,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,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EAA0B,CAAO,CACnC,CAAC,CAEL,EAPF,SAAA,CASE,EAAC,EAAO,QAAR,CACE,UAAW,8CAA8C,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,2 +1,2 @@
|
|
|
1
|
-
import{a as e,c as t,d as n,f as r,l as i,n as a,o,p as s,s as c,t as l,u}from"./host-callback.js";import{LockerverseSdkError as d,estimateLockerverseCheckout as f}from"@lockerverse/sdk/checkout";import{createContext as p,useCallback as m,useContext as h,useEffect as g,useId as _,useLayoutEffect as v,useMemo as y,useReducer as b,useRef as x,useState as S}from"react";import{AddressElement as C,Elements as w,PaymentElement as T,useElements as ee,useStripe as E}from"@stripe/react-stripe-js";import{loadStripe as D}from"@stripe/stripe-js/pure/index.js";import{array as O,minLength as k,minValue as A,nonEmpty as j,number as M,object as N,pipe as P,regex as F,safeInteger as I,safeParse as L,strictObject as R,string as z,trim as B,union as V}from"valibot";import{Fragment as te,jsx as H,jsxs as U}from"react/jsx-runtime";import{Select as W}from"@base-ui/react/select";const ne=p(void 0);function re({children:e,container:t}){return H(ne.Provider,{value:t,children:e})}function ie(){return H(`svg`,{"aria-hidden":`true`,fill:`none`,viewBox:`0 0 16 16`,children:H(`path`,{d:`m4 6 4 4 4-4`})})}function ae(){return H(`svg`,{"aria-hidden":`true`,fill:`none`,viewBox:`0 0 16 16`,children:H(`path`,{d:`m3 8 3 3 7-7`})})}function G({ariaDescribedBy:e,ariaLabel:t,ariaLabelledBy:n,className:r,id:i,invalid:a=!1,name:o,onValueChange:s,options:c,value:l}){let u=h(ne),d=[`lockerverse-payment__select`,r].filter(Boolean).join(` `);return H(`div`,{className:d,children:U(W.Root,{id:i,items:c,name:o,onValueChange:e=>{e!==null&&s(e)},value:l,children:[U(W.Trigger,{"aria-describedby":e,"aria-invalid":a||void 0,"aria-label":t,"aria-labelledby":n,className:`lockerverse-payment__select-trigger`,children:[H(W.Value,{}),H(W.Icon,{"aria-hidden":`true`,className:`lockerverse-payment__select-icon`,children:H(ie,{})})]}),H(W.Portal,{container:u,children:H(W.Positioner,{alignItemWithTrigger:!1,className:`lockerverse-payment__select-positioner`,sideOffset:6,children:H(W.Popup,{className:`lockerverse-payment__select-popup`,children:H(W.List,{className:`lockerverse-payment__select-list`,children:c.map(e=>U(W.Item,{className:`lockerverse-payment__select-item`,value:e.value,children:[H(W.ItemText,{children:e.label}),H(W.ItemIndicator,{"aria-hidden":`true`,className:`lockerverse-payment__select-item-indicator`,children:H(ae,{})})]},e.value))})})})})]})})}const K=[`XS`,`S`,`M`,`L`,`XL`,`XXL`,`XXXL`],oe=[`15`,`12`,`10`,`5`],q=[...oe,`custom`];function se({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=q.indexOf(t),r;switch(e.key){case`ArrowDown`:case`ArrowRight`:r=(n+1)%q.length;break;case`ArrowLeft`:case`ArrowUp`:r=(n-1+q.length)%q.length;break;case`Home`:r=0;break;case`End`:r=q.length-1;break;default:return}e.preventDefault();let i=q[r];i&&((e.currentTarget.closest(`[role="radiogroup"]`)?.querySelectorAll(`input[type="radio"]`))?.[r]?.focus(),a({tipPercent:i}))};return U(`div`,{className:`lockerverse-payment__tip-box`,children:[H(`p`,{children:`Add a tip to support the Lockerverse platform`}),U(`div`,{"aria-label":`Tip amount`,role:`radiogroup`,children:[oe.map(e=>U(`label`,{className:`lockerverse-payment__tip-choice`,children:[H(`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}),U(`span`,{children:[e,`%`]})]},e)),U(`label`,{className:`lockerverse-payment__tip-choice`,children:[H(`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`}),H(`span`,{children:`Other`})]})]}),i.tipPercent===`custom`?U(`label`,{children:[H(`span`,{children:`Custom tip`}),U(`span`,{className:`lockerverse-payment__money-input`,children:[H(`span`,{"aria-hidden":`true`,children:`$`}),H(`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?H(`span`,{className:`lockerverse-payment__field-message`,id:n,children:t}):null]}):H(`input`,{name:`tip`,type:`hidden`,value:i.tipPercent})]})}function J({checked:e,children:t,name:n,onChange:r}){return U(`label`,{className:`lockerverse-payment__check-row`,children:[H(`input`,{checked:e,name:n,onChange:e=>r(e.currentTarget.checked),type:`checkbox`}),H(`span`,{children:t})]})}function ce({customFields:e,errors:n,fields:r,idPrefix:i,isPromoApplying:a,onChange:o,onApplyPromo:s,promoError:c,values:l}){let u=e=>o({...l,...e});return U(`div`,{className:`lockerverse-payment__additional-fields`,children:[r.memberId?U(`label`,{children:[H(`span`,{children:`Member ID`}),H(`input`,{name:`memberId`,onChange:e=>u({memberId:e.currentTarget.value}),placeholder:`Optional`,value:l.memberId})]}):null,r.merchSize?U(`div`,{className:`lockerverse-payment__field`,children:[H(`span`,{id:`${i}-merch-size-label`,children:`Size`}),H(G,{ariaLabelledBy:`${i}-merch-size-label`,name:`merchSize`,onValueChange:e=>u({merchSize:e}),options:K.map(e=>({label:e,value:e})),value:l.merchSize})]}):null,r.promoCode?U(`div`,{className:`lockerverse-payment__field`,children:[H(`span`,{id:`${i}-promo-code-label`,children:`Promo code`}),U(`div`,{className:`lockerverse-payment__promo-control`,children:[H(`input`,{"aria-describedby":c?`${i}-promo-code-error`:void 0,"aria-invalid":c?`true`:void 0,"aria-labelledby":`${i}-promo-code-label`,name:`promoCode`,onChange:e=>u({promoCode:e.currentTarget.value}),placeholder:`Optional`,value:l.promoCode}),H(`button`,{disabled:!l.promoCode.trim()||a,onClick:s,type:`button`,children:a?`Applying…`:`Apply`})]}),c?H(`p`,{className:`lockerverse-payment__field-message`,id:`${i}-promo-code-error`,role:`alert`,children:c}):null]}):null,H(t,{choiceClassName:`lockerverse-payment__check-row`,errorClassName:`lockerverse-payment__field-message`,errors:n,fields:e,idPrefix:i,onChange:e=>u({customFields:e}),values:l.customFields})]})}function Y({amountCents:e,enabled:t,onChange:n,values:r}){return t?U(J,{checked:r.includeServiceFee,name:`includeServiceFee`,onChange:e=>n({...r,includeServiceFee:e}),children:[`Add `,le(e),` to help cover processing fees`]}):null}function le(e){return new Intl.NumberFormat(`en-US`,{currency:`USD`,style:`currency`}).format(e/100)}function ue(e){return a(e)}function de(t,n){let r=n?{...t,phone:ue(t.phone)}:t,i=N(n?{email:e,phone:o}:{email:e}),a=L(i,r);if(a.success)return{errors:{},value:a.output};let s={};for(let e of a.issues){let t=e.path?.[0]?.key;(t===`email`||t===`phone`)&&!s[t]&&(s[t]=e.message)}return{errors:s,value:null}}function fe(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 pe(e,t){if(e.status===`succeeded`||e.status===`unresolved`)return e;switch(t.type){case`field_changed`:return X(e,[`invalid`,`refreshing_quote`],{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`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,status:`editing`});case`succeeded`:return X(e,[`recovering`,`submitting`],{message:t.message,status:`succeeded`});case`unresolved`:return X(e,[`recovering`,`submitting`],{message:t.message,status:`unresolved`});default:return e}}function me(e){return e.status===`editing`||e.status===`invalid`||e.status===`refreshing_quote`?e.error:void 0}function he(e){return e.status===`succeeded`?`success`:e.status===`unresolved`?`unresolved`:e.status===`submitting`||e.status===`recovering`?`submitting`:e.status===`invalid`?`invalid`:me(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){return e.checkoutStatus===`success`?{kind:`success`,payment:e}:e.checkoutStatus===`failed`?{kind:`failed`,payment:e}:{kind:`unresolved`,paymentReference:e.paymentReference,reason:e.checkoutStatus===`action_required`?`action_required`:`pending`}}async function xe(e,t,n){if(t.checkoutStatus!==`action_required`)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 d&&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=P(z(),B(),j()),Te=P(M(),I(),A(1)),Ee=P(O(V([R({amountCents:Te,productSlug:we}),R({productSlug:we,quantity:Te}),R({productSlug:we})])),k(1)),De=P(z(),B(),F(/^(?:0|[1-9]\d*)(?:\.\d{1,2})?$/,`Enter a valid tip amount.`));function Oe(e){let t=L(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=L(Ee,e);return t.success?{success:!0,value:t.output}:{message:`Lockerverse payment configuration is invalid.`,success:!1}}function Ae(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 je(e,t,n,r){return{...n?{email:n}:{},...e.widget.fields.serviceFee?{includeServiceFee:t.includeServiceFee}:{},...e.widget.fields.promoCode&&t.promoCode.trim()?{promoCode:t.promoCode.trim()}:{},...e.widget.fields.tipping?{tipCents:r}:{}}}function Me(e,t){if(!e?.complete)throw Error(`${t} address is required.`);return e.value}function Ne(e,t,n,r){if(e.widget.fields.shipping)return t.shippingMatchesBilling?n:Me(r.shipping,`Shipping`)}function Pe({billingAddress:e,catalog:t,email:n,phone:r,shippingAddress:i}){return{payment_method_data:{billing_details:{address:e.address,email:n,name:e.name,...t.widget.fields.phone?{phone:r}:{}}},...i?{shipping:{address:i.address,name:i.name,phone:t.widget.fields.phone?r:i.phone??null}}:{}}}function Fe({catalog:e,confirmationToken:t,email:n,fieldValues:r,metadata:a,phone:o,shippingAddress:s}){return{...t?{confirmationToken:t}:{},customFieldAnswers:i(e.widget.customFields,r.customFields),email:n,...a?{metadata:a}:{},...e.widget.fields.memberId&&r.memberId.trim()?{memberId:r.memberId.trim()}:{},...e.widget.fields.merchSize?{merchSize:r.merchSize}:{},...e.widget.fields.phone?{phone:o}:{},...s?{shipping:{address:{city:s.address.city??``,country:s.address.country,line1:s.address.line1??``,...s.address.line2?{line2:s.address.line2}:{},postal_code:s.address.postal_code??``,state:s.address.state??``},name:s.name}}:{}}}function Z(e,t){l(e,t)}function Ie(e,t){l(e,t)}function Q(e){if(!e())throw Error(`Payment component is no longer active.`)}function Le(e,t,n){return e.kind===`unresolved`&&e.reason===`action_required`&&!t&&!n}async function Re({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=ue(d),_=Ae(f.subtotalCents,o);if(!_.success)throw Error(_.message);let v=je(t,o,h,_.cents),y=await r.calculateTotal({...v,catalog:t,items:n});if(Q(s),y.totalCents>0&&ye(f,y,c,m))return{kind:`quote_changed`,quote:y};if(y.totalCents===0){let n;t.widget.fields.shipping&&(n=Ne(t,o,Me(e.billing,`Billing`),e)),Q(s),Z(u,{connectedAccountId:y.payment.connectedAccountId,paymentReference:y.paymentReference});let i=await Se(r,{checkout:y,submission:Fe({catalog:t,email:h,fieldValues:o,metadata:l,phone:g,...n?{shippingAddress:n}:{}})},p);return Q(s),i.kind===`failed`?{kind:`payment_failed`,message:`Order could not be completed. Review the details and try again.`}:i.kind===`unresolved`?{kind:`payment_unresolved`,paymentReference:i.paymentReference,reason:i.reason}:{kind:`payment`,payment:i.payment,quote:y}}if(!(i&&p))throw Error(`Payment form is still loading.`);await i.update({amount:y.totalCents}),Q(s);let b=await i.submit();if(Q(s),b.error)throw Error(b.error.message);let x=Me(e.billing,`Billing`),S=Ne(t,o,x,e),C=await p.createConfirmationToken({elements:i,params:Pe({billingAddress:x,catalog:t,email:h,phone:g,shippingAddress:S})});if(Q(s),C.error)throw Error(C.error.message);Z(u,{connectedAccountId:y.payment.connectedAccountId,paymentReference:y.paymentReference});let w=await Se(r,{checkout:y,submission:Fe({catalog:t,confirmationToken:C.confirmationToken.id,email:h,fieldValues:o,metadata:l,phone:g,...S?{shippingAddress:S}:{}})},p);return Q(s),w.kind===`failed`?{kind:`payment_failed`,message:`Payment was declined. Check your payment details and try again.`}:w.kind===`unresolved`?{kind:`payment_unresolved`,paymentReference:w.paymentReference,reason:w.reason}:{kind:`payment`,payment:w.payment,quote:y}}function ze(e){return new Intl.NumberFormat(`en-US`,{currency:`USD`,style:`currency`}).format(e/100)}function Be(e,t){if(!t)return e instanceof Error?e.message:`The order total could not be updated.`}function Ve({nextQuote:e,onQuoteChange:t,setDisplayedTotalCents:n,setPromoError:r,updateWorkflow:i,validatePromo:a}){i({type:`quote_refresh_succeeded`}),n(e.totalCents),t(e),a&&r(e.appliedDiscount?.source===`promo_code`?void 0:`This promo code is invalid or cannot be applied.`)}function He({error:e,setPromoError:t,updateWorkflow:n,validatePromo:r}){r&&t(`This promo code is invalid or cannot be applied.`);let i=Be(e,r);n(i===void 0?{type:`quote_refresh_failed`}:{error:i,type:`quote_refresh_failed`})}function Ue({onPaymentComplete:e,onPaymentRecoveryChange:t,onPaymentUncertain:n,onQuoteChange:r,result:i,setDisplayedTotalCents:a,transitionWorkflow:o}){if(i.kind===`quote_changed`){let e=`The total changed to ${ze(i.quote.totalCents)}. Review it and pay again.`;r(i.quote,e),a(i.quote.totalCents),o({type:`quote_changed`});return}if(i.kind===`payment_failed`){Z(t,null),o({error:i.message,type:`retryable_failure`});return}if(i.kind===`payment_unresolved`){o({message:`Payment is still processing. Do not submit it again.`,type:`unresolved`}),Ie(n,{paymentReference:i.paymentReference,reason:i.reason});return}r(i.quote),Z(t,null),o({message:i.payment.paymentRequired?`Payment completed successfully.`:`Order confirmed. No payment was required.`,type:`succeeded`}),l(e,i.payment)}function We(e){let{catalog:t,checkoutItems:n,client:r,elements:i,email:a,fieldValues:o,metadata:s,onPaymentComplete:c,onResumePaymentFailed:u,onPaymentRecoveryChange:d,onPaymentUncertain:f,onQuoteChange:p,onStateChange:h,quote:_,resumePayment:v,stripe:y,stripeConnectedAccountId:b,stripeLoadFailed:C,updateWorkflow:w,workflow:T}=e,[ee,E]=S(_.totalCents),[D,O]=S(),k=x(!1),A=x(0),j=x(0),M=m(e=>w(e,!0),[w]),N=m(()=>{let e=j.current+1;return j.current=e,()=>j.current===e},[]);g(()=>()=>{j.current+=1,A.current+=1},[]);let P=t.widget.fields.tipping?Ae(_.subtotalCents,o):{cents:0,success:!0},F=P.success?P.cents:null;g(()=>{if(F===null)return;let e=t.widget.fields.serviceFee&&o.includeServiceFee?_.serviceFeeCents||Math.round(_.subtotalCents*t.pricingPolicy.serviceFeeRateBasisPoints/1e4):0,n=_.totalCents-_.serviceFeeCents-_.tipCents+e+F;E(n),n>0&&i?.update({amount:n})},[t.pricingPolicy.serviceFeeRateBasisPoints,t.widget.fields.serviceFee,i,o.includeServiceFee,F,_.serviceFeeCents,_.tipCents,_.totalCents,_.subtotalCents]),g(()=>{if(!v||k.current||T.status!==`recovering`)return;k.current=!0;let e=N();return h(he(T)),Ce(r,v.paymentReference,y).then(t=>{if(e()&&!Le(t,y,C)){if(t.kind===`failed`){Z(d,null),u(),M({error:`The previous payment failed. Check your details and try again.`,type:`recovery_failed`});return}if(t.kind===`unresolved`){M({message:`Payment is still processing. Do not submit it again.`,type:`unresolved`}),Ie(f,{paymentReference:t.paymentReference,reason:t.reason});return}Z(d,null),M({message:t.payment.paymentRequired?`Payment completed successfully.`:`Order confirmed. No payment was required.`,type:`succeeded`}),l(c,t.payment)}}),()=>{e()&&(j.current+=1),k.current=!1}},[r,c,u,d,f,h,v,y,C,N,M,T]);let I=m((e=!1,t=!1)=>{t||(A.current+=1),e&&O(void 0),w({type:`field_changed`})},[w]);async function L(e=!1,i=!1){let s=de({email:a.trim().toLowerCase(),phone:``},!1);if(!(P.success&&(s.value||e)))return;A.current+=1;let c=A.current;w({type:`quote_refresh_started`});try{let e=await r.calculateTotal({...je(t,o,s.value?.email??``,P.cents),catalog:t,items:n});if(c!==A.current)return;Ve({nextQuote:e,onQuoteChange:p,setDisplayedTotalCents:E,setPromoError:O,updateWorkflow:w,validatePromo:i})}catch(e){if(c!==A.current)return;He({error:e,setPromoError:O,updateWorkflow:w,validatePromo:i})}}async function R(){O(void 0),await L(!0,!0)}async function z({addresses:e,phone:l}){M({type:`submission_started`});let u=N();try{let m=await Re({addresses:e,catalog:t,checkoutItems:n,client:r,elements:i,email:a,fieldValues:o,isAttemptActive:u,locallyPreviewedTotalCents:ee,metadata:s,onPaymentRecoveryChange:d,phone:l,quote:_,stripe:y,stripeConnectedAccountId:b});if(!u())return;Ue({onPaymentComplete:c,onPaymentRecoveryChange:d,onPaymentUncertain:f,onQuoteChange:p,result:m,setDisplayedTotalCents:E,transitionWorkflow:M})}catch(e){if(!u())return;Z(d,null),M({error:e instanceof Error?e.message:`Payment could not be completed.`,type:`retryable_failure`})}}let B=T.status===`succeeded`||T.status===`unresolved`?T.message:void 0;return{commands:{applyPromo:R,fieldChanged:I,refreshAuthoritativeTotal:L,reportStripeLoadError:e=>M({error:e,type:`retryable_failure`}),reportValidationFailure:()=>M({type:`validation_failed`}),submit:z},state:{displayedTotalCents:ee,isRecovering:T.status===`recovering`,isRefreshingQuote:T.status===`refreshing_quote`,isSubmitting:ge(T),parsedTip:P,paymentError:me(T),promoError:D,terminalMessage:B}}}const Ge=new Map,Ke=(e,t)=>{let n=t?.stripeAccount??null,r=Ge.get(e);r||(r=new Map,Ge.set(e,r));let i=r.get(n);if(i)return i;let a=D(e,t).catch(()=>(r?.get(n)===a&&(r.delete(n),r.size===0&&Ge.delete(e)),null));return r.set(n,a),a};function qe(e){let{connectedAccountId:t,publishableKey:n}=e.payment;return Ke(n,t?{stripeAccount:t}:void 0)}function $(e){return new Intl.NumberFormat(`en-US`,{currency:`USD`,style:`currency`}).format(e/100)}function Je(e){return e===`monthly`?{interval:`month`,label:`Monthly`}:e===`annually`?{interval:`year`,label:`Annual`}:null}const Ye=[{callingCode:`+1`,label:`🇺🇸 +1`,value:`US`},{callingCode:`+52`,label:`🇲🇽 +52`,value:`MX`},{callingCode:`+380`,label:`🇺🇦 +380`,value:`UA`},{callingCode:`+48`,label:`🇵🇱 +48`,value:`PL`},{callingCode:`+1`,label:`🇨🇦 +1`,value:`CA`},{callingCode:`+49`,label:`🇩🇪 +49`,value:`DE`},{callingCode:`+44`,label:`🇬🇧 +44`,value:`GB`},{callingCode:`+46`,label:`🇸🇪 +46`,value:`SE`},{callingCode:`+358`,label:`🇫🇮 +358`,value:`FI`},{callingCode:`+1`,label:`🇵🇷 +1`,value:`PR`}];function Xe(e,t){return e.trim().startsWith(`+`)?e:`${Ye.find(e=>e.value===t)?.callingCode??`+1`}${e}`}function Ze(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 Qe({accentColor:e,catalog:t,checkoutItems:n,client:r,fontFamily:i,metadata:a,onPaymentComplete:o,onResumePaymentFailed:s,onPaymentRecoveryChange:c,onPaymentUncertain:l,onQuoteChange:u,quote:d,resumePayment:f,onStateChange:p,stripeLoader:h,theme:_,visualStyle:v}){let[b,C]=S(()=>fe(!!f)),T=x(b);T.current=b;let ee=m((e,t=!1)=>{let n=pe(T.current,e);n!==T.current&&(T.current=n,C(n),t&&p(he(n)))},[p]),E=Ze(t,d,f),D=x({connectedAccountId:E,paymentOption:d.paymentOption});b.status!==`submitting`&&b.status!==`recovering`&&(D.current={connectedAccountId:E,paymentOption:d.paymentOption});let{connectedAccountId:O,paymentOption:k}=D.current,A=y(()=>h(t.payment.publishableKey,O?{stripeAccount:O}:void 0).catch(()=>null),[t.payment.publishableKey,O,h]),[j,M]=S(!1);return g(()=>{let e=!0;return M(!1),A.then(t=>{e&&t===null&&M(!0)}),()=>{e=!1}},[A]),H(w,{options:{amount:Math.max(d.totalCents,100),appearance:{rules:{".Input:focus":{borderColor:e,boxShadow:`0 0 0 1px ${e}`,outline:`none`}},theme:_===`light`?`stripe`:`night`,variables:{borderRadius:v?.[`--lockerverse-radius`]??`10px`,colorBackground:v?.[`--lockerverse-control`]??(_===`light`?`#f5f6f7`:`#121212`),colorDanger:v?.[`--lockerverse-danger`]??(_===`light`?`#c52b3e`:`#f08a98`),colorPrimary:e,colorText:v?.[`--lockerverse-text`]??(_===`light`?`#121416`:`#ffffff`),colorTextPlaceholder:v?.[`--lockerverse-placeholder`]??(_===`light`?`#72767d`:`#6b6b6b`),colorTextSecondary:v?.[`--lockerverse-muted`]??(_===`light`?`#62666d`:`#a1a1aa`),focusBoxShadow:`none`,focusOutline:`none`,fontFamily:i,fontSizeBase:`16px`}},currency:t.payment.currency,excludedPaymentMethodTypes:[`us_bank_account`],mode:k===`one-time`?`payment`:`subscription`,syncAddressCheckbox:`none`},stripe:A,children:H(lt,{catalog:t,checkoutItems:n,client:r,metadata:a,onPaymentComplete:o,onPaymentRecoveryChange:c,onPaymentUncertain:l,onQuoteChange:u,onResumePaymentFailed:s,onStateChange:p,quote:d,resumePayment:f,stripeConnectedAccountId:O,stripeLoadFailed:j,updateWorkflow:ee,workflowState:b})},`${t.payment.publishableKey}:${O??`platform`}:${k}`)}function $e({label:e}){return U(`div`,{className:`lockerverse-payment__stripe-loader`,role:`status`,children:[H(`p`,{children:e}),U(`div`,{"aria-hidden":`true`,children:[H(`span`,{}),H(`span`,{}),H(`span`,{})]})]})}function et({onError:e,onReady:t,ready:n}){return U(`div`,{className:`lockerverse-payment__stripe-element`,"data-ready":n,children:[n?null:H($e,{label:`Loading payment form...`}),H(`div`,{className:`lockerverse-payment__stripe-mount`,children:H(T,{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:`never`},wallets:{applePay:`auto`,googlePay:`never`}}})})]})}function tt({label:e,mode:t,onChange:n,onError:r,onReady:i,ready:a}){return U(`div`,{className:`lockerverse-payment__address`,children:[H(`h2`,{children:e}),U(`div`,{className:`lockerverse-payment__stripe-element lockerverse-payment__stripe-element--address`,"data-ready":a,children:[a?null:H($e,{label:`Loading ${e.toLowerCase()}...`}),H(`div`,{className:`lockerverse-payment__stripe-mount`,children:H(C,{onChange:n,onLoadError:({error:t})=>r(t.message??`${e} failed to load.`),onReady:i,options:{autocomplete:{mode:`automatic`},mode:t}})})]})]})}function nt({message:e}){return e?H(`p`,{className:`lockerverse-payment__field-message`,role:`alert`,children:e}):null}function rt({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 U(te,{children:[f?H(et,{onError:c,onReady:()=>u(!0),ready:i}):null,f||e.widget.fields.shipping?H(tt,{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?U(`div`,{className:`lockerverse-payment__shipping`,children:[H(J,{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:H(tt,{label:`Shipping address`,mode:`shipping`,onChange:e=>o(`shipping`,e),onError:c,onReady:()=>d(!0),ready:a})]}):null]})}function it({displayedBaseCents:e,displayedTipCents:t,displayedTotalCents:n,quote:r}){let i=Je(r.paymentOption),a=Math.max(0,e-r.subtotalCents+r.discountCents);return U(`section`,{"aria-label":`Payment summary`,className:`lockerverse-payment__payment-summary`,children:[H(`h2`,{children:`Order summary`}),H(`div`,{className:`lockerverse-payment__payment-summary-items`,children:r.lineItems.map(e=>U(`div`,{className:`lockerverse-payment__payment-summary-row`,children:[U(`span`,{children:[e.productName,e.quantity>1?U(te,{children:[` `,U(`small`,{children:[`× `,e.quantity]})]}):null,e.paymentOption===`monthly`?H(`small`,{children:` · Monthly`}):null,e.paymentOption===`annually`?H(`small`,{children:` · Annual`}):null]}),H(`strong`,{children:$(e.subtotalCents)})]},e.listingId))}),U(`div`,{className:`lockerverse-payment__payment-summary-totals`,children:[a>0?U(`div`,{className:`lockerverse-payment__payment-summary-row lockerverse-payment__payment-summary-detail`,children:[H(`span`,{children:`Service fee`}),H(`strong`,{children:$(a)})]}):null,r.discountCents>0&&r.appliedDiscount?U(`div`,{className:`lockerverse-payment__payment-summary-row lockerverse-payment__payment-summary-discount`,children:[U(`span`,{children:[r.appliedDiscount.source===`email_list`?`Email discount`:`Promo code discount`,` `,`(`,r.appliedDiscount.percentageOff,`% off)`]}),U(`strong`,{children:[`-`,$(r.discountCents)]})]}):null,t>0?U(`div`,{className:`lockerverse-payment__payment-summary-row lockerverse-payment__payment-summary-detail lockerverse-payment__payment-summary-tip`,children:[H(`span`,{children:`Tip`}),H(`strong`,{children:$(t)})]}):null,U(`div`,{className:`lockerverse-payment__payment-summary-row lockerverse-payment__payment-summary-total`,children:[H(`span`,{children:i?`${i.label} total`:`Total`}),H(`strong`,{children:$(n)})]})]})]})}function at({catalog:e,displayedTotalCents:t,fieldValues:n,isBillingAddressReady:r,isPaymentReady:i,isRequiredShippingReady:a,isSubmitting:o,onFieldValuesChange:s,quote:c}){let l=t===0,u=l?!e.widget.fields.shipping||r&&a:i&&r&&a,d=Je(c.paymentOption),f=l?`Complete order`:`Pay ${$(t)}`;!l&&d&&(f=`Subscribe for ${$(t)}/${d.interval}`),o&&(f=l?`Completing…`:`Processing…`);let p=`Process payment for ${$(t)} total`;return l?p=`Complete order`:d&&(p=`Start ${d.label.toLowerCase()} subscription for ${$(t)}`),U(`div`,{className:`lockerverse-payment__actions`,children:[H(Y,{amountCents:c.serviceFeeCents||Math.round(c.subtotalCents*e.pricingPolicy.serviceFeeRateBasisPoints/1e4),enabled:e.widget.fields.serviceFee,onChange:s,values:n}),H(`button`,{"aria-busy":o,"aria-label":p,disabled:o||!u,type:`submit`,children:f})]})}function ot(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 st({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&&ot(n,`custom:${o}`)}function ct({email:e,emailDiscountPercentOff:t,emailErrorId:n,emailId:r,emailRef:i,errors:a,onEmailBlur:o,onEmailChange:s,onPhoneChange:c,onPhoneCountryChange:l,phone:u,phoneCountry:d,phoneEnabled:f,phoneErrorId:p,phoneId:m,phoneRef:h}){return U(`div`,{className:`lockerverse-payment__contact`,children:[H(`label`,{htmlFor:r,children:`Email`}),H(`input`,{"aria-describedby":a.email?n:void 0,"aria-invalid":a.email?`true`:void 0,autoComplete:`email`,id:r,name:`email`,onBlur:o,onChange:e=>s(e.currentTarget.value),placeholder:`name@example.com`,ref:i,type:`email`,value:e}),a.email?H(`p`,{className:`lockerverse-payment__field-message`,id:n,children:a.email}):null,t===void 0?null:U(`p`,{className:`lockerverse-payment__discount-message`,role:`status`,children:[`Your email qualifies for `,t,`% off.`]}),f?U(te,{children:[H(`label`,{htmlFor:m,children:`Phone`}),U(`div`,{className:`lockerverse-payment__phone-control`,children:[H(G,{ariaLabel:`Phone number country`,className:`lockerverse-payment__select--phone-country`,name:`phoneCountry`,onValueChange:l,options:Ye,value:d}),H(`input`,{"aria-describedby":a.phone?p:void 0,"aria-invalid":a.phone?`true`:void 0,autoComplete:`tel`,id:m,inputMode:`tel`,name:`phone`,onChange:e=>c(e.currentTarget.value),placeholder:`(201) 555-0123`,ref:h,type:`tel`,value:u})]}),a.phone?H(`p`,{className:`lockerverse-payment__field-message`,id:p,children:a.phone}):null]}):null]})}function lt({catalog:e,checkoutItems:t,client:r,metadata:i,onPaymentComplete:a,onResumePaymentFailed:o,onPaymentRecoveryChange:s,onPaymentUncertain:c,onQuoteChange:l,onStateChange:d,quote:f,resumePayment:p,stripeConnectedAccountId:m,stripeLoadFailed:h,updateWorkflow:v,workflowState:y}){let[b,C]=S(``),[w,T]=S(``),[D,O]=S(`US`),[k,A]=S({}),[j,M]=S({}),[N,P]=S(),[F,I]=S(!1),[L,R]=S(!1),[z,B]=S(!1),[V,te]=S({customFields:u(e.widget.customFields),customTip:``,includeServiceFee:e.widget.fields.serviceFee,memberId:``,merchSize:`M`,promoCode:``,shippingMatchesBilling:!0,tipPercent:`10`}),W=x({billing:null,shipping:null}),ne=x(null),re=x(null),ie=x(null),ae=x(f.totalCents>0),G=We({catalog:e,checkoutItems:t,client:r,elements:ee(),email:b,fieldValues:V,metadata:i,onPaymentComplete:a,onPaymentRecoveryChange:s,onPaymentUncertain:c,onQuoteChange:l,onResumePaymentFailed:o,onStateChange:d,quote:f,resumePayment:p,stripe:E(),stripeConnectedAccountId:m,stripeLoadFailed:h,updateWorkflow:v,workflow:y}),{displayedTotalCents:K,isRecovering:oe,isRefreshingQuote:q,isSubmitting:J,parsedTip:Y,paymentError:le,promoError:ue,terminalMessage:fe}=G.state,X=`lockerverse-${_()}`,pe=`${X}-email`,me=`${pe}-error`,he=`${X}-phone`,ge=`${he}-error`,_e=`${X}-tip-error`,ve=(Y.success?Y.cents:null)??0,ye=K-ve,be=!e.widget.fields.shipping||V.shippingMatchesBilling||z;g(()=>{J&&ie.current?.focus({preventScroll:!0})},[J]),g(()=>{let e=K>0;e&&!ae.current&&(I(!1),R(!1)),ae.current=e},[K]);function xe(e){G.commands.fieldChanged(!1,e!==`email`),A(t=>{let n={...t};return delete n[e],n})}function Se(e){let t=e.promoCode!==V.promoCode,n=e.includeServiceFee!==V.includeServiceFee;G.commands.fieldChanged(t,!(t||n)),te(e),M({}),P(void 0)}async function Ce(t){t.preventDefault();let r=de({email:b,phone:Xe(w,D)},e.widget.fields.phone),i=n(e.widget.customFields,V.customFields);if(!(r.value&&Y.success)||Object.keys(i).length>0){A(r.errors),M(i),P(Y.success?void 0:Y.message),G.commands.reportValidationFailure();let e=t.currentTarget;queueMicrotask(()=>{st({customFieldErrors:i,emailRef:ne,form:e,parsedTipSuccess:Y.success,phoneRef:re,validationErrors:r.errors})});return}A({}),M({}),await G.commands.submit({addresses:W.current,phone:Xe(w,D)})}return fe?H(`p`,{className:`lockerverse-payment__payment-status`,ref:ie,role:`status`,tabIndex:-1,children:fe}):oe?H(`p`,{className:`lockerverse-payment__payment-status`,role:`status`,children:`Recovering payment…`}):U(`form`,{"aria-busy":J,className:`lockerverse-payment__form`,noValidate:!0,onSubmit:Ce,children:[H(`div`,{"data-lockerverse-input-region":``,inert:J?!0:void 0,children:U(`fieldset`,{className:`lockerverse-payment__input-fieldset`,disabled:J,children:[H(it,{displayedBaseCents:ye,displayedTipCents:ve,displayedTotalCents:K,quote:f}),H(se,{enabled:e.widget.fields.tipping,error:N,errorId:_e,onChange:Se,values:V}),H(ct,{email:b,emailDiscountPercentOff:f.appliedDiscount?.source===`email_list`?f.appliedDiscount.percentageOff:void 0,emailErrorId:me,emailId:pe,emailRef:ne,errors:k,onEmailBlur:()=>G.commands.refreshAuthoritativeTotal(),onEmailChange:e=>{C(e),xe(`email`)},onPhoneChange:e=>{T(e),xe(`phone`)},onPhoneCountryChange:e=>{O(e),G.commands.fieldChanged(!1,!0)},phone:w,phoneCountry:D,phoneEnabled:e.widget.fields.phone,phoneErrorId:ge,phoneId:he,phoneRef:re}),H(rt,{catalog:e,displayedTotalCents:K,fieldValues:V,isBillingAddressReady:L,isPaymentReady:F,isShippingAddressReady:z,onAddressChange:(e,t)=>{W.current[e]=t},onFieldValuesChange:Se,onStripeLoadError:G.commands.reportStripeLoadError,setIsBillingAddressReady:R,setIsPaymentReady:I,setIsShippingAddressReady:B}),H(ce,{customFields:e.widget.customFields,errors:j,fields:e.widget.fields,idPrefix:X,isPromoApplying:q,onApplyPromo:G.commands.applyPromo,onChange:Se,promoError:ue,values:V}),H(at,{catalog:e,displayedTotalCents:K,fieldValues:V,isBillingAddressReady:L,isPaymentReady:F,isRequiredShippingReady:be,isSubmitting:J,onFieldValuesChange:Se,quote:f})]})}),J?H(`p`,{className:`lockerverse-payment__sr-only`,ref:ie,role:`status`,tabIndex:-1,children:K===0?`Completing order…`:`Processing payment…`}):null,H(nt,{message:le})]})}function ut(){return H(c,{fieldCount:2,label:`Loading payment…`,sectionCount:2,showCheckbox:!0})}function dt(e,t){switch(t.type){case`loading`:return{phase:`loading`,revision:e.revision};case`ready`:return ht(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 ft(e,t){return e===t}function pt({checkout:e}){return{displayedQuote:e,type:`ready`}}function mt(e){return e instanceof Error?e.message:`Lockerverse payment could not load.`}function ht(e,t){return{checkoutItems:[...e.items],displayedQuote:e,phase:`ready`,quoteFailure:void 0,revision:t}}function gt(e,t){let n=e.widget.fields.serviceFee;return f(e,{includeServiceFee:n,selection:t})}function _t(e,t){try{return ht(gt(e,t),1)}catch(e){return{failure:mt(e),phase:`error`,revision:0}}}function vt({catalog:e,client:t,paymentState:n,selection:r}){let i=ke(r),a=i.success?JSON.stringify(i.value):`invalid-selection`,o=y(()=>i.success?JSON.parse(a):[],[i.success,a]),[s,c]=b(dt,void 0,()=>i.success?_t(e,o):{phase:`loading`,revision:0}),l=x(void 0),u=x(0),d=x(s.phase===`ready`?a:void 0),f=x(s.phase===`error`?a:void 0);g(()=>{if(!i.success||n===`submitting`||n===`success`||n===`unresolved`||ft(f.current,a)||ft(l.current,a))return;let r=!0;l.current=a;let s=d.current===a;s||c({type:`loading`});function p(e){r&&c(e)}function m(){r&&(l.current=void 0,f.current=a)}let h;function g(e){if(!r||(l.current=void 0,f.current=a,s&&h!==void 0&&u.current!==h))return;let t=mt(e);c(s?{failure:t,type:`quote-error`}:{failure:t,type:`error`})}async function _(){try{h=u.current;let n=e.widget.fields.serviceFee;if(!s){let t=gt(e,o);s=!0,d.current=a,p(pt({checkout:t}))}m();let r=await t.calculateTotal({catalog:e,includeServiceFee:n,selection:o});u.current===h&&p({checkout:r,type:`checkout`})}catch(e){g(e)}}return _(),()=>{r=!1,ft(l.current,a)&&(l.current=void 0)}},[e,t,i.success,n,a,o]);let p=n===`submitting`||n===`success`||n===`unresolved`,m=ft(d.current,a)||ft(f.current,a)||ft(l.current,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`})}}}function yt({catalog:e,client:t,...n}){let{branding:i,className:a,metadata:o,onPaymentComplete:c,onPaymentRecoveryChange:l,onPaymentUncertain:u,resumePayment:d,selection:f,style:p,stripeLoader:h=Ke,theme:_=`dark`,...y}=n,[b,C]=S(d),w=x(null),[T,ee]=S(),[E,D]=S(`idle`),O=x(void 0),{selectionError:k,session:A,updateCheckout:j}=vt({catalog:e,client:t,paymentState:E,selection:f}),M=A.phase===`ready`?A.revision:void 0,N=m(e=>{M!==void 0&&(O.current=M),D(e)},[M]),P=m(e=>l?.(e),[l]),F=m(()=>{C(void 0)},[]);g(()=>{A.phase===`loading`&&ee(void 0)},[A.phase]),v(()=>{A.phase===`ready`&&O.current!==A.revision&&D(e=>e===`success`||e===`unresolved`?e:`idle`)},[A.phase,A.revision]);let I=[`lockerverse-payment`,a].filter(Boolean).join(` `),L=i??e.community,R=s(p?.[`--lockerverse-accent`]??L?.accentColor??`#38d77a`),z=r(R),B={...p,...p?.[`--lockerverse-accent`]!==void 0||L?.accentColor?{"--lockerverse-accent":R}:{},...z&&p?.[`--lockerverse-accent-contrast`]===void 0?{"--lockerverse-accent-contrast":z}:{}};return k?H(`section`,{...y,className:I,"data-lockerverse-theme":_,role:`alert`,style:B,children:k}):A.phase===`error`?H(`section`,{...y,className:I,"data-lockerverse-theme":_,style:B,children:H(`p`,{role:`alert`,children:A.failure})}):A.phase===`ready`?U(`section`,{...y,"aria-label":`Payment`,className:I,"data-lockerverse-theme":_,"data-payment-state":E,ref:w,style:B,children:[U(`header`,{children:[e.widget.showCommunityBranding&&L?U(`div`,{className:`lockerverse-payment__branding`,children:[L.imageUrl?H(`img`,{alt:L.name,height:`48`,src:L.imageUrl,width:`48`}):null,H(`strong`,{children:L.name})]}):null,H(`h1`,{children:e.widget.title??e.widget.name}),e.widget.description?H(`p`,{children:e.widget.description}):null]}),T?H(`p`,{className:`lockerverse-payment__payment-status`,role:`status`,children:T}):null,A.quoteFailure?U(`div`,{className:`lockerverse-payment__payment-status`,role:`alert`,children:[H(`span`,{children:A.quoteFailure}),H(`span`,{children:` The final total will be checked when you submit.`})]}):null,H(re,{container:w,children:H(Qe,{accentColor:R,catalog:e,checkoutItems:A.checkoutItems,client:t,fontFamily:p?.[`--lockerverse-font-family`]??`ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif`,metadata:o,onPaymentComplete:c,onPaymentRecoveryChange:P,onPaymentUncertain:u,onQuoteChange:(e,t)=>{ee(t),j(e)},onResumePaymentFailed:F,onStateChange:N,quote:A.displayedQuote,resumePayment:b,stripeLoader:h,theme:_,visualStyle:B},A.revision)})]}):H(`section`,{...y,"aria-busy":`true`,"aria-label":`Payment`,className:I,"data-lockerverse-theme":_,style:B,children:H(ut,{})})}function bt({children:e,loading:t=!1,viewProps:n}){let{branding:i,className:a,metadata:o,onPaymentComplete:c,onPaymentRecoveryChange:l,onPaymentUncertain:u,resumePayment:d,selection:f,stripeLoader:p,style:m,theme:h=`dark`,...g}=n,_=s(m?.[`--lockerverse-accent`]??i?.accentColor??`#38d77a`),v=r(_),y={...m,...m?.[`--lockerverse-accent`]!==void 0||i?.accentColor?{"--lockerverse-accent":_}:{},...v&&m?.[`--lockerverse-accent-contrast`]===void 0?{"--lockerverse-accent-contrast":v}:{}};return H(`section`,{...g,...t?{"aria-busy":!0,"aria-label":`Payment`}:{},className:[`lockerverse-payment`,a].filter(Boolean).join(` `),"data-lockerverse-theme":h,style:y,children:e})}function xt({widget:e,...t}){return e.error?U(bt,{viewProps:t,children:[H(`p`,{role:`alert`,children:e.error.message}),H(`button`,{onClick:e.refresh,type:`button`,children:`Retry`})]}):e.loading||!e.catalog?H(bt,{loading:!0,viewProps:t,children:H(ut,{})}):H(yt,{catalog:e.catalog,client:e.client,...t})}export{qe as n,xt as t};
|
|
1
|
+
import{a as e,c as t,d as n,f as r,l as i,n as a,o,p as s,s as c,t as l,u}from"./host-callback.js";import{LockerverseSdkError as d,estimateLockerverseCheckout as f}from"@lockerverse/sdk/checkout";import{createContext as p,useCallback as m,useContext as h,useEffect as g,useId as _,useLayoutEffect as v,useMemo as y,useReducer as b,useRef as x,useState as S}from"react";import{AddressElement as C,Elements as w,PaymentElement as T,useElements as E,useStripe as D}from"@stripe/react-stripe-js";import{loadStripe as O}from"@stripe/stripe-js/pure/index.js";import{array as k,minLength as A,minValue as j,nonEmpty as M,number as N,object as P,pipe as F,regex as I,safeInteger as L,safeParse as R,strictObject as z,string as B,trim as V,union as H}from"valibot";import{Fragment as ee,jsx as U,jsxs as W}from"react/jsx-runtime";import{Select as G}from"@base-ui/react/select";const te=new Intl.NumberFormat(`en-US`,{currency:`USD`,style:`currency`});function K(e){return te.format(e/100)}const ne=p(void 0);function re({children:e,container:t}){return U(ne.Provider,{value:t,children:e})}function q(){return U(`svg`,{"aria-hidden":`true`,fill:`none`,viewBox:`0 0 16 16`,children:U(`path`,{d:`m4 6 4 4 4-4`})})}function J(){return U(`svg`,{"aria-hidden":`true`,fill:`none`,viewBox:`0 0 16 16`,children:U(`path`,{d:`m3 8 3 3 7-7`})})}function ie({ariaDescribedBy:e,ariaLabel:t,ariaLabelledBy:n,className:r,id:i,invalid:a=!1,name:o,onValueChange:s,options:c,value:l}){let u=h(ne),d=[`lockerverse-payment__select`,r].filter(Boolean).join(` `);return U(`div`,{className:d,children:W(G.Root,{id:i,items:c,name:o,onValueChange:e=>{e!==null&&s(e)},value:l,children:[W(G.Trigger,{"aria-describedby":e,"aria-invalid":a||void 0,"aria-label":t,"aria-labelledby":n,className:`lockerverse-payment__select-trigger`,children:[U(G.Value,{}),U(G.Icon,{"aria-hidden":`true`,className:`lockerverse-payment__select-icon`,children:U(q,{})})]}),U(G.Portal,{container:u,children:U(G.Positioner,{alignItemWithTrigger:!1,className:`lockerverse-payment__select-positioner`,sideOffset:6,children:U(G.Popup,{className:`lockerverse-payment__select-popup`,children:U(G.List,{className:`lockerverse-payment__select-list`,children:c.map(e=>W(G.Item,{className:`lockerverse-payment__select-item`,value:e.value,children:[U(G.ItemText,{children:e.label}),U(G.ItemIndicator,{"aria-hidden":`true`,className:`lockerverse-payment__select-item-indicator`,children:U(J,{})})]},e.value))})})})})]})})}const ae=[`XS`,`S`,`M`,`L`,`XL`,`XXL`,`XXXL`],Y=[`15`,`12`,`10`,`5`],X=[...Y,`custom`];function oe({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=X.indexOf(t),r;switch(e.key){case`ArrowDown`:case`ArrowRight`:r=(n+1)%X.length;break;case`ArrowLeft`:case`ArrowUp`:r=(n-1+X.length)%X.length;break;case`Home`:r=0;break;case`End`:r=X.length-1;break;default:return}e.preventDefault();let i=X[r];i&&((e.currentTarget.closest(`[role="radiogroup"]`)?.querySelectorAll(`input[type="radio"]`))?.[r]?.focus(),a({tipPercent:i}))};return W(`div`,{className:`lockerverse-payment__tip-box`,children:[U(`p`,{children:`Add a tip to support the Lockerverse platform`}),W(`div`,{"aria-label":`Tip amount`,role:`radiogroup`,children:[Y.map(e=>W(`label`,{className:`lockerverse-payment__tip-choice`,children:[U(`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}),W(`span`,{children:[e,`%`]})]},e)),W(`label`,{className:`lockerverse-payment__tip-choice`,children:[U(`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`}),U(`span`,{children:`Other`})]})]}),i.tipPercent===`custom`?W(`label`,{children:[U(`span`,{children:`Custom tip`}),W(`span`,{className:`lockerverse-payment__money-input`,children:[U(`span`,{"aria-hidden":`true`,children:`$`}),U(`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?U(`span`,{className:`lockerverse-payment__field-message`,id:n,children:t}):null]}):U(`input`,{name:`tip`,type:`hidden`,value:i.tipPercent})]})}function se({checked:e,children:t,name:n,onChange:r}){return W(`label`,{className:`lockerverse-payment__check-row`,children:[U(`input`,{checked:e,name:n,onChange:e=>r(e.currentTarget.checked),type:`checkbox`}),U(`span`,{children:t})]})}function ce({customFields:e,errors:n,fields:r,idPrefix:i,isPromoApplying:a,onChange:o,onApplyPromo:s,promoError:c,values:l}){let u=e=>o({...l,...e});return W(`div`,{className:`lockerverse-payment__additional-fields`,children:[r.memberId?W(`label`,{children:[U(`span`,{children:`Member ID`}),U(`input`,{name:`memberId`,onChange:e=>u({memberId:e.currentTarget.value}),placeholder:`Optional`,value:l.memberId})]}):null,r.merchSize?W(`div`,{className:`lockerverse-payment__field`,children:[U(`span`,{id:`${i}-merch-size-label`,children:`Size`}),U(ie,{ariaLabelledBy:`${i}-merch-size-label`,name:`merchSize`,onValueChange:e=>{let t=ae.find(t=>t===e);t&&u({merchSize:t})},options:ae.map(e=>({label:e,value:e})),value:l.merchSize})]}):null,r.promoCode?W(`div`,{className:`lockerverse-payment__field`,children:[U(`span`,{id:`${i}-promo-code-label`,children:`Promo code`}),W(`div`,{className:`lockerverse-payment__promo-control`,children:[U(`input`,{"aria-describedby":c?`${i}-promo-code-error`:void 0,"aria-invalid":c?`true`:void 0,"aria-labelledby":`${i}-promo-code-label`,name:`promoCode`,onChange:e=>u({promoCode:e.currentTarget.value}),placeholder:`Optional`,value:l.promoCode}),U(`button`,{disabled:!l.promoCode.trim()||a,onClick:s,type:`button`,children:a?`Applying…`:`Apply`})]}),c?U(`p`,{className:`lockerverse-payment__field-message`,id:`${i}-promo-code-error`,role:`alert`,children:c}):null]}):null,U(t,{choiceClassName:`lockerverse-payment__check-row`,errorClassName:`lockerverse-payment__field-message`,errors:n,fields:e,idPrefix:i,onChange:e=>u({customFields:e}),values:l.customFields})]})}function le({amountCents:e,enabled:t,onChange:n,values:r}){return t?W(se,{checked:r.includeServiceFee,name:`includeServiceFee`,onChange:e=>n({...r,includeServiceFee:e}),children:[`Add `,K(e),` to help cover processing fees`]}):null}function ue(e){return{error:void 0,message:void 0,status:e?`recovering`:`editing`}}function Z(e,t,n){return t.includes(e.status)?{...e,...n}:e}function de(e,t){if(e.status===`succeeded`||e.status===`unresolved`)return e;switch(t.type){case`field_changed`:return Z(e,[`editing`,`invalid`,`refreshing_quote`],{error:void 0,status:`editing`});case`validation_failed`:return Z(e,[`editing`],{status:`invalid`});case`quote_refresh_started`:return Z(e,[`editing`,`invalid`],{status:`refreshing_quote`});case`quote_refresh_succeeded`:return Z(e,[`refreshing_quote`],{error:void 0,status:`editing`});case`quote_refresh_failed`:return Z(e,[`refreshing_quote`],{error:t.error??e.error,status:`editing`});case`submission_started`:return Z(e,[`editing`,`invalid`,`refreshing_quote`],{error:void 0,status:`submitting`});case`quote_changed`:return Z(e,[`submitting`],{status:`editing`});case`retryable_failure`:return Z(e,[`editing`,`invalid`,`submitting`],{error:t.error,status:`editing`});case`recovery_failed`:return Z(e,[`recovering`],{error:t.error,status:`editing`});case`succeeded`:return Z(e,[`recovering`,`submitting`],{message:t.message,status:`succeeded`});case`unresolved`:return Z(e,[`recovering`,`submitting`],{message:t.message,status:`unresolved`});default:return e}}function fe(e){return e.status===`editing`||e.status===`invalid`||e.status===`refreshing_quote`?e.error:void 0}function pe(e){return e.status===`succeeded`?`success`:e.status===`unresolved`?`unresolved`:e.status===`submitting`||e.status===`recovering`?`submitting`:e.status===`invalid`?`invalid`:fe(e)?`error`:`idle`}function me(e){return e.status===`submitting`}function he(e){return a(e)}function ge(t,n){let r=n?{...t,phone:he(t.phone)}:t,i=P(n?{email:e,phone:o}:{email:e}),a=R(i,r);if(a.success)return{errors:{},value:a.output};let s={};for(let e of a.issues){let t=e.path?.[0]?.key;(t===`email`||t===`phone`)&&!s[t]&&(s[t]=e.message)}return{errors:s,value:null}}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){return e.checkoutStatus===`success`?{kind:`success`,payment:e}:e.checkoutStatus===`failed`?{kind:`failed`,payment:e}:{kind:`unresolved`,paymentReference:e.paymentReference,reason:e.checkoutStatus===`action_required`?`action_required`:`pending`}}async function Q(e,t,n){if(t.checkoutStatus!==`action_required`)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 xe(e,t,n){let r;try{r=await e.submitPayment(t)}catch(n){if(!(n instanceof d&&n.recoveryRecommended))throw n;try{r=await e.getPaymentStatus(t.checkout.paymentReference)}catch{return{kind:`unresolved`,paymentReference:t.checkout.paymentReference,reason:`recovery_failed`}}}return Q(e,r,n)}async function Se(e,t,n){try{return Q(e,await e.getPaymentStatus(t),n)}catch{return{kind:`unresolved`,paymentReference:t,reason:`recovery_failed`}}}const Ce=F(B(),V(),M()),we=F(N(),L(),j(1)),Te=F(k(H([z({amountCents:we,productSlug:Ce}),z({productSlug:Ce,quantity:we}),z({productSlug:Ce})])),A(1)),Ee=F(B(),V(),I(/^(?:0|[1-9]\d*)(?:\.\d{1,2})?$/,`Enter a valid tip amount.`));function De(e){let t=R(Ee,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 Oe(e){let t=R(Te,e);return t.success?{success:!0,value:t.output}:{message:`Lockerverse payment configuration is invalid.`,success:!1}}const ke=`This promo code is invalid or cannot be applied.`;function Ae(e,t){return t.tipPercent===`custom`?t.customTip.trim()?De(t.customTip):{cents:0,success:!0}:{cents:Math.round(e*Number(t.tipPercent)/100),success:!0}}function je(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 Me(e,t,n){let r=e.widget.fields.tipping?Ae(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 Ne(e,t){return{displayedTotalCents:e.totalCents,promoError:t&&e.appliedDiscount?.source!==`promo_code`?ke:void 0}}function Pe(e,t){let n;return t||(n=e instanceof Error?e.message:`The order total could not be updated.`),{paymentError:n,promoError:t?ke:void 0}}function Fe(e,t){if(!e?.complete)throw Error(`${t} address is required.`);return e.value}function Ie(e,t,n,r){if(e.widget.fields.shipping)return t.shippingMatchesBilling?n:Fe(r.shipping,`Shipping`)}function Le({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 Re({catalog:e,confirmationToken:t,email:n,fieldValues:r,metadata:a,phone:o,shippingAddress:s}){let c={customFieldAnswers:i(e.widget.customFields,r.customFields),email:n};if(t&&(c.confirmationToken=t),a&&(c.metadata=a),e.widget.fields.memberId&&r.memberId.trim()&&(c.memberId=r.memberId.trim()),e.widget.fields.merchSize&&(c.merchSize=r.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 ze(e){if(!e())throw Error(`Payment component is no longer active.`)}function Be(e,t){l(e,t)}function Ve(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}:{email:n,kind:`payment`,payment:e.payment,quote:t}}async function He({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=he(d),_=Ae(f.subtotalCents,o);if(!_.success)throw Error(_.message);let v=await r.calculateTotal({...je(t,o,h,_.cents),catalog:t,items:n});if(ze(s),v.totalCents>0&&ye(f,v,c,m))return{kind:`quote_changed`,quote:v};let y,b;if(v.totalCents===0)t.widget.fields.shipping&&(y=Ie(t,o,Fe(e.billing,`Billing`),e));else{if(!(i&&p))throw Error(`Payment form is still loading.`);await i.update({amount:v.totalCents}),ze(s);let n=await i.submit();if(ze(s),n.error)throw Error(n.error.message);let r=Fe(e.billing,`Billing`);y=Ie(t,o,r,e);let a=await p.createConfirmationToken({elements:i,params:Le({billingAddress:r,catalog:t,email:h,phone:g,shippingAddress:y})});if(ze(s),a.error)throw Error(a.error.message);b=a.confirmationToken.id}Be(u,{connectedAccountId:v.payment.connectedAccountId,paymentReference:v.paymentReference});let x=await xe(r,{checkout:v,submission:Re({catalog:t,confirmationToken:b,email:h,fieldValues:o,metadata:l,phone:g,shippingAddress:y})},p);return ze(s),Ve(x,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 Ue(e,t){l(e,t)}function We(e,t){l(e,t)}function Ge(e,t){return{...e,...t}}function Ke(e,t,n){return e.kind===`unresolved`&&e.reason===`action_required`&&!t&&!n}function qe({nextQuote:e,onQuoteChange:t,setDisplayedTotalCents:n,setPromoError:r,updateState:i,validatePromo:a}){let o=Ne(e,a);i({type:`quote_refresh_succeeded`}),n(o.displayedTotalCents),t(e),a&&r(o.promoError)}function Je({error:e,setPromoError:t,updateState:n,validatePromo:r}){let i=Pe(e,r);r&&t(i.promoError),n(i.paymentError===void 0?{type:`quote_refresh_failed`}:{error:i.paymentError,type:`quote_refresh_failed`})}function Ye({onPaymentComplete:e,onPaymentRecoveryChange:t,onPaymentUncertain:n,onQuoteChange:r,result:i,setDisplayedTotalCents:a,dispatchState:o}){if(i.kind===`quote_changed`){let e=`The total changed to ${K(i.quote.totalCents)}. Review it and pay again.`;r(i.quote,e),a(i.quote.totalCents),o({type:`quote_changed`});return}if(i.kind===`payment_failed`){Ue(t,null),o({error:i.message,type:`retryable_failure`});return}if(i.kind===`payment_unresolved`){o({message:`Payment is still processing. Do not submit it again.`,type:`unresolved`}),We(n,{paymentReference:i.paymentReference,reason:i.reason});return}r(i.quote),Ue(t,null),o({message:i.payment.paymentRequired?`Payment completed successfully.`:`Order confirmed. No payment was required.`,type:`succeeded`}),l(e,Ge(i.payment,{email:i.email,lineItems:i.quote.lineItems}))}function Xe(e){let{catalog:t,checkoutItems:n,client:r,elements:i,email:a,fieldValues:o,metadata:s,onPaymentComplete:c,onResumePaymentFailed:u,onPaymentRecoveryChange:d,onPaymentUncertain:f,onQuoteChange:p,onStateChange:h,quote:_,resumePayment:v,stripe:y,stripeConnectedAccountId:b,stripeLoadFailed:C,paymentState:w,updateState:T}=e,[E,D]=S(_.totalCents),[O,k]=S(),A=x(!1),j=x(0),M=x(0),N=m(e=>T(e,!0),[T]),P=m(()=>{let e=M.current+1;return M.current=e,()=>M.current===e},[]);g(()=>()=>{M.current+=1,j.current+=1},[]);let{parsedTip:F,totalCents:I}=Me(t,o,_);g(()=>{I!==null&&(D(I),I>0&&i?.update({amount:I}))},[t.pricingPolicy.serviceFeeRateBasisPoints,t.widget.fields.serviceFee,i,o.includeServiceFee,I,_.serviceFeeCents,_.tipCents,_.totalCents,_.subtotalCents]),g(()=>{if(!v||A.current||w.status!==`recovering`)return;A.current=!0;let e=P();return h(pe(w)),Se(r,v.paymentReference,y).then(t=>{if(e()&&!Ke(t,y,C)){if(t.kind===`failed`){Ue(d,null),u(),N({error:`The previous payment failed. Check your details and try again.`,type:`recovery_failed`});return}if(t.kind===`unresolved`){N({message:`Payment is still processing. Do not submit it again.`,type:`unresolved`}),We(f,{paymentReference:t.paymentReference,reason:t.reason});return}Ue(d,null),N({message:t.payment.paymentRequired?`Payment completed successfully.`:`Order confirmed. No payment was required.`,type:`succeeded`}),l(c,Ge(t.payment,{email:null,lineItems:null}))}}),()=>{e()&&(M.current+=1),A.current=!1}},[r,c,u,d,f,h,v,y,C,P,N,w]);let L=m((e=!1,t=!1)=>{t||(j.current+=1),e&&k(void 0),T({type:`field_changed`})},[T]);async function R(e=!1,i=!1){let s=ge({email:a.trim().toLowerCase(),phone:``},!1);if(!(F.success&&(s.value||e)))return;j.current+=1;let c=j.current;T({type:`quote_refresh_started`});try{let e=await r.calculateTotal({...je(t,o,s.value?.email??``,F.cents),catalog:t,items:n});if(c!==j.current)return;qe({nextQuote:e,onQuoteChange:p,setDisplayedTotalCents:D,setPromoError:k,updateState:T,validatePromo:i})}catch(e){if(c!==j.current)return;Je({error:e,setPromoError:k,updateState:T,validatePromo:i})}}async function z(){k(void 0),await R(!0,!0)}async function B({addresses:e,phone:l}){N({type:`submission_started`});let u=P();try{let m=await He({addresses:e,catalog:t,checkoutItems:n,client:r,elements:i,email:a,fieldValues:o,isAttemptActive:u,locallyPreviewedTotalCents:E,metadata:s,onPaymentRecoveryChange:d,phone:l,quote:_,stripe:y,stripeConnectedAccountId:b});if(!u())return;Ye({dispatchState:N,onPaymentComplete:c,onPaymentRecoveryChange:d,onPaymentUncertain:f,onQuoteChange:p,result:m,setDisplayedTotalCents:D})}catch(e){if(!u())return;Ue(d,null),N({error:e instanceof Error?e.message:`Payment could not be completed.`,type:`retryable_failure`})}}let V=w.status===`succeeded`||w.status===`unresolved`?w.message:void 0;return{commands:{applyPromo:z,fieldChanged:L,refreshAuthoritativeTotal:R,reportStripeLoadError:e=>N({error:e,type:`retryable_failure`}),reportValidationFailure:()=>N({type:`validation_failed`}),submit:B},state:{displayedTotalCents:E,isRecovering:w.status===`recovering`,isRefreshingQuote:w.status===`refreshing_quote`,isSubmitting:me(w),parsedTip:F,paymentError:fe(w),promoError:O,terminalMessage:V}}}const Ze=new Map,Qe=(e,t)=>{let n=t?.stripeAccount??null,r=Ze.get(e);r||(r=new Map,Ze.set(e,r));let i=r.get(n);if(i)return i;let a=O(e,t).catch(()=>(r?.get(n)===a&&(r.delete(n),r.size===0&&Ze.delete(e)),null));return r.set(n,a),a};function $e(e){let{connectedAccountId:t,publishableKey:n}=e.payment;return Qe(n,t?{stripeAccount:t}:void 0)}function et(e){return e===`monthly`?{interval:`month`,label:`Monthly`}:e===`annually`?{interval:`year`,label:`Annual`}:null}const tt=[{callingCode:`+1`,label:`🇺🇸 +1`,value:`US`},{callingCode:`+52`,label:`🇲🇽 +52`,value:`MX`},{callingCode:`+380`,label:`🇺🇦 +380`,value:`UA`},{callingCode:`+48`,label:`🇵🇱 +48`,value:`PL`},{callingCode:`+1`,label:`🇨🇦 +1`,value:`CA`},{callingCode:`+49`,label:`🇩🇪 +49`,value:`DE`},{callingCode:`+44`,label:`🇬🇧 +44`,value:`GB`},{callingCode:`+46`,label:`🇸🇪 +46`,value:`SE`},{callingCode:`+358`,label:`🇫🇮 +358`,value:`FI`},{callingCode:`+1`,label:`🇵🇷 +1`,value:`PR`}];function nt(e,t){return e.trim().startsWith(`+`)?e:`${tt.find(e=>e.value===t)?.callingCode??`+1`}${e}`}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,fontFamily:i,metadata:a,onPaymentComplete:o,onResumePaymentFailed:s,onPaymentRecoveryChange:c,onPaymentUncertain:l,onQuoteChange:u,quote:d,resumePayment:f,onStateChange:p,stripeLoader:h,theme:_,visualStyle:v}){let[b,C]=S(()=>ue(!!f)),T=x(b);T.current=b;let E=m((e,t=!1)=>{let n=de(T.current,e);n!==T.current&&(T.current=n,C(n),t&&p(pe(n)))},[p]),D=rt(t,d,f),O=x({connectedAccountId:D,paymentOption:d.paymentOption});b.status!==`submitting`&&b.status!==`recovering`&&(O.current={connectedAccountId:D,paymentOption:d.paymentOption});let{connectedAccountId:k,paymentOption:A}=O.current,j=y(()=>h(t.payment.publishableKey,k?{stripeAccount:k}:void 0).catch(()=>null),[t.payment.publishableKey,k,h]),[M,N]=S(!1);return g(()=>{let e=!0;return N(!1),j.then(t=>{e&&t===null&&N(!0)}),()=>{e=!1}},[j]),U(w,{options:{amount:Math.max(d.totalCents,100),appearance:{rules:{".Input:focus":{borderColor:e,boxShadow:`0 0 0 1px ${e}`,outline:`none`}},theme:_===`light`?`stripe`:`night`,variables:{borderRadius:v?.[`--lockerverse-radius`]??`10px`,colorBackground:v?.[`--lockerverse-control`]??(_===`light`?`#f5f6f7`:`#121212`),colorDanger:v?.[`--lockerverse-danger`]??(_===`light`?`#c52b3e`:`#f08a98`),colorPrimary:e,colorText:v?.[`--lockerverse-text`]??(_===`light`?`#121416`:`#ffffff`),colorTextPlaceholder:v?.[`--lockerverse-placeholder`]??(_===`light`?`#72767d`:`#6b6b6b`),colorTextSecondary:v?.[`--lockerverse-muted`]??(_===`light`?`#62666d`:`#a1a1aa`),focusBoxShadow:`none`,focusOutline:`none`,fontFamily:i,fontSizeBase:`16px`}},currency:t.payment.currency,excludedPaymentMethodTypes:[`us_bank_account`],mode:A===`one-time`?`payment`:`subscription`,syncAddressCheckbox:`none`},stripe:j,children:U(ht,{catalog:t,checkoutItems:n,client:r,metadata:a,onPaymentComplete:o,onPaymentRecoveryChange:c,onPaymentUncertain:l,onQuoteChange:u,onResumePaymentFailed:s,onStateChange:p,paymentState:b,quote:d,resumePayment:f,stripeConnectedAccountId:k,stripeLoadFailed:M,updateState:E})},`${t.payment.publishableKey}:${k??`platform`}:${A}`)}function at({label:e}){return W(`div`,{className:`lockerverse-payment__stripe-loader`,role:`status`,children:[U(`p`,{children:e}),W(`div`,{"aria-hidden":`true`,children:[U(`span`,{}),U(`span`,{}),U(`span`,{})]})]})}function ot({onError:e,onReady:t,ready:n}){return W(`div`,{className:`lockerverse-payment__stripe-element`,"data-ready":n,children:[n?null:U(at,{label:`Loading payment form...`}),U(`div`,{className:`lockerverse-payment__stripe-mount`,children:U(T,{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:`never`},wallets:{applePay:`auto`,googlePay:`never`}}})})]})}function st({label:e,mode:t,onChange:n,onError:r,onReady:i,ready:a}){return W(`div`,{className:`lockerverse-payment__address`,children:[U(`h2`,{children:e}),W(`div`,{className:`lockerverse-payment__stripe-element lockerverse-payment__stripe-element--address`,"data-ready":a,children:[a?null:U(at,{label:`Loading ${e.toLowerCase()}...`}),U(`div`,{className:`lockerverse-payment__stripe-mount`,children:U(C,{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?U(`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 W(ee,{children:[f?U(ot,{onError:c,onReady:()=>u(!0),ready:i}):null,f||e.widget.fields.shipping?U(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?W(`div`,{className:`lockerverse-payment__shipping`,children:[U(se,{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:U(st,{label:`Shipping address`,mode:`shipping`,onChange:e=>o(`shipping`,e),onError:c,onReady:()=>d(!0),ready:a})]}):null]})}function ut({displayedBaseCents:e,displayedTipCents:t,displayedTotalCents:n,quote:r}){let i=et(r.paymentOption),a=Math.max(0,e-r.subtotalCents+r.discountCents);return W(`section`,{"aria-label":`Payment summary`,className:`lockerverse-payment__payment-summary`,children:[U(`h2`,{children:`Order summary`}),U(`div`,{className:`lockerverse-payment__payment-summary-items`,children:r.lineItems.map(e=>W(`div`,{className:`lockerverse-payment__payment-summary-row`,children:[W(`span`,{children:[e.productName,e.quantity>1?W(ee,{children:[` `,W(`small`,{children:[`× `,e.quantity]})]}):null,e.paymentOption===`monthly`?U(`small`,{children:` · Monthly`}):null,e.paymentOption===`annually`?U(`small`,{children:` · Annual`}):null]}),U(`strong`,{children:K(e.subtotalCents)})]},e.listingId))}),W(`div`,{className:`lockerverse-payment__payment-summary-totals`,children:[a>0?W(`div`,{className:`lockerverse-payment__payment-summary-row lockerverse-payment__payment-summary-detail`,children:[U(`span`,{children:`Service fee`}),U(`strong`,{children:K(a)})]}):null,r.discountCents>0&&r.appliedDiscount?W(`div`,{className:`lockerverse-payment__payment-summary-row lockerverse-payment__payment-summary-discount`,children:[W(`span`,{children:[r.appliedDiscount.source===`email_list`?`Email discount`:`Promo code discount`,` `,`(`,r.appliedDiscount.percentageOff,`% off)`]}),W(`strong`,{children:[`-`,K(r.discountCents)]})]}):null,t>0?W(`div`,{className:`lockerverse-payment__payment-summary-row lockerverse-payment__payment-summary-detail lockerverse-payment__payment-summary-tip`,children:[U(`span`,{children:`Tip`}),U(`strong`,{children:K(t)})]}):null,W(`div`,{className:`lockerverse-payment__payment-summary-row lockerverse-payment__payment-summary-total`,children:[U(`span`,{children:i?`${i.label} total`:`Total`}),U(`strong`,{children:K(n)})]})]})]})}function dt({catalog:e,displayedTotalCents:t,fieldValues:n,isBillingAddressReady:r,isPaymentReady:i,isRequiredShippingReady:a,isSubmitting:o,onFieldValuesChange:s,quote:c}){let l=t===0,u=l?!e.widget.fields.shipping||r&&a:i&&r&&a,d=et(c.paymentOption),f=l?`Complete order`:`Pay ${K(t)}`;!l&&d&&(f=`Subscribe for ${K(t)}/${d.interval}`),o&&(f=l?`Completing…`:`Processing…`);let p=`Process payment for ${K(t)} total`;return l?p=`Complete order`:d&&(p=`Start ${d.label.toLowerCase()} subscription for ${K(t)}`),W(`div`,{className:`lockerverse-payment__actions`,children:[U(le,{amountCents:c.serviceFeeCents||Math.round(c.subtotalCents*e.pricingPolicy.serviceFeeRateBasisPoints/1e4),enabled:e.widget.fields.serviceFee,onChange:s,values:n}),U(`button`,{"aria-busy":o,"aria-label":p,disabled:o||!u,type:`submit`,children:f})]})}function ft(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 pt({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&&ft(n,`custom:${o}`)}function mt({email:e,emailDiscountPercentOff:t,emailErrorId:n,emailId:r,emailRef:i,errors:a,onEmailBlur:o,onEmailChange:s,onPhoneChange:c,onPhoneCountryChange:l,phone:u,phoneCountry:d,phoneEnabled:f,phoneErrorId:p,phoneId:m,phoneRef:h}){return W(`div`,{className:`lockerverse-payment__contact`,children:[U(`label`,{htmlFor:r,children:`Email`}),U(`input`,{"aria-describedby":a.email?n:void 0,"aria-invalid":a.email?`true`:void 0,autoComplete:`email`,id:r,name:`email`,onBlur:o,onChange:e=>s(e.currentTarget.value),placeholder:`name@example.com`,ref:i,type:`email`,value:e}),a.email?U(`p`,{className:`lockerverse-payment__field-message`,id:n,children:a.email}):null,t===void 0?null:W(`p`,{className:`lockerverse-payment__discount-message`,role:`status`,children:[`Your email qualifies for `,t,`% off.`]}),f?W(ee,{children:[U(`label`,{htmlFor:m,children:`Phone`}),W(`div`,{className:`lockerverse-payment__phone-control`,children:[U(ie,{ariaLabel:`Phone number country`,className:`lockerverse-payment__select--phone-country`,name:`phoneCountry`,onValueChange:l,options:tt,value:d}),U(`input`,{"aria-describedby":a.phone?p:void 0,"aria-invalid":a.phone?`true`:void 0,autoComplete:`tel`,id:m,inputMode:`tel`,name:`phone`,onChange:e=>c(e.currentTarget.value),placeholder:`(201) 555-0123`,ref:h,type:`tel`,value:u})]}),a.phone?U(`p`,{className:`lockerverse-payment__field-message`,id:p,children:a.phone}):null]}):null]})}function ht({catalog:e,checkoutItems:t,client:r,metadata:i,onPaymentComplete:a,onResumePaymentFailed:o,onPaymentRecoveryChange:s,onPaymentUncertain:c,onQuoteChange:l,onStateChange:d,quote:f,resumePayment:p,stripeConnectedAccountId:m,stripeLoadFailed:h,paymentState:v,updateState:y}){let[b,C]=S(``),[w,T]=S(``),[O,k]=S(`US`),[A,j]=S({}),[M,N]=S({}),[P,F]=S(),[I,L]=S(!1),[R,z]=S(!1),[B,V]=S(!1),[H,ee]=S({customFields:u(e.widget.customFields),customTip:``,includeServiceFee:e.widget.fields.serviceFee,memberId:``,merchSize:`M`,promoCode:``,shippingMatchesBilling:!0,tipPercent:`10`}),G=x({billing:null,shipping:null}),te=x(null),K=x(null),ne=x(null),re=x(f.totalCents>0),q=Xe({catalog:e,checkoutItems:t,client:r,elements:E(),email:b,fieldValues:H,metadata:i,onPaymentComplete:a,onPaymentRecoveryChange:s,onPaymentUncertain:c,onQuoteChange:l,onResumePaymentFailed:o,onStateChange:d,paymentState:v,quote:f,resumePayment:p,stripe:D(),stripeConnectedAccountId:m,stripeLoadFailed:h,updateState:y}),{displayedTotalCents:J,isRecovering:ie,isRefreshingQuote:ae,isSubmitting:Y,parsedTip:X,paymentError:se,promoError:le,terminalMessage:ue}=q.state,Z=`lockerverse-${_()}`,de=`${Z}-email`,fe=`${de}-error`,pe=`${Z}-phone`,me=`${pe}-error`,he=`${Z}-tip-error`,_e=(X.success?X.cents:null)??0,ve=J-_e,ye=!e.widget.fields.shipping||H.shippingMatchesBilling||B;g(()=>{Y&&ne.current?.focus({preventScroll:!0})},[Y]),g(()=>{let e=J>0;e&&!re.current&&(L(!1),z(!1)),re.current=e},[J]);function be(e){q.commands.fieldChanged(!1,e!==`email`),j(t=>{let n={...t};return delete n[e],n})}function Q(e){let t=e.promoCode!==H.promoCode,n=e.includeServiceFee!==H.includeServiceFee;q.commands.fieldChanged(t,!(t||n)),ee(e),N({}),F(void 0)}async function xe(t){t.preventDefault();let r=ge({email:b,phone:nt(w,O)},e.widget.fields.phone),i=n(e.widget.customFields,H.customFields);if(!(r.value&&X.success)||Object.keys(i).length>0){j(r.errors),N(i),F(X.success?void 0:X.message),q.commands.reportValidationFailure();let e=t.currentTarget;queueMicrotask(()=>{pt({customFieldErrors:i,emailRef:te,form:e,parsedTipSuccess:X.success,phoneRef:K,validationErrors:r.errors})});return}j({}),N({}),await q.commands.submit({addresses:G.current,phone:nt(w,O)})}return ue?U(`p`,{className:`lockerverse-payment__payment-status`,ref:ne,role:`status`,tabIndex:-1,children:ue}):ie?U(`p`,{className:`lockerverse-payment__payment-status`,role:`status`,children:`Recovering payment…`}):W(`form`,{"aria-busy":Y,className:`lockerverse-payment__form`,noValidate:!0,onSubmit:xe,children:[U(`div`,{"data-lockerverse-input-region":``,inert:Y?!0:void 0,children:W(`fieldset`,{className:`lockerverse-payment__input-fieldset`,disabled:Y,children:[U(ut,{displayedBaseCents:ve,displayedTipCents:_e,displayedTotalCents:J,quote:f}),U(oe,{enabled:e.widget.fields.tipping,error:P,errorId:he,onChange:Q,values:H}),U(mt,{email:b,emailDiscountPercentOff:f.appliedDiscount?.source===`email_list`?f.appliedDiscount.percentageOff:void 0,emailErrorId:fe,emailId:de,emailRef:te,errors:A,onEmailBlur:()=>q.commands.refreshAuthoritativeTotal(),onEmailChange:e=>{C(e),be(`email`)},onPhoneChange:e=>{T(e),be(`phone`)},onPhoneCountryChange:e=>{k(e),q.commands.fieldChanged(!1,!0)},phone:w,phoneCountry:O,phoneEnabled:e.widget.fields.phone,phoneErrorId:me,phoneId:pe,phoneRef:K}),U(lt,{catalog:e,displayedTotalCents:J,fieldValues:H,isBillingAddressReady:R,isPaymentReady:I,isShippingAddressReady:B,onAddressChange:(e,t)=>{G.current[e]=t},onFieldValuesChange:Q,onStripeLoadError:q.commands.reportStripeLoadError,setIsBillingAddressReady:z,setIsPaymentReady:L,setIsShippingAddressReady:V}),U(ce,{customFields:e.widget.customFields,errors:M,fields:e.widget.fields,idPrefix:Z,isPromoApplying:ae,onApplyPromo:q.commands.applyPromo,onChange:Q,promoError:le,values:H}),U(dt,{catalog:e,displayedTotalCents:J,fieldValues:H,isBillingAddressReady:R,isPaymentReady:I,isRequiredShippingReady:ye,isSubmitting:Y,onFieldValuesChange:Q,quote:f})]})}),Y?U(`p`,{className:`lockerverse-payment__sr-only`,ref:ne,role:`status`,tabIndex:-1,children:J===0?`Completing order…`:`Processing payment…`}):null,U(ct,{message:se})]})}function gt(){return U(c,{fieldCount:2,label:`Loading payment…`,sectionCount:2,showCheckbox:!0})}function _t(e,t){switch(t.type){case`loading`:return{phase:`loading`,revision:e.revision};case`ready`:return bt(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){return e===t}function vt({checkout:e}){return{displayedQuote:e,type:`ready`}}function yt(e){return e instanceof Error?e.message:`Lockerverse payment could not load.`}function bt(e,t){return{checkoutItems:[...e.items],displayedQuote:e,phase:`ready`,quoteFailure:void 0,revision:t}}function xt(e,t){let n=e.widget.fields.serviceFee;return f(e,{includeServiceFee:n,selection:t})}function St(e,t){try{return bt(xt(e,t),1)}catch(e){return{failure:yt(e),phase:`error`,revision:0}}}function Ct({catalog:e,client:t,paymentState:n,selection:r}){let i=Oe(r),a=i.success?JSON.stringify(i.value):`invalid-selection`,o=y(()=>i.success?i.value:[],[i.success,a]),[s,c]=b(_t,void 0,()=>i.success?St(e,o):{phase:`loading`,revision:0}),l=x(void 0),u=x(0),d=x(s.phase===`ready`?a:void 0),f=x(s.phase===`error`?a:void 0);g(()=>{if(!i.success||n===`submitting`||n===`success`||n===`unresolved`||$(f.current,a)||$(l.current,a))return;let r=!0;l.current=a;let s=d.current===a;s||c({type:`loading`});function p(e){r&&c(e)}function m(){r&&(l.current=void 0,f.current=a)}let h;function g(e){if(!r||(l.current=void 0,f.current=a,s&&h!==void 0&&u.current!==h))return;let t=yt(e);c(s?{failure:t,type:`quote-error`}:{failure:t,type:`error`})}async function _(){try{h=u.current;let n=e.widget.fields.serviceFee;if(!s){let t=xt(e,o);s=!0,d.current=a,p(vt({checkout:t}))}m();let r=await t.calculateTotal({catalog:e,includeServiceFee:n,selection:o});u.current===h&&p({checkout:r,type:`checkout`})}catch(e){g(e)}}return _(),()=>{r=!1,$(l.current,a)&&(l.current=void 0)}},[e,t,i.success,n,a,o]);let p=n===`submitting`||n===`success`||n===`unresolved`,m=$(d.current,a)||$(f.current,a)||$(l.current,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`})}}}function wt({catalog:e,client:t,...n}){let{branding:i,className:a,metadata:o,onPaymentComplete:c,onPaymentRecoveryChange:l,onPaymentUncertain:u,resumePayment:d,selection:f,style:p,stripeLoader:h=Qe,theme:_=`dark`,...y}=n,[b,C]=S(d),w=x(null),[T,E]=S(),[D,O]=S(`idle`),k=x(void 0),{selectionError:A,session:j,updateCheckout:M}=Ct({catalog:e,client:t,paymentState:D,selection:f}),N=j.phase===`ready`?j.revision:void 0,P=m(e=>{N!==void 0&&(k.current=N),O(e)},[N]),F=m(e=>l?.(e),[l]),I=m(()=>{C(void 0)},[]);g(()=>{j.phase===`loading`&&E(void 0)},[j.phase]),v(()=>{j.phase===`ready`&&k.current!==j.revision&&O(e=>e===`success`||e===`unresolved`?e:`idle`)},[j.phase,j.revision]);let L=[`lockerverse-payment`,a].filter(Boolean).join(` `),R=i??e.community,z=s(p?.[`--lockerverse-accent`]??R?.accentColor??`#38d77a`),B=r(z),V={...p};return(p?.[`--lockerverse-accent`]!==void 0||R?.accentColor)&&(V[`--lockerverse-accent`]=z),B&&p?.[`--lockerverse-accent-contrast`]===void 0&&(V[`--lockerverse-accent-contrast`]=B),A?U(`section`,{...y,className:L,"data-lockerverse-theme":_,role:`alert`,style:V,children:A}):j.phase===`error`?U(`section`,{...y,className:L,"data-lockerverse-theme":_,style:V,children:U(`p`,{role:`alert`,children:j.failure})}):j.phase===`ready`?W(`section`,{...y,"aria-label":`Payment`,className:L,"data-lockerverse-theme":_,"data-payment-state":D,ref:w,style:V,children:[W(`header`,{children:[e.widget.showCommunityBranding&&R?W(`div`,{className:`lockerverse-payment__branding`,children:[R.imageUrl?U(`img`,{alt:R.name,height:`48`,src:R.imageUrl,width:`48`}):null,U(`strong`,{children:R.name})]}):null,U(`h1`,{children:e.widget.title??e.widget.name}),e.widget.description?U(`p`,{children:e.widget.description}):null]}),T?U(`p`,{className:`lockerverse-payment__payment-status`,role:`status`,children:T}):null,j.quoteFailure?W(`div`,{className:`lockerverse-payment__payment-status`,role:`alert`,children:[U(`span`,{children:j.quoteFailure}),U(`span`,{children:` The final total will be checked when you submit.`})]}):null,U(re,{container:w,children:U(it,{accentColor:z,catalog:e,checkoutItems:j.checkoutItems,client:t,fontFamily:p?.[`--lockerverse-font-family`]??`ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif`,metadata:o,onPaymentComplete:c,onPaymentRecoveryChange:F,onPaymentUncertain:u,onQuoteChange:(e,t)=>{E(t),M(e)},onResumePaymentFailed:I,onStateChange:P,quote:j.displayedQuote,resumePayment:b,stripeLoader:h,theme:_,visualStyle:V},j.revision)})]}):U(`section`,{...y,"aria-busy":`true`,"aria-label":`Payment`,className:L,"data-lockerverse-theme":_,style:V,children:U(gt,{})})}function Tt({children:e,loading:t=!1,viewProps:n}){let{branding:i,className:a,metadata:o,onPaymentComplete:c,onPaymentRecoveryChange:l,onPaymentUncertain:u,resumePayment:d,selection:f,stripeLoader:p,style:m,theme:h=`dark`,...g}=n,_=s(m?.[`--lockerverse-accent`]??i?.accentColor??`#38d77a`),v=r(_),y={...m};return(m?.[`--lockerverse-accent`]!==void 0||i?.accentColor)&&(y[`--lockerverse-accent`]=_),v&&m?.[`--lockerverse-accent-contrast`]===void 0&&(y[`--lockerverse-accent-contrast`]=v),U(`section`,{...g,...t?{"aria-busy":!0,"aria-label":`Payment`}:{},className:[`lockerverse-payment`,a].filter(Boolean).join(` `),"data-lockerverse-theme":h,style:y,children:e})}function Et({widget:e,...t}){return e.error?W(Tt,{viewProps:t,children:[U(`p`,{role:`alert`,children:e.error.message}),U(`button`,{onClick:e.refresh,type:`button`,children:`Retry`})]}):e.loading||!e.catalog?U(Tt,{loading:!0,viewProps:t,children:U(gt,{})}):U(wt,{catalog:e.catalog,client:e.client,...t})}export{$e as n,Et as t};
|
|
2
2
|
//# sourceMappingURL=lockerverse-payment.js.map
|