@adyen/adyen-web 6.35.0 → 6.36.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/adyen.css +5 -5
- package/dist/cjs/adyen.css.map +1 -1
- package/dist/cjs/index.cjs +2 -2
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/index.d.cts +2613 -1935
- package/dist/es/adyen.css +5 -5
- package/dist/es/adyen.css.map +1 -1
- package/dist/es/components/ApplePay/services/ApplePayService.js.map +1 -1
- package/dist/es/components/Donation/Donation.js +1 -1
- package/dist/es/components/Donation/Donation.js.map +1 -1
- package/dist/es/components/Donation/DonationCampaignService.js +2 -0
- package/dist/es/components/Donation/DonationCampaignService.js.map +1 -0
- package/dist/es/components/Donation/components/DonationComponent.js +1 -1
- package/dist/es/components/Donation/components/DonationComponent.js.map +1 -1
- package/dist/es/components/Donation/components/utils.js.map +1 -1
- package/dist/es/components/Iris/Iris.js +1 -1
- package/dist/es/components/Iris/Iris.js.map +1 -1
- package/dist/es/components/Iris/types.js.map +1 -1
- package/dist/es/components/PayByBankPix/components/Enrollment/Enrollment.js +1 -1
- package/dist/es/components/PayByBankPix/components/Enrollment/Enrollment.js.map +1 -1
- package/dist/es/components/helpers/IssuerListContainer/IssuerListContainer.js +1 -1
- package/dist/es/components/helpers/IssuerListContainer/IssuerListContainer.js.map +1 -1
- package/dist/es/components/internal/Address/Address.js +1 -1
- package/dist/es/components/internal/Address/Address.js.map +1 -1
- package/dist/es/components/internal/Address/components/AddressSearch.js.map +1 -1
- package/dist/es/components/internal/ClickToPay/components/CtPInfo/CtPInfoModal/CtPInfoModal.js +1 -1
- package/dist/es/components/internal/ClickToPay/components/CtPInfo/CtPInfoModal/CtPInfoModal.js.map +1 -1
- package/dist/es/components/internal/DisclaimerMessage/DisclaimerMessage.js +1 -1
- package/dist/es/components/internal/DisclaimerMessage/DisclaimerMessage.js.map +1 -1
- package/dist/es/components/internal/FormFields/Field/Field.js +1 -1
- package/dist/es/components/internal/FormFields/Field/Field.js.map +1 -1
- package/dist/es/components/internal/FormFields/Fieldset/Fieldset.js +1 -1
- package/dist/es/components/internal/FormFields/Fieldset/Fieldset.js.map +1 -1
- package/dist/es/components/internal/FormFields/Select/components/SelectButton.js +1 -1
- package/dist/es/components/internal/FormFields/Select/components/SelectButton.js.map +1 -1
- package/dist/es/components/internal/IssuerList/IssuerButtonGroup/IssuerButtonGroup.js +1 -1
- package/dist/es/components/internal/IssuerList/IssuerButtonGroup/IssuerButtonGroup.js.map +1 -1
- package/dist/es/components/internal/IssuerList/IssuerList.js +1 -1
- package/dist/es/components/internal/IssuerList/IssuerList.js.map +1 -1
- package/dist/es/components/internal/SecuredFields/lib/CSF/CSF.js.map +1 -1
- package/dist/es/components/internal/UIElement/UIElement.js +1 -1
- package/dist/es/components/internal/UIElement/UIElement.js.map +1 -1
- package/dist/es/components/internal/UIElement/utils.js +1 -1
- package/dist/es/components/internal/UIElement/utils.js.map +1 -1
- package/dist/es/core/Analytics/events/AnalyticsErrorEvent.js.map +1 -1
- package/dist/es/core/Analytics/events/AnalyticsInfoEvent.js +1 -1
- package/dist/es/core/Analytics/events/AnalyticsInfoEvent.js.map +1 -1
- package/dist/es/core/Analytics/events/AnalyticsLogEvent.js +1 -1
- package/dist/es/core/Analytics/events/AnalyticsLogEvent.js.map +1 -1
- package/dist/es/core/CheckoutSession/CheckoutSession.js +1 -1
- package/dist/es/core/CheckoutSession/CheckoutSession.js.map +1 -1
- package/dist/es/core/Services/sessions/constants.js +1 -1
- package/dist/es/core/Services/sessions/constants.js.map +1 -1
- package/dist/es/core/Services/sessions/fetch-donation-campaigns.js +2 -0
- package/dist/es/core/Services/sessions/fetch-donation-campaigns.js.map +1 -0
- package/dist/es/core/Services/sessions/make-donation.js +2 -0
- package/dist/es/core/Services/sessions/make-donation.js.map +1 -0
- package/dist/es/core/config.js +1 -1
- package/dist/es/core/config.js.map +1 -1
- package/dist/es/core/core.registry.js +1 -1
- package/dist/es/core/core.registry.js.map +1 -1
- package/dist/es/core/utils.js +1 -1
- package/dist/es/core/utils.js.map +1 -1
- package/dist/es/index.d.ts +2613 -1935
- package/dist/es-legacy/adyen.css +5 -5
- package/dist/es-legacy/adyen.css.map +1 -1
- package/dist/es-legacy/components/ApplePay/services/ApplePayService.js.map +1 -1
- package/dist/es-legacy/components/Donation/Donation.js +1 -1
- package/dist/es-legacy/components/Donation/Donation.js.map +1 -1
- package/dist/es-legacy/components/Donation/DonationCampaignService.js +2 -0
- package/dist/es-legacy/components/Donation/DonationCampaignService.js.map +1 -0
- package/dist/es-legacy/components/Donation/components/DonationComponent.js +1 -1
- package/dist/es-legacy/components/Donation/components/DonationComponent.js.map +1 -1
- package/dist/es-legacy/components/Donation/components/utils.js.map +1 -1
- package/dist/es-legacy/components/Iris/Iris.js +1 -1
- package/dist/es-legacy/components/Iris/Iris.js.map +1 -1
- package/dist/es-legacy/components/Iris/types.js.map +1 -1
- package/dist/es-legacy/components/PayByBankPix/components/Enrollment/Enrollment.js +1 -1
- package/dist/es-legacy/components/PayByBankPix/components/Enrollment/Enrollment.js.map +1 -1
- package/dist/es-legacy/components/helpers/IssuerListContainer/IssuerListContainer.js +1 -1
- package/dist/es-legacy/components/helpers/IssuerListContainer/IssuerListContainer.js.map +1 -1
- package/dist/es-legacy/components/internal/Address/Address.js +1 -1
- package/dist/es-legacy/components/internal/Address/Address.js.map +1 -1
- package/dist/es-legacy/components/internal/Address/components/AddressSearch.js.map +1 -1
- package/dist/es-legacy/components/internal/ClickToPay/components/CtPInfo/CtPInfoModal/CtPInfoModal.js +1 -1
- package/dist/es-legacy/components/internal/ClickToPay/components/CtPInfo/CtPInfoModal/CtPInfoModal.js.map +1 -1
- package/dist/es-legacy/components/internal/DisclaimerMessage/DisclaimerMessage.js +1 -1
- package/dist/es-legacy/components/internal/DisclaimerMessage/DisclaimerMessage.js.map +1 -1
- package/dist/es-legacy/components/internal/FormFields/Field/Field.js +1 -1
- package/dist/es-legacy/components/internal/FormFields/Field/Field.js.map +1 -1
- package/dist/es-legacy/components/internal/FormFields/Fieldset/Fieldset.js +1 -1
- package/dist/es-legacy/components/internal/FormFields/Fieldset/Fieldset.js.map +1 -1
- package/dist/es-legacy/components/internal/FormFields/Select/components/SelectButton.js +1 -1
- package/dist/es-legacy/components/internal/FormFields/Select/components/SelectButton.js.map +1 -1
- package/dist/es-legacy/components/internal/IssuerList/IssuerButtonGroup/IssuerButtonGroup.js +1 -1
- package/dist/es-legacy/components/internal/IssuerList/IssuerButtonGroup/IssuerButtonGroup.js.map +1 -1
- package/dist/es-legacy/components/internal/IssuerList/IssuerList.js +1 -1
- package/dist/es-legacy/components/internal/IssuerList/IssuerList.js.map +1 -1
- package/dist/es-legacy/components/internal/SecuredFields/lib/CSF/CSF.js.map +1 -1
- package/dist/es-legacy/components/internal/UIElement/UIElement.js +1 -1
- package/dist/es-legacy/components/internal/UIElement/UIElement.js.map +1 -1
- package/dist/es-legacy/components/internal/UIElement/utils.js +1 -1
- package/dist/es-legacy/components/internal/UIElement/utils.js.map +1 -1
- package/dist/es-legacy/core/Analytics/events/AnalyticsErrorEvent.js.map +1 -1
- package/dist/es-legacy/core/Analytics/events/AnalyticsInfoEvent.js +1 -1
- package/dist/es-legacy/core/Analytics/events/AnalyticsInfoEvent.js.map +1 -1
- package/dist/es-legacy/core/Analytics/events/AnalyticsLogEvent.js +1 -1
- package/dist/es-legacy/core/Analytics/events/AnalyticsLogEvent.js.map +1 -1
- package/dist/es-legacy/core/CheckoutSession/CheckoutSession.js +1 -1
- package/dist/es-legacy/core/CheckoutSession/CheckoutSession.js.map +1 -1
- package/dist/es-legacy/core/Services/sessions/constants.js +1 -1
- package/dist/es-legacy/core/Services/sessions/constants.js.map +1 -1
- package/dist/es-legacy/core/Services/sessions/fetch-donation-campaigns.js +2 -0
- package/dist/es-legacy/core/Services/sessions/fetch-donation-campaigns.js.map +1 -0
- package/dist/es-legacy/core/Services/sessions/make-donation.js +2 -0
- package/dist/es-legacy/core/Services/sessions/make-donation.js.map +1 -0
- package/dist/es-legacy/core/config.js +1 -1
- package/dist/es-legacy/core/config.js.map +1 -1
- package/dist/es-legacy/core/core.registry.js +1 -1
- package/dist/es-legacy/core/core.registry.js.map +1 -1
- package/dist/es-legacy/core/utils.js +1 -1
- package/dist/es-legacy/core/utils.js.map +1 -1
- package/package.json +19 -19
- package/styles/adyen.css +5 -5
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ApplePayService.js","sources":["../../../../../src/components/ApplePay/services/ApplePayService.ts"],"sourcesContent":["import { ApplePayConfiguration, ApplePayPaymentAuthorizationResult } from '../types';\n\nexport interface ApplePayServiceOptions {\n version: number;\n onError: (error?: unknown) => void;\n onCancel?: (event: ApplePayJS.Event) => void;\n onValidateMerchant: ApplePayConfiguration['onValidateMerchant'];\n onCouponCodeChanged?: ApplePayConfiguration['onCouponCodeChanged'];\n onPaymentMethodSelected?: ApplePayConfiguration['onPaymentMethodSelected'];\n onShippingMethodSelected?: ApplePayConfiguration['onShippingMethodSelected'];\n onShippingContactSelected?: ApplePayConfiguration['onShippingContactSelected'];\n onPaymentAuthorized: (\n resolve: (result: ApplePayPaymentAuthorizationResult) => void,\n reject: (result: ApplePayPaymentAuthorizationResult) => void,\n event: ApplePayJS.ApplePayPaymentAuthorizedEvent\n ) => void;\n}\n\nclass ApplePayService {\n private session: ApplePaySession;\n private readonly options: ApplePayServiceOptions;\n\n constructor(paymentRequest: ApplePayJS.ApplePayPaymentRequest, options: ApplePayServiceOptions) {\n this.options = options;\n\n this.session = new ApplePaySession(options.version, paymentRequest);\n this.session.onvalidatemerchant = event => {\n void this.onvalidatemerchant(event, options.onValidateMerchant);\n };\n this.session.onpaymentauthorized = event => {\n void this.onpaymentauthorized(event, options.onPaymentAuthorized);\n };\n\n this.session.oncancel = event => {\n this.oncancel(event, options.onCancel);\n };\n\n if (typeof options.onPaymentMethodSelected === 'function') {\n this.session.onpaymentmethodselected = event => {\n void this.onpaymentmethodselected(event, options.onPaymentMethodSelected);\n };\n }\n\n if (typeof options.onShippingContactSelected === 'function') {\n this.session.onshippingcontactselected = event => {\n void this.onshippingcontactselected(event, options.onShippingContactSelected);\n };\n }\n\n if (typeof options.onShippingMethodSelected === 'function') {\n this.session.onshippingmethodselected = event => {\n void this.onshippingmethodselected(event, options.onShippingMethodSelected);\n };\n }\n\n if (typeof options.onCouponCodeChanged === 'function') {\n this.session.oncouponcodechanged = event => {\n void this.oncouponcodechanged(event, options.onCouponCodeChanged);\n };\n }\n }\n\n /**\n * Begins the merchant validation process.\n * When this method is called, the payment sheet is presented and the merchant validation process is initiated.\n * @see {@link https://developer.apple.com/documentation/applepayontheweb/applepaysession/1778001-begin}\n */\n begin() {\n return this.session.begin();\n }\n\n /**\n * An event handler that is called when the payment sheet is displayed.\n * Use this attribute to request and return a merchant session.\n * @param event - An ApplePayValidateMerchantEvent object (contains validationURL)\n * @param onValidateMerchant - A promise implemented by the merchant that will resolve with the merchantSession\n * @see {@link https://developer.apple.com/documentation/applepayontheweb/apple_pay_js_api/providing_merchant_validation}\n */\n onvalidatemerchant(event: ApplePayJS.ApplePayValidateMerchantEvent, onValidateMerchant: ApplePayConfiguration['onValidateMerchant']) {\n return new Promise<unknown>((resolve, reject) => {\n void onValidateMerchant(resolve, reject, event.validationURL);\n })\n .then(response => {\n this.session.completeMerchantValidation(response);\n })\n .catch(error => {\n console.error(error);\n this.session.abort();\n this.options.onError(error);\n });\n }\n\n /**\n * An event handler that is called when the user has authorized the Apple Pay payment with Touch ID, Face ID, or passcode.\n * The onpaymentauthorized function must complete the payment and respond by calling completePayment before the 30 second timeout.\n *\n * @param event - The event parameter contains the payment (ApplePayPayment) attribute.\n * @param onPaymentAuthorized - A promise that will complete the payment when resolved. Use this promise to process the payment.\n * @see {@link https://developer.apple.com/documentation/applepayontheweb/applepaysession/1778020-onpaymentauthorized}\n */\n onpaymentauthorized(\n event: ApplePayJS.ApplePayPaymentAuthorizedEvent,\n onPaymentAuthorized: ApplePayServiceOptions['onPaymentAuthorized']\n ): Promise<void> {\n return new Promise((resolve, reject) => onPaymentAuthorized(resolve, reject, event))\n .then((result: ApplePayPaymentAuthorizationResult) => {\n this.session.completePayment(result);\n })\n .catch((result: ApplePayPaymentAuthorizationResult) => {\n this.session.completePayment(result);\n });\n }\n\n /**\n * An event handler that is called when a new payment method is selected.\n * The onpaymentmethodselected function must resolve before the 30 second timeout\n *\n * @param event - The event parameter contains the payment (ApplePayPayment) attribute.\n * @param onPaymentMethodSelected - A promise that will complete the payment when resolved. Use this promise to process the payment.\n * @see {@link https://developer.apple.com/documentation/applepayontheweb/applepaysession/1778013-onpaymentmethodselected}\n */\n onpaymentmethodselected(\n event: ApplePayJS.ApplePayPaymentMethodSelectedEvent,\n onPaymentMethodSelected: ApplePayServiceOptions['onPaymentMethodSelected']\n ) {\n return new Promise((resolve, reject) => onPaymentMethodSelected(resolve, reject, event))\n .then((paymentMethodUpdate: ApplePayJS.ApplePayPaymentMethodUpdate) => {\n this.session.completePaymentMethodSelection(paymentMethodUpdate);\n })\n .catch((paymentMethodUpdate: ApplePayJS.ApplePayPaymentMethodUpdate) => {\n this.session.completePaymentMethodSelection(paymentMethodUpdate);\n });\n }\n\n /**\n * An event handler that is called when a new payment method is selected.\n * The onpaymentmethodselected function must resolve before the 30 second timeout\n * @param event - The event parameter contains the shippingContact attribute.\n * @param onShippingContactSelected - A promise that will complete the selection of a shipping contact with an update.\n * @see {@link https://developer.apple.com/documentation/applepayontheweb/applepaysession/1778009-onshippingcontactselected}\n */\n onshippingcontactselected(\n event: ApplePayJS.ApplePayShippingContactSelectedEvent,\n onShippingContactSelected: ApplePayConfiguration['onShippingContactSelected']\n ) {\n return new Promise((resolve, reject) => onShippingContactSelected(resolve, reject, event))\n .then((shippingContactUpdate: ApplePayJS.ApplePayShippingContactUpdate) => {\n this.session.completeShippingContactSelection(shippingContactUpdate);\n })\n .catch((shippingContactUpdate: ApplePayJS.ApplePayShippingContactUpdate) => {\n this.session.completeShippingContactSelection(shippingContactUpdate);\n });\n }\n\n /**\n * An event handler that is called when a new payment method is selected.\n * The onpaymentmethodselected function must resolve before the 30 second timeout\n * @param event - The event parameter contains the shippingMethod attribute.\n * @param onShippingMethodSelected - A promise that will complete the selection of a shipping method with an update.\n * @see {@link https://developer.apple.com/documentation/applepayontheweb/applepaysession/1778009-onshippingcontactselected}\n */\n onshippingmethodselected(\n event: ApplePayJS.ApplePayShippingMethodSelectedEvent,\n onShippingMethodSelected: ApplePayConfiguration['onShippingMethodSelected']\n ) {\n return new Promise((resolve, reject) => onShippingMethodSelected(resolve, reject, event))\n .then((shippingMethodUpdate: ApplePayJS.ApplePayShippingMethodUpdate) => {\n this.session.completeShippingMethodSelection(shippingMethodUpdate);\n })\n .catch((shippingMethodUpdate: ApplePayJS.ApplePayShippingMethodUpdate) => {\n this.session.completeShippingMethodSelection(shippingMethodUpdate);\n });\n }\n\n oncouponcodechanged(event: ApplePayJS.ApplePayCouponCodeChangedEvent, onCouponCodeChanged: ApplePayConfiguration['onCouponCodeChanged']) {\n return new Promise((resolve, reject) => onCouponCodeChanged(resolve, reject, event))\n .then((couponCodeUpdate: ApplePayJS.ApplePayCouponCodeUpdate) => {\n this.session.completeCouponCodeChange(couponCodeUpdate);\n })\n .catch((couponCodeUpdate: ApplePayJS.ApplePayCouponCodeUpdate) => {\n this.session.completeCouponCodeChange(couponCodeUpdate);\n });\n }\n\n /**\n * An event handler that is automatically called when the payment UI is dismissed.\n * This function can be called even after an onpaymentauthorized event has been dispatched.\n * @param event -\n * @param onCancel -\n * @see {@link https://developer.apple.com/documentation/applepayontheweb/applepaysession/1778029-oncancel}\n */\n oncancel(event: ApplePayJS.Event, onCancel: (event: ApplePayJS.Event) => void): void {\n onCancel(event);\n }\n}\n\nexport default ApplePayService;\n"],"names":["ApplePayService","begin","this","session","onvalidatemerchant","event","onValidateMerchant","Promise","resolve","reject","validationURL","then","response","completeMerchantValidation","catch","error","console","abort","options","onError","onpaymentauthorized","onPaymentAuthorized","result","completePayment","onpaymentmethodselected","onPaymentMethodSelected","paymentMethodUpdate","completePaymentMethodSelection","onshippingcontactselected","onShippingContactSelected","shippingContactUpdate","completeShippingContactSelection","onshippingmethodselected","onShippingMethodSelected","shippingMethodUpdate","completeShippingMethodSelection","oncouponcodechanged","onCouponCodeChanged","couponCodeUpdate","completeCouponCodeChange","oncancel","onCancel","constructor","paymentRequest","_define_property","ApplePaySession","version"],"mappings":"wHAkBA,MAAMA,EAiDFC,KAAAA,GACI,OAAOC,KAAKC,QAAQF,OACxB,CASAG,kBAAAA,CAAmBC,EAAiDC,GAChE,OAAO,IAAIC,QAAiB,CAACC,EAASC,KAC7BH,EAAmBE,EAASC,EAAQJ,EAAMK,iBAE9CC,KAAKC,IACFV,KAAKC,QAAQU,2BAA2BD,KAE3CE,MAAMC,IACHC,QAAQD,MAAMA,GACdb,KAAKC,QAAQc,QACbf,KAAKgB,QAAQC,QAAQJ,IAEjC,CAUAK,mBAAAA,CACIf,EACAgB,GAEA,OAAO,IAAId,QAAQ,CAACC,EAASC,IAAWY,EAAoBb,EAASC,EAAQJ,IACxEM,KAAMW,IACHpB,KAAKC,QAAQoB,gBAAgBD,KAEhCR,MAAOQ,IACJpB,KAAKC,QAAQoB,gBAAgBD,IAEzC,CAUAE,uBAAAA,CACInB,EACAoB,GAEA,OAAO,IAAIlB,QAAQ,CAACC,EAASC,IAAWgB,EAAwBjB,EAASC,EAAQJ,IAC5EM,KAAMe,IACHxB,KAAKC,QAAQwB,+BAA+BD,KAE/CZ,MAAOY,IACJxB,KAAKC,QAAQwB,+BAA+BD,IAExD,CASAE,yBAAAA,CACIvB,EACAwB,GAEA,OAAO,IAAItB,QAAQ,CAACC,EAASC,IAAWoB,EAA0BrB,EAASC,EAAQJ,IAC9EM,KAAMmB,IACH5B,KAAKC,QAAQ4B,iCAAiCD,KAEjDhB,MAAOgB,IACJ5B,KAAKC,QAAQ4B,iCAAiCD,IAE1D,CASAE,wBAAAA,CACI3B,EACA4B,G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,sBAGzD"}
|
|
1
|
+
{"version":3,"file":"ApplePayService.js","sources":["../../../../../src/components/ApplePay/services/ApplePayService.ts"],"sourcesContent":["import { ApplePayConfiguration, ApplePayPaymentAuthorizationResult } from '../types';\n\nexport interface ApplePayServiceOptions {\n version: number;\n onError: (error?: unknown) => void;\n onCancel?: (event: ApplePayJS.Event) => void;\n onValidateMerchant: ApplePayConfiguration['onValidateMerchant'];\n onCouponCodeChanged?: ApplePayConfiguration['onCouponCodeChanged'];\n onPaymentMethodSelected?: ApplePayConfiguration['onPaymentMethodSelected'];\n onShippingMethodSelected?: ApplePayConfiguration['onShippingMethodSelected'];\n onShippingContactSelected?: ApplePayConfiguration['onShippingContactSelected'];\n onPaymentAuthorized: (\n resolve: (result: ApplePayPaymentAuthorizationResult) => void,\n reject: (result: ApplePayPaymentAuthorizationResult) => void,\n event: ApplePayJS.ApplePayPaymentAuthorizedEvent\n ) => void;\n}\n\nclass ApplePayService {\n private session: ApplePaySession;\n private readonly options: ApplePayServiceOptions;\n\n constructor(paymentRequest: ApplePayJS.ApplePayPaymentRequest, options: ApplePayServiceOptions) {\n this.options = options;\n\n this.session = new ApplePaySession(options.version, paymentRequest);\n this.session.onvalidatemerchant = event => {\n void this.onvalidatemerchant(event, options.onValidateMerchant);\n };\n this.session.onpaymentauthorized = event => {\n void this.onpaymentauthorized(event, options.onPaymentAuthorized);\n };\n\n this.session.oncancel = event => {\n this.oncancel(event, options.onCancel);\n };\n\n if (typeof options.onPaymentMethodSelected === 'function') {\n this.session.onpaymentmethodselected = event => {\n void this.onpaymentmethodselected(event, options.onPaymentMethodSelected);\n };\n }\n\n if (typeof options.onShippingContactSelected === 'function') {\n this.session.onshippingcontactselected = event => {\n void this.onshippingcontactselected(event, options.onShippingContactSelected);\n };\n }\n\n if (typeof options.onShippingMethodSelected === 'function') {\n this.session.onshippingmethodselected = event => {\n void this.onshippingmethodselected(event, options.onShippingMethodSelected);\n };\n }\n\n if (typeof options.onCouponCodeChanged === 'function') {\n this.session.oncouponcodechanged = event => {\n void this.oncouponcodechanged(event, options.onCouponCodeChanged);\n };\n }\n }\n\n /**\n * Begins the merchant validation process.\n * When this method is called, the payment sheet is presented and the merchant validation process is initiated.\n * @see {@link https://developer.apple.com/documentation/applepayontheweb/applepaysession/begin}\n */\n begin() {\n return this.session.begin();\n }\n\n /**\n * An event handler that is called when the payment sheet is displayed.\n * Use this attribute to request and return a merchant session.\n * @param event - An ApplePayValidateMerchantEvent object (contains validationURL)\n * @param onValidateMerchant - A function implemented by the merchant that will resolve with the merchantSession\n * @see {@link https://developer.apple.com/documentation/applepayontheweb/applepaysession/onvalidatemerchant}\n */\n onvalidatemerchant(event: ApplePayJS.ApplePayValidateMerchantEvent, onValidateMerchant: ApplePayConfiguration['onValidateMerchant']) {\n return new Promise<unknown>((resolve, reject) => {\n void onValidateMerchant(resolve, reject, event.validationURL);\n })\n .then(response => {\n this.session.completeMerchantValidation(response);\n })\n .catch(error => {\n console.error(error);\n this.session.abort();\n this.options.onError(error);\n });\n }\n\n /**\n * An event handler that is called when the user has authorized the Apple Pay payment with Touch ID, Face ID, or passcode.\n * The onpaymentauthorized function must complete the payment and respond by calling completePayment before the 30 second timeout.\n *\n * @param event - An ApplePayPaymentAuthorizedEvent object (contains payment).\n * @param onPaymentAuthorized - A function that will complete the payment when resolved. Use this promise to process the payment.\n * @see {@link https://developer.apple.com/documentation/applepayontheweb/applepaysession/onpaymentauthorized}\n */\n onpaymentauthorized(\n event: ApplePayJS.ApplePayPaymentAuthorizedEvent,\n onPaymentAuthorized: ApplePayServiceOptions['onPaymentAuthorized']\n ): Promise<void> {\n return new Promise((resolve, reject) => onPaymentAuthorized(resolve, reject, event))\n .then((result: ApplePayPaymentAuthorizationResult) => {\n this.session.completePayment(result);\n })\n .catch((result: ApplePayPaymentAuthorizationResult) => {\n this.session.completePayment(result);\n });\n }\n\n /**\n * An event handler that is called when a new payment method is selected.\n * The onpaymentmethodselected function must resolve before the 30 second timeout\n *\n * @param event - An ApplePayPaymentMethodSelectedEvent object (contains paymentMethod).\n * @param onPaymentMethodSelected - A function that will complete the payment when resolved. Use this promise to process the payment.\n * @see {@link https://developer.apple.com/documentation/applepayontheweb/applepaysession/onpaymentmethodselected}\n */\n onpaymentmethodselected(\n event: ApplePayJS.ApplePayPaymentMethodSelectedEvent,\n onPaymentMethodSelected: ApplePayServiceOptions['onPaymentMethodSelected']\n ) {\n return new Promise((resolve, reject) => onPaymentMethodSelected(resolve, reject, event))\n .then((paymentMethodUpdate: ApplePayJS.ApplePayPaymentMethodUpdate) => {\n this.session.completePaymentMethodSelection(paymentMethodUpdate);\n })\n .catch((paymentMethodUpdate: ApplePayJS.ApplePayPaymentMethodUpdate) => {\n this.session.completePaymentMethodSelection(paymentMethodUpdate);\n });\n }\n\n /**\n * An event handler that is called when a new shipping contact is selected.\n * The onshippingcontactselected function must resolve before the 30 second timeout\n * @param event - An ApplePayShippingContactSelectedEvent object (contains shippingContact).\n * @param onShippingContactSelected - A function that will complete the selection of a shipping contact with an update.\n * @see {@link https://developer.apple.com/documentation/applepayontheweb/applepaysession/onshippingcontactselected}\n */\n onshippingcontactselected(\n event: ApplePayJS.ApplePayShippingContactSelectedEvent,\n onShippingContactSelected: ApplePayConfiguration['onShippingContactSelected']\n ) {\n return new Promise((resolve, reject) => onShippingContactSelected(resolve, reject, event))\n .then((shippingContactUpdate: ApplePayJS.ApplePayShippingContactUpdate) => {\n this.session.completeShippingContactSelection(shippingContactUpdate);\n })\n .catch((shippingContactUpdate: ApplePayJS.ApplePayShippingContactUpdate) => {\n this.session.completeShippingContactSelection(shippingContactUpdate);\n });\n }\n\n /**\n * An event handler that is called when a new shipping method is selected.\n * The onshippingmethodselected function must resolve before the 30 second timeout\n * @param event - An ApplePayShippingMethodSelectedEvent object (contains shippingMethod).\n * @param onShippingMethodSelected - A function that will complete the selection of a shipping method with an update.\n * @see {@link https://developer.apple.com/documentation/applepayontheweb/applepaysession/onshippingmethodselected}\n */\n onshippingmethodselected(\n event: ApplePayJS.ApplePayShippingMethodSelectedEvent,\n onShippingMethodSelected: ApplePayConfiguration['onShippingMethodSelected']\n ) {\n return new Promise((resolve, reject) => onShippingMethodSelected(resolve, reject, event))\n .then((shippingMethodUpdate: ApplePayJS.ApplePayShippingMethodUpdate) => {\n this.session.completeShippingMethodSelection(shippingMethodUpdate);\n })\n .catch((shippingMethodUpdate: ApplePayJS.ApplePayShippingMethodUpdate) => {\n this.session.completeShippingMethodSelection(shippingMethodUpdate);\n });\n }\n\n /**\n * An event handler called by the system when the user enters or updates a coupon code.\n * The oncouponcodechanged function must resolve before the 30 second timeout\n * @param event - An ApplePayCouponCodeChangedEvent object (contains couponCode).\n * @param onCouponCodeChanged - A function that will complete the entry or update of a coupon code with an update.\n * @see {@link https://developer.apple.com/documentation/applepayontheweb/applepaysession/oncouponcodechanged}\n */\n oncouponcodechanged(event: ApplePayJS.ApplePayCouponCodeChangedEvent, onCouponCodeChanged: ApplePayConfiguration['onCouponCodeChanged']) {\n return new Promise((resolve, reject) => onCouponCodeChanged(resolve, reject, event))\n .then((couponCodeUpdate: ApplePayJS.ApplePayCouponCodeUpdate) => {\n this.session.completeCouponCodeChange(couponCodeUpdate);\n })\n .catch((couponCodeUpdate: ApplePayJS.ApplePayCouponCodeUpdate) => {\n this.session.completeCouponCodeChange(couponCodeUpdate);\n });\n }\n\n /**\n * An event handler that is automatically called when the payment UI is dismissed.\n * This function can be called even after an onpaymentauthorized event has been dispatched.\n * @param event - An ApplePayJS.Event object\n * @param onCancel - A function that will complete the cancellation of the payment.\n * @see {@link https://developer.apple.com/documentation/applepayontheweb/applepaysession/oncancel}\n */\n oncancel(event: ApplePayJS.Event, onCancel: (event: ApplePayJS.Event) => void): void {\n onCancel(event);\n }\n}\n\nexport default ApplePayService;\n"],"names":["ApplePayService","begin","this","session","onvalidatemerchant","event","onValidateMerchant","Promise","resolve","reject","validationURL","then","response","completeMerchantValidation","catch","error","console","abort","options","onError","onpaymentauthorized","onPaymentAuthorized","result","completePayment","onpaymentmethodselected","onPaymentMethodSelected","paymentMethodUpdate","completePaymentMethodSelection","onshippingcontactselected","onShippingContactSelected","shippingContactUpdate","completeShippingContactSelection","onshippingmethodselected","onShippingMethodSelected","shippingMethodUpdate","completeShippingMethodSelection","oncouponcodechanged","onCouponCodeChanged","couponCodeUpdate","completeCouponCodeChange","oncancel","onCancel","constructor","paymentRequest","_define_property","ApplePaySession","version"],"mappings":"wHAkBA,MAAMA,EAiDFC,KAAAA,GACI,OAAOC,KAAKC,QAAQF,OACxB,CASAG,kBAAAA,CAAmBC,EAAiDC,GAChE,OAAO,IAAIC,QAAiB,CAACC,EAASC,KAC7BH,EAAmBE,EAASC,EAAQJ,EAAMK,iBAE9CC,KAAKC,IACFV,KAAKC,QAAQU,2BAA2BD,KAE3CE,MAAMC,IACHC,QAAQD,MAAMA,GACdb,KAAKC,QAAQc,QACbf,KAAKgB,QAAQC,QAAQJ,IAEjC,CAUAK,mBAAAA,CACIf,EACAgB,GAEA,OAAO,IAAId,QAAQ,CAACC,EAASC,IAAWY,EAAoBb,EAASC,EAAQJ,IACxEM,KAAMW,IACHpB,KAAKC,QAAQoB,gBAAgBD,KAEhCR,MAAOQ,IACJpB,KAAKC,QAAQoB,gBAAgBD,IAEzC,CAUAE,uBAAAA,CACInB,EACAoB,GAEA,OAAO,IAAIlB,QAAQ,CAACC,EAASC,IAAWgB,EAAwBjB,EAASC,EAAQJ,IAC5EM,KAAMe,IACHxB,KAAKC,QAAQwB,+BAA+BD,KAE/CZ,MAAOY,IACJxB,KAAKC,QAAQwB,+BAA+BD,IAExD,CASAE,yBAAAA,CACIvB,EACAwB,GAEA,OAAO,IAAItB,QAAQ,CAACC,EAASC,IAAWoB,EAA0BrB,EAASC,EAAQJ,IAC9EM,KAAMmB,IACH5B,KAAKC,QAAQ4B,iCAAiCD,KAEjDhB,MAAOgB,IACJ5B,KAAKC,QAAQ4B,iCAAiCD,IAE1D,CASAE,wBAAAA,CACI3B,EACA4B,GAEA,OAAO,IA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|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createElement as t
|
|
1
|
+
import{createElement as t}from"../../external/preact/dist/preact.js";import{UIElement as e}from"../internal/UIElement/UIElement.js";import n from"./components/DonationComponent.js";import{TxVariants as o}from"../tx-variants.js";import{AnalyticsLogEvent as s,LogEventSubtype as i,LogEventType as a}from"../../core/Analytics/events/AnalyticsLogEvent.js";import{AnalyticsInfoEvent as r,UiTarget as c,InfoEventType as d}from"../../core/Analytics/events/AnalyticsInfoEvent.js";import l,{REPARENT_WITHOUT_AUTO_START_ERROR_MSG as m}from"./DonationCampaignService.js";function p(t,e,n){return e in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}class h extends e{static isServiceMode(t){return"rootNode"in t&&!!t.rootNode}async initialiseServiceMode(t,e){if(t.session)if(t.session.sessionsDonationInitiated)console.error(m);else{t.session.sessionsDonationInitiated=!0;try{const n=await new l(t,e).initialise();n&&(this.props={...this.props,...n},this.mount(e.rootNode))}catch(e){t.options.donation?.onDonationFailure?.(e)}}}get data(){return this.state.data}get isValid(){return this.state.isValid}setState(t){this.state={...this.state,...t}}donate(){const t=new s({component:h.type,type:a.submit,subType:i.donation,message:"Making donation"});this.core.modules.analytics.sendAnalytics(t);const{data:e,isValid:n}=this;this.props.onDonate({data:e,isValid:n},this)}cancel(){const t=new s({component:h.type,type:a.closed,subType:i.donation,message:"Opting to not make donation"});this.core.modules.analytics.sendAnalytics(t);const{data:e,isValid:n}=this;this.isInServiceMode&&this.unmount(),this.props.onCancel({data:e,isValid:n})}amountSelected(t){const e=new r({component:h.type,type:d.selected,selectedValue:JSON.stringify(t.data.amount),target:c.donationAmountButton});this.core.modules.analytics.sendAnalytics(e)}componentToRender(){return t(n,{...this.props,ref:t=>{this.componentRef=t},onChange:this.setState,onDonate:this.donate,onCancel:this.cancel,onAmountSelected:this.amountSelected})}constructor(t,e){const n=h.isServiceMode(e);super(t,n?void 0:e),p(this,"isInServiceMode",!1),this.donate=this.donate.bind(this),this.cancel=this.cancel.bind(this),this.amountSelected=this.amountSelected.bind(this),this.isInServiceMode=n,t.session&&n&&this.initialiseServiceMode(t,e)}}p(h,"type",o.donation),p(h,"defaultProps",{onCancel:()=>{},onDonate:()=>{}});export{h as default};
|
|
2
2
|
//# sourceMappingURL=Donation.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Donation.js","sources":["../../../../src/components/Donation/Donation.tsx"],"sourcesContent":["import {
|
|
1
|
+
{"version":3,"file":"Donation.js","sources":["../../../../src/components/Donation/Donation.tsx"],"sourcesContent":["import { h } from 'preact';\nimport UIElement from '../internal/UIElement/UIElement';\nimport DonationComponent from './components/DonationComponent';\nimport { TxVariants } from '../tx-variants';\nimport type { ICore } from '../../core/types';\nimport { DonationCampaignOptions, DonationConfiguration, DonationProps } from './types';\nimport { AnalyticsLogEvent, LogEventSubtype, LogEventType } from '../../core/Analytics/events/AnalyticsLogEvent';\nimport { DonationPayload } from './components/types';\nimport { AnalyticsInfoEvent, InfoEventType, UiTarget } from '../../core/Analytics/events/AnalyticsInfoEvent';\nimport DonationCampaignService, { REPARENT_WITHOUT_AUTO_START_ERROR_MSG } from './DonationCampaignService';\n\nclass DonationElement extends UIElement<DonationConfiguration> {\n public static readonly type = TxVariants.donation;\n\n private readonly isInServiceMode: boolean = false;\n\n constructor(checkout: ICore, props: DonationProps) {\n const isServiceMode = DonationElement.isServiceMode(props);\n const initialConfig = isServiceMode ? undefined : props;\n\n super(checkout, initialConfig);\n\n this.donate = this.donate.bind(this);\n this.cancel = this.cancel.bind(this);\n this.amountSelected = this.amountSelected.bind(this);\n\n this.isInServiceMode = isServiceMode;\n\n if (checkout.session && isServiceMode) {\n void this.initialiseServiceMode(checkout, props); // NOSONAR - async in constructor is intentional for fire-and-forget service mode initialization\n }\n }\n\n /**\n * Type guard to determine if props are for \"service\" mode.\n *\n * The \"service\" mode is used in the /sessions flow:\n * - if the /payments response mandates it, we consult the /sessions/donationCampaigns endpoint on behalf of the merchant, and mount any found Donation Campaigns.\n *\n * The opposite of this mode is the \"direct\" mode, used in the Advanced flow:\n * - the merchant makes their own call to the /donationCampaigns endpoint and provides the Donation Campaign directly to the component.\n */\n private static isServiceMode(props: DonationProps): props is DonationCampaignOptions {\n return 'rootNode' in props && !!props.rootNode;\n }\n\n public static readonly defaultProps = {\n onCancel: () => {},\n onDonate: () => {}\n };\n\n private async initialiseServiceMode(checkout: ICore, props: DonationCampaignOptions) {\n if (!checkout.session) {\n return;\n }\n\n if (checkout.session.sessionsDonationInitiated) {\n console.error(REPARENT_WITHOUT_AUTO_START_ERROR_MSG);\n return;\n }\n\n checkout.session.sessionsDonationInitiated = true;\n try {\n const donationCampaign = await new DonationCampaignService(checkout, props).initialise();\n if (donationCampaign) {\n this.props = { ...this.props, ...donationCampaign };\n this.mount(props.rootNode);\n }\n // If no campaigns found (response is null), don't mount - silently do nothing\n } catch (error: unknown) {\n // Call merchant defined callback\n // e.g. when the merchant wants to reparent the component and donation type = roundup but no commercialTxAmount has been set\n checkout.options.donation?.onDonationFailure?.(error);\n }\n }\n\n /**\n * Returns the component payment data ready to submit to the Checkout API\n */\n get data() {\n return this.state.data;\n }\n\n /**\n * Returns whether the component state is valid or not\n */\n get isValid() {\n return this.state.isValid;\n }\n\n setState(newState) {\n this.state = { ...this.state, ...newState };\n }\n\n donate() {\n // Send analytics\n const event = new AnalyticsLogEvent({\n component: DonationElement.type,\n type: LogEventType.submit,\n subType: LogEventSubtype.donation,\n message: 'Making donation'\n });\n this.core.modules.analytics.sendAnalytics(event);\n\n // Call callback\n const { data, isValid } = this;\n this.props.onDonate({ data, isValid }, this);\n }\n\n cancel() {\n // Send analytics\n const event = new AnalyticsLogEvent({\n component: DonationElement.type,\n type: LogEventType.closed,\n subType: LogEventSubtype.donation,\n message: 'Opting to not make donation'\n });\n this.core.modules.analytics.sendAnalytics(event);\n\n // Call callback\n const { data, isValid } = this;\n\n // If running in service mode, unmount the component\n if (this.isInServiceMode) {\n this.unmount();\n }\n\n this.props.onCancel({ data, isValid });\n }\n\n amountSelected(state: DonationPayload) {\n // Send analytics\n const event = new AnalyticsInfoEvent({\n component: DonationElement.type,\n type: InfoEventType.selected,\n selectedValue: JSON.stringify(state.data.amount),\n target: UiTarget.donationAmountButton\n });\n this.core.modules.analytics.sendAnalytics(event);\n }\n\n protected override componentToRender(): h.JSX.Element {\n return (\n <DonationComponent\n {...this.props}\n // @ts-ignore ref is internal from the Component\n ref={ref => {\n this.componentRef = ref;\n }}\n onChange={this.setState}\n onDonate={this.donate}\n onCancel={this.cancel}\n onAmountSelected={this.amountSelected}\n />\n );\n }\n}\n\nexport default DonationElement;\n"],"names":["DonationElement","UIElement","isServiceMode","props","rootNode","initialiseServiceMode","checkout","session","sessionsDonationInitiated","console","error","REPARENT_WITHOUT_AUTO_START_ERROR_MSG","donationCampaign","DonationCampaignService","initialise","this","mount","options","donation","onDonationFailure","data","state","isValid","setState","newState","donate","event","AnalyticsLogEvent","component","type","LogEventType","submit","subType","LogEventSubtype","message","core","modules","analytics","sendAnalytics","onDonate","cancel","closed","isInServiceMode","unmount","onCancel","amountSelected","AnalyticsInfoEvent","InfoEventType","selected","selectedValue","JSON","stringify","amount","target","UiTarget","donationAmountButton","componentToRender","h","DonationComponent","ref","componentRef","onChange","onAmountSelected","constructor","super","undefined","_define_property","bind","TxVariants","defaultProps"],"mappings":"wqBAWA,MAAMA,UAAwBC,EA+B1B,oBAAeC,CAAcC,GACzB,MAAO,aAAcA,KAAWA,EAAMC,QAC1C,CAOA,2BAAcC,CAAsBC,EAAiBH,GACjD,GAAKG,EAASC,QAId,GAAID,EAASC,QAAQC,0BACjBC,QAAQC,MAAMC,OADlB,CAKAL,EAASC,QAAQC,2BAA4B,EAC7C,IACI,MAAMI,QAAyB,IAAIC,EAAwBP,EAAUH,GAAOW,aACxEF,IACAG,KAAKZ,MAAQ,IAAKY,KAAKZ,SAAUS,GACjCG,KAAKC,MAAMb,EAAMC,UAGzB,CAAE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/C,KAAK8B,gBAGnC,CA3IA,WAAAkB,CAAYzD,EAAiBH,GACzB,MAAMD,EAAgBF,EAAgBE,cAAcC,GAGpD6D,MAAM1D,EAFgBJ,OAAgB+D,EAAY9D,GAJtD+D,EAAAnD,KAAiB2B,mBAA2B,GAQxC3B,KAAKU,OAASV,KAAKU,OAAO0C,KAAKpD,MAC/BA,KAAKyB,OAASzB,KAAKyB,OAAO2B,KAAKpD,MAC/BA,KAAK8B,eAAiB9B,KAAK8B,eAAesB,KAAKpD,MAE/CA,KAAK2B,gBAAkBxC,EAEnBI,EAASC,SAAWL,GACfa,KAAKV,sBAAsBC,EAAUH,EAElD,EAnBA+D,EADElE,EACqB6B,OAAOuC,EAAWlD,UAkCzCgD,EAnCElE,EAmCqBqE,eAAe,CAClCzB,SAAU,OACVL,SAAU"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{AnalyticsLogEvent as n,LogEventSubtype as o,LogEventType as t}from"../../core/Analytics/events/AnalyticsLogEvent.js";function i(n,o,t){return o in n?Object.defineProperty(n,o,{value:t,enumerable:!0,configurable:!0,writable:!0}):n[o]=t,n}const a=3e3,e="Donation instantiation error:: You need to set donation.autoMount to false if you wish to display the Donation component in a different container.\nThe Donation component will be displayed in the default container.";class s{async initialise(){const[n]=await Promise.all([this.callSessionsDonationCampaigns(),new Promise(n=>setTimeout(n,this.delayMS))]);return n}async callSessionsDonationCampaigns(){const i=new n({component:s.type,type:t.apiRequest,subType:o.donationCampaigns,message:"Sessions flow: calling donationCampaigns endpoint"});this.core.modules.analytics.sendAnalytics(i);const a=await this.makeSessionsDonationCampaignsCall(),[e]=a?.donationCampaigns||[];return e?this.handleDonationCampaign(e):null}handleDonationCampaign(n){const{id:o,campaignName:t,...i}=n,a=i.donation.type,e={...i,onCancel:n=>{this.onDonationCompleted?.({didDonate:!1})},onDonate:(n,t)=>{const i={amount:n.data.amount,donationCampaignId:o,donationType:a};this.callSessionsDonations(i,t)},commercialTxAmount:this.commercialTxAmount};if("roundup"===a&&!this.commercialTxAmount)throw new Error('The donation type is "roundup" and the commercialTxAmount is not set.\nIt will not be possible to mount a Donation component.');return e}async callSessionsDonations(n,o){try{const t=await this.makeSessionDonationsCall(n);"Authorised"===t.resultCode?(o.setStatus("success"),this.onDonationCompleted?.({didDonate:!0})):(o.setStatus("error"),this.onDonationFailed?.(t.resultCode))}catch(n){o.setStatus("error"),this.onDonationFailed?.(n)}}async makeSessionsDonationCampaignsCall(){if(!this.core.session)throw new Error("DonationCampaignService requires a session to be configured");return await this.core.session.fetchDonationCampaigns()}async makeSessionDonationsCall(n){if(!this.core.session)throw new Error("DonationCampaignService requires a session to be configured");return await this.core.session.makeDonation(n)}constructor(n,o){i(this,"core",void 0),i(this,"commercialTxAmount",0),i(this,"onDonationCompleted",void 0),i(this,"onDonationFailed",void 0),i(this,"delayMS",void 0),this.core=n,this.onDonationCompleted=n.options.donation?.onDonationSuccess,this.onDonationFailed=n.options.donation?.onDonationFailure,this.commercialTxAmount=o.commercialTxAmount,this.delayMS=n.options.donation?.delay??3e3}}i(s,"type","donationCampaignService");export{a as DEFAULT_DONATION_AUTO_START_DELAY_MS,e as REPARENT_WITHOUT_AUTO_START_ERROR_MSG,s as default};
|
|
2
|
+
//# sourceMappingURL=DonationCampaignService.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"DonationCampaignService.js","sources":["../../../../src/components/Donation/DonationCampaignService.tsx"],"sourcesContent":["import type { ICore } from '../../core/types';\nimport { DonationCampaign, DonationConfiguration, DonationCampaignOptions } from './types';\nimport type { DonationPayload } from './components/types';\nimport type {\n CheckoutSessionDonationCampaignsResponse,\n CheckoutSessionDonationsRequestData,\n CheckoutSessionDonationsResponse\n} from '../../core/CheckoutSession/types';\nimport Donation from './Donation';\nimport { AnalyticsLogEvent, LogEventSubtype, LogEventType } from '../../core/Analytics/events/AnalyticsLogEvent';\n\nexport const DEFAULT_DONATION_AUTO_START_DELAY_MS = 3000;\n\nexport const REPARENT_WITHOUT_AUTO_START_ERROR_MSG =\n 'Donation instantiation error:: You need to set donation.autoMount to false if you wish to display the Donation component in a different container.\\nThe Donation component will be displayed in the default container.';\n\nclass DonationCampaignService {\n public static readonly type = 'donationCampaignService';\n\n private readonly core: ICore;\n\n private readonly commercialTxAmount: number = 0;\n private readonly onDonationCompleted?: (result: { didDonate: boolean }) => void;\n private readonly onDonationFailed?: (reason: unknown) => void;\n\n private readonly delayMS: number;\n\n constructor(checkout: ICore, donationCampaignProps: DonationCampaignOptions) {\n this.core = checkout;\n\n this.onDonationCompleted = checkout.options.donation?.onDonationSuccess;\n this.onDonationFailed = checkout.options.donation?.onDonationFailure;\n\n this.commercialTxAmount = donationCampaignProps.commercialTxAmount;\n\n this.delayMS = checkout.options.donation?.delay ?? DEFAULT_DONATION_AUTO_START_DELAY_MS;\n }\n\n public async initialise(): Promise<DonationConfiguration | null> {\n const [donationConfiguration] = await Promise.all([\n this.callSessionsDonationCampaigns(),\n new Promise(resolve => setTimeout(resolve, this.delayMS))\n ]);\n return donationConfiguration;\n }\n\n private async callSessionsDonationCampaigns(): Promise<DonationConfiguration | null> {\n // Send analytics\n const event = new AnalyticsLogEvent({\n component: DonationCampaignService.type,\n type: LogEventType.apiRequest,\n subType: LogEventSubtype.donationCampaigns,\n message: 'Sessions flow: calling donationCampaigns endpoint'\n });\n this.core.modules.analytics.sendAnalytics(event);\n\n const response: CheckoutSessionDonationCampaignsResponse = await this.makeSessionsDonationCampaignsCall();\n const [donationCampaign] = response?.donationCampaigns || [];\n return donationCampaign ? this.handleDonationCampaign(donationCampaign) : null;\n }\n\n private handleDonationCampaign(donationCampaign: DonationCampaign): DonationConfiguration {\n const { id, campaignName, ...restDonationCampaignProps } = donationCampaign;\n\n const donationType = restDonationCampaignProps.donation.type;\n\n const donationComponentProps: DonationConfiguration = {\n ...(restDonationCampaignProps as DonationConfiguration),\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n onCancel: (state: DonationPayload) => {\n // Call merchant defined onDonationCompleted callback\n this.onDonationCompleted?.({ didDonate: false });\n },\n onDonate: (state: DonationPayload, component: Donation) => {\n // Make the request\n const donationRequestData: CheckoutSessionDonationsRequestData = {\n amount: state.data.amount,\n donationCampaignId: id,\n donationType: donationType\n };\n\n void this.callSessionsDonations(donationRequestData, component);\n },\n commercialTxAmount: this.commercialTxAmount\n };\n\n if (donationType === 'roundup' && !this.commercialTxAmount) {\n // This error will be handled gracefully by the Donation component. The question remains whether we want analytics on this?\n throw new Error(\n 'The donation type is \"roundup\" and the commercialTxAmount is not set.\\nIt will not be possible to mount a Donation component.'\n );\n }\n\n return donationComponentProps;\n }\n\n private async callSessionsDonations(donationRequestData: CheckoutSessionDonationsRequestData, component: Donation): Promise<void> {\n try {\n const response: CheckoutSessionDonationsResponse = await this.makeSessionDonationsCall(donationRequestData);\n\n if (response.resultCode === 'Authorised') {\n component.setStatus('success');\n this.onDonationCompleted?.({ didDonate: true });\n } else {\n component.setStatus('error');\n this.onDonationFailed?.(response.resultCode);\n }\n } catch (error: unknown) {\n component.setStatus('error');\n this.onDonationFailed?.(error);\n }\n }\n\n private async makeSessionsDonationCampaignsCall(): Promise<CheckoutSessionDonationCampaignsResponse> {\n if (!this.core.session) {\n throw new Error('DonationCampaignService requires a session to be configured');\n }\n return await this.core.session.fetchDonationCampaigns();\n }\n\n private async makeSessionDonationsCall(donationRequestData: CheckoutSessionDonationsRequestData): Promise<CheckoutSessionDonationsResponse> {\n if (!this.core.session) {\n throw new Error('DonationCampaignService requires a session to be configured');\n }\n return await this.core.session.makeDonation(donationRequestData);\n }\n}\n\nexport default DonationCampaignService;\n"],"names":["DEFAULT_DONATION_AUTO_START_DELAY_MS","REPARENT_WITHOUT_AUTO_START_ERROR_MSG","DonationCampaignService","initialise","donationConfiguration","Promise","all","this","callSessionsDonationCampaigns","resolve","setTimeout","delayMS","event","AnalyticsLogEvent","component","type","LogEventType","apiRequest","subType","LogEventSubtype","donationCampaigns","message","core","modules","analytics","sendAnalytics","response","makeSessionsDonationCampaignsCall","donationCampaign","handleDonationCampaign","id","campaignName","restDonationCampaignProps","donationType","donation","donationComponentProps","onCancel","state","onDonationCompleted","didDonate","onDonate","donationRequestData","amount","data","donationCampaignId","callSessionsDonations","commercialTxAmount","Error","makeSessionDonationsCall","resultCode","setStatus","onDonationFailed","error","session","fetchDonationCampaigns","makeDonation","constructor","checkout","donationCampaignProps","_define_property","options","onDonationSuccess","onDonationFailure","delay"],"mappings":"oPAWO,MAAMA,EAAuC,IAEvCC,EACT,yNAEJ,MAAMC,EAsBF,gBAAaC,GACT,MAAOC,SAA+BC,QAAQC,IAAI,CAC9CC,KAAKC,gCACL,IAAIH,QAAQI,GAAWC,WAAWD,EAASF,KAAKI,YAEpD,OAAOP,CACX,CAEA,mCAAcI,GAEV,MAAMI,EAAQ,IAAIC,EAAkB,CAChCC,UAAWZ,EAAwBa,KACnCA,KAAMC,EAAaC,WACnBC,QAASC,EAAgBC,kBACzBC,QAAS,sDAEbd,KAAKe,KAAKC,QAAQC,UAAUC,cAAcb,GAE1C,MAAMc,QAA2DnB,KAAKoB,qCAC/DC,GAAoBF,GAAUN,mBAAqB,GAC1D,OAAOQ,EAAmBrB,KAAKsB,uBAAuBD,GAAoB,IAC9E,CAEQC,sBAAAA,CAAuBD,GAC3B,MAAME,GAAEA,EAAEC,aAAEA,KAAiBC,GAA8BJ,EAErDK,EAAeD,EAA0BE,SAASnB,KAElDoB,EAAgD,IAC9CH,EAGJI,SAAWC,IAEP9B,KAAK+B,sBAAsB,CAAEC,WAAW,KAE5CC,SAAU,CAACH,EAAwBvB,KAE/B,MAAM2B,EAA2D,CAC7DC,OAAQL,EAAMM,KAAKD,OACnBE,mBAAoBd,EACpBG,aAAcA,GAGb1B,KAAKsC,sBAAsBJ,EAAqB3B,IAEzDgC,mBAAoBvC,KAAKuC,oBAG7B,GAAqB,YAAjBb,IAA+B1B,KAAKuC,mBAEpC,MAAM,IAAIC,MACN,iIAIR,OAAOZ,CACX,CAEA,2BAAcU,CAAsBJ,EAA0D3B,GAC1F,IACI,MAAMY,QAAmDnB,KAAKyC,yBAAyBP,GAE3D,eAAxBf,EAASuB,YACTnC,EAAUoC,UAAU,WACpB3C,KAAK+B,sBAAsB,CAAEC,WAAW,MAExCzB,EAAUoC,UAAU,SACpB3C,KAAK4C,mBAAmBzB,EAASuB,YAEzC,CAAE,MAAOG,GACLtC,EAAUoC,UAAU,SACpB3C,KAAK4C,mBAAmBC,EAC5B,CACJ,CAEA,uCAAczB,GACV,IAAKpB,KAAKe,KAAK+B,QACX,MAAM,IAAIN,MAAM,+DAEpB,aAAaxC,KAAKe,KAAK+B,QAAQC,wBACnC,CAEA,8BAAcN,CAAyBP,GACnC,IAAKlC,KAAKe,KAAK+B,QACX,MAAM,IAAIN,MAAM,+DAEpB,aAAaxC,KAAKe,KAAK+B,QAAQE,aAAad,EAChD,CAnGA,WAAAe,CAAYC,EAAiBC,GAR7BC,EAAApD,KAAiBe,eAEjBqC,EAAApD,KAAiBuC,qBAA6B,GAC9Ca,EAAApD,KAAiB+B,8BACjBqB,EAAApD,KAAiB4C,2BAEjBQ,EAAApD,KAAiBI,kBAGbJ,KAAKe,KAAOmC,EAEZlD,KAAK+B,oBAAsBmB,EAASG,QAAQ1B,UAAU2B,kBACtDtD,KAAK4C,iBAAmBM,EAASG,QAAQ1B,UAAU4B,kBAEnDvD,KAAKuC,mBAAqBY,EAAsBZ,mBAEhDvC,KAAKI,QAAU8C,EAASG,QAAQ1B,UAAU6B,OAxBE,GAyBhD,EAnBAJ,EADEzD,EACqBa,OAAO"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createElement as e}from"../../../external/preact/dist/preact.js";import{useState as t,useEffect as o}from"../../../external/preact/hooks/dist/hooks.js";import n from"./CampaignContent.js";import a from"../../internal/Button/Button.js";import s from"../../internal/Img/Img.js";import{useCoreContext as r}from"../../../core/Context/CoreProvider.js";import
|
|
1
|
+
import{createElement as e}from"../../../external/preact/dist/preact.js";import{useState as t,useEffect as o}from"../../../external/preact/hooks/dist/hooks.js";import n from"./CampaignContent.js";import a from"../../internal/Button/Button.js";import s from"../../internal/Img/Img.js";import{useCoreContext as r}from"../../../core/Context/CoreProvider.js";import u from"../../internal/DisclaimerMessage/DisclaimerMessage.js";import c from"../../../core/Context/useImage.js";import i from"./FixedAmounts.js";import m from"./Roundup.js";import{getRoundupAmount as d,getAmountLabel as l,getRoundupAmountLabel as g}from"./utils.js";function _(_){const{donation:p,commercialTxAmount:y,onAmountSelected:h,onCancel:v,onDonate:k,showCancelButton:f=!0,termsAndConditionsUrl:C}=_,{i18n:x}=r(),A=c(),{currency:j,type:N}=p,B="roundup"===N,[D,S]=t("ready"),[w,F]=t(B),[I,R]=t({currency:j,value:B?d(p.maxRoundupAmount,y):null});this.setStatus=e=>{S(e)};const M=()=>{S("loading"),k({data:{amount:I}})};return o(()=>{_.onChange({data:{amount:I},isValid:w})},[I,w]),"error"===D?e("div",{className:"adyen-checkout__adyen-giving"},e(s,{className:"adyen-checkout__status__icon adyen-checkout__status__icon--error",src:A({imageFolder:"components/"})("error"),alt:x.get("error.message.unknown")}),e("div",{className:"adyen-checkout__status__text"},x.get("error.message.unknown"))):"success"===D?e("div",{className:"adyen-checkout__adyen-giving"},e(s,{className:"adyen-checkout__status__icon adyen-checkout__status__icon--success",src:A({imageFolder:"components/"})("heart"),alt:x.get("thanksForYourSupport")}),e("div",{className:"adyen-checkout__status__text"},x.get("thanksForYourSupport"))):e("div",{className:"adyen-checkout__adyen-giving"},e(n,_),e("div",{className:"adyen-checkout__adyen-giving-actions"},C&&e(u,{message:x.get("donationTermsCondition"),urls:[C]}),B?e(m,{donationAmount:g(x,{maxRoundupAmount:p.maxRoundupAmount,commercialTxAmount:y,currency:j}),originalPaymentAmount:l(x,{value:y,currency:j}),status:D,onDonateButtonClicked:M}):e(i,{selectedAmount:I.value,values:p.values,currency:j,status:D,onAmountSelected:({target:e})=>{const t=parseInt(e.value,10);F(!0),R(e=>({...e,value:t})),h({data:{amount:{...I,value:t}}})},onDonateButtonClicked:M}),f&&e(a,{classNameModifiers:["decline"],variant:"ghost",onClick:()=>{S("ready"),v({data:{amount:I},isValid:w})},disabled:"loading"===D,label:`${x.get("notNowButton")} ›`})))}_.defaultProps={onCancel:()=>{},onChange:()=>{},onDonate:()=>{},donation:{},showCancelButton:!0};export{_ as default};
|
|
2
2
|
//# sourceMappingURL=DonationComponent.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"DonationComponent.js","sources":["../../../../../src/components/Donation/components/DonationComponent.tsx"],"sourcesContent":["import { h } from 'preact';\nimport { useEffect, useState } from 'preact/hooks';\nimport CampaignContent from './CampaignContent';\nimport Button from '../../internal/Button';\nimport Img from '../../internal/Img';\nimport { useCoreContext } from '../../../core/Context/CoreProvider';\nimport '../Donation.scss';\nimport DisclaimerMessage from '../../internal/DisclaimerMessage';\nimport { DonationAmount, DonationComponentProps, Status } from './types';\nimport useImage from '../../../core/Context/useImage';\nimport FixedAmounts from './FixedAmounts';\nimport Roundup from './Roundup';\nimport { getAmountLabel, getRoundupAmount, getRoundupAmountLabel } from './utils';\n\nexport default function DonationComponent(props: Readonly<DonationComponentProps>) {\n const { donation, commercialTxAmount, onCancel, onDonate, showCancelButton = true, termsAndConditionsUrl } = props;\n const { i18n } = useCoreContext();\n const getImage = useImage();\n const { currency, type } = donation;\n const isRoundupDonation = type === 'roundup';\n const [status, setStatus] = useState<Status>('ready');\n const [isValid, setIsValid] = useState<boolean>(isRoundupDonation);\n const [amount, setAmount] = useState<DonationAmount>({\n currency,\n value: isRoundupDonation ? getRoundupAmount(donation.maxRoundupAmount, commercialTxAmount) : null\n });\n\n this.setStatus = (status: Status) => {\n setStatus(status);\n };\n\n const handleAmountSelected = ({ target }) => {\n const value = parseInt(target.value, 10);\n setIsValid(true);\n setAmount((amount: DonationAmount) => ({ ...amount, value }));\n };\n\n const handleDonate = () => {\n setStatus('loading');\n onDonate({ data: { amount } });\n };\n\n const handleDecline = () => {\n setStatus('ready');\n onCancel({ data: { amount }, isValid });\n };\n\n useEffect(() => {\n props.onChange({ data: { amount }, isValid });\n }, [amount, isValid]);\n\n if (status === 'error') {\n return (\n <div className=\"adyen-checkout__adyen-giving\">\n <Img\n className=\"adyen-checkout__status__icon adyen-checkout__status__icon--error\"\n src={getImage({ imageFolder: 'components/' })('error')}\n alt={i18n.get('error.message.unknown')}\n />\n <div className=\"adyen-checkout__status__text\">{i18n.get('error.message.unknown')}</div>\n </div>\n );\n }\n\n if (status === 'success') {\n return (\n <div className=\"adyen-checkout__adyen-giving\">\n <Img\n className=\"adyen-checkout__status__icon adyen-checkout__status__icon--success\"\n src={getImage({ imageFolder: 'components/' })('heart')}\n alt={i18n.get('thanksForYourSupport')}\n />\n\n <div className=\"adyen-checkout__status__text\">{i18n.get('thanksForYourSupport')}</div>\n </div>\n );\n }\n\n return (\n <div className=\"adyen-checkout__adyen-giving\">\n <CampaignContent {...props} />\n\n <div className=\"adyen-checkout__adyen-giving-actions\">\n {termsAndConditionsUrl && <DisclaimerMessage message={i18n.get('donationTermsCondition')} urls={[termsAndConditionsUrl]} />}\n {isRoundupDonation ? (\n <Roundup\n donationAmount={getRoundupAmountLabel(i18n, { maxRoundupAmount: donation.maxRoundupAmount, commercialTxAmount, currency })}\n originalPaymentAmount={getAmountLabel(i18n, { value: commercialTxAmount, currency })}\n status={status}\n onDonateButtonClicked={handleDonate}\n ></Roundup>\n ) : (\n <FixedAmounts\n selectedAmount={amount.value}\n values={donation.values}\n currency={currency}\n status={status}\n onAmountSelected={handleAmountSelected}\n onDonateButtonClicked={handleDonate}\n ></FixedAmounts>\n )}\n {showCancelButton && (\n <Button\n classNameModifiers={['decline']}\n variant=\"ghost\"\n onClick={handleDecline}\n disabled={status === 'loading'}\n label={`${i18n.get('notNowButton')} ›`}\n />\n )}\n </div>\n </div>\n );\n}\n\nDonationComponent.defaultProps = {\n onCancel: () => {},\n onChange: () => {},\n onDonate: () => {},\n donation: {},\n showCancelButton: true\n};\n"],"names":["DonationComponent","props","donation","commercialTxAmount","onCancel","onDonate","showCancelButton","termsAndConditionsUrl","i18n","useCoreContext","getImage","useImage","currency","type","isRoundupDonation","status","setStatus","useState","isValid","setIsValid","amount","setAmount","value","getRoundupAmount","maxRoundupAmount","this","handleDonate","data","useEffect","onChange","h","div","className","Img","src","imageFolder","alt","get","CampaignContent","DisclaimerMessage","message","urls","Roundup","donationAmount","getRoundupAmountLabel","originalPaymentAmount","getAmountLabel","onDonateButtonClicked","FixedAmounts","selectedAmount","values","
|
|
1
|
+
{"version":3,"file":"DonationComponent.js","sources":["../../../../../src/components/Donation/components/DonationComponent.tsx"],"sourcesContent":["import { h } from 'preact';\nimport { useEffect, useState } from 'preact/hooks';\nimport CampaignContent from './CampaignContent';\nimport Button from '../../internal/Button';\nimport Img from '../../internal/Img';\nimport { useCoreContext } from '../../../core/Context/CoreProvider';\nimport '../Donation.scss';\nimport DisclaimerMessage from '../../internal/DisclaimerMessage';\nimport { DonationAmount, DonationComponentProps, Status } from './types';\nimport useImage from '../../../core/Context/useImage';\nimport FixedAmounts from './FixedAmounts';\nimport Roundup from './Roundup';\nimport { getAmountLabel, getRoundupAmount, getRoundupAmountLabel } from './utils';\n\nexport default function DonationComponent(props: Readonly<DonationComponentProps>) {\n const { donation, commercialTxAmount, onAmountSelected, onCancel, onDonate, showCancelButton = true, termsAndConditionsUrl } = props;\n const { i18n } = useCoreContext();\n const getImage = useImage();\n const { currency, type } = donation;\n const isRoundupDonation = type === 'roundup';\n const [status, setStatus] = useState<Status>('ready');\n const [isValid, setIsValid] = useState<boolean>(isRoundupDonation);\n const [amount, setAmount] = useState<DonationAmount>({\n currency,\n value: isRoundupDonation ? getRoundupAmount(donation.maxRoundupAmount, commercialTxAmount) : null\n });\n\n this.setStatus = (status: Status) => {\n setStatus(status);\n };\n\n const handleAmountSelected = ({ target }) => {\n const value = parseInt(target.value, 10);\n setIsValid(true);\n setAmount((amount: DonationAmount) => ({ ...amount, value }));\n\n onAmountSelected({ data: { amount: { ...amount, value } } });\n };\n\n const handleDonate = () => {\n setStatus('loading');\n onDonate({ data: { amount } });\n };\n\n const handleDecline = () => {\n setStatus('ready');\n onCancel({ data: { amount }, isValid });\n };\n\n useEffect(() => {\n props.onChange({ data: { amount }, isValid });\n }, [amount, isValid]);\n\n if (status === 'error') {\n return (\n <div className=\"adyen-checkout__adyen-giving\">\n <Img\n className=\"adyen-checkout__status__icon adyen-checkout__status__icon--error\"\n src={getImage({ imageFolder: 'components/' })('error')}\n alt={i18n.get('error.message.unknown')}\n />\n <div className=\"adyen-checkout__status__text\">{i18n.get('error.message.unknown')}</div>\n </div>\n );\n }\n\n if (status === 'success') {\n return (\n <div className=\"adyen-checkout__adyen-giving\">\n <Img\n className=\"adyen-checkout__status__icon adyen-checkout__status__icon--success\"\n src={getImage({ imageFolder: 'components/' })('heart')}\n alt={i18n.get('thanksForYourSupport')}\n />\n\n <div className=\"adyen-checkout__status__text\">{i18n.get('thanksForYourSupport')}</div>\n </div>\n );\n }\n\n return (\n <div className=\"adyen-checkout__adyen-giving\">\n <CampaignContent {...props} />\n\n <div className=\"adyen-checkout__adyen-giving-actions\">\n {termsAndConditionsUrl && <DisclaimerMessage message={i18n.get('donationTermsCondition')} urls={[termsAndConditionsUrl]} />}\n {isRoundupDonation ? (\n <Roundup\n donationAmount={getRoundupAmountLabel(i18n, { maxRoundupAmount: donation.maxRoundupAmount, commercialTxAmount, currency })}\n originalPaymentAmount={getAmountLabel(i18n, { value: commercialTxAmount, currency })}\n status={status}\n onDonateButtonClicked={handleDonate}\n ></Roundup>\n ) : (\n <FixedAmounts\n selectedAmount={amount.value}\n values={donation.values}\n currency={currency}\n status={status}\n onAmountSelected={handleAmountSelected}\n onDonateButtonClicked={handleDonate}\n ></FixedAmounts>\n )}\n {showCancelButton && (\n <Button\n classNameModifiers={['decline']}\n variant=\"ghost\"\n onClick={handleDecline}\n disabled={status === 'loading'}\n label={`${i18n.get('notNowButton')} ›`}\n />\n )}\n </div>\n </div>\n );\n}\n\nDonationComponent.defaultProps = {\n onCancel: () => {},\n onChange: () => {},\n onDonate: () => {},\n donation: {},\n showCancelButton: true\n};\n"],"names":["DonationComponent","props","donation","commercialTxAmount","onAmountSelected","onCancel","onDonate","showCancelButton","termsAndConditionsUrl","i18n","useCoreContext","getImage","useImage","currency","type","isRoundupDonation","status","setStatus","useState","isValid","setIsValid","amount","setAmount","value","getRoundupAmount","maxRoundupAmount","this","handleDonate","data","useEffect","onChange","h","div","className","Img","src","imageFolder","alt","get","CampaignContent","DisclaimerMessage","message","urls","Roundup","donationAmount","getRoundupAmountLabel","originalPaymentAmount","getAmountLabel","onDonateButtonClicked","FixedAmounts","selectedAmount","values","target","parseInt","Button","classNameModifiers","variant","onClick","disabled","label","defaultProps"],"mappings":"knBAce,SAASA,EAAkBC,GACtC,MAAMC,SAAEA,EAAQC,mBAAEA,EAAkBC,iBAAEA,EAAgBC,SAAEA,EAAQC,SAAEA,EAAQC,iBAAEA,GAAmB,EAAIC,sBAAEA,GAA0BP,GACzHQ,KAAEA,GAASC,IACXC,EAAWC,KACXC,SAAEA,EAAQC,KAAEA,GAASZ,EACrBa,EAA6B,YAATD,GACnBE,EAAQC,GAAaC,EAAiB,UACtCC,EAASC,GAAcF,EAAkBH,IACzCM,EAAQC,GAAaJ,EAAyB,CACjDL,WACAU,MAAOR,EAAoBS,EAAiBtB,EAASuB,iBAAkBtB,GAAsB,OAGjGuB,KAAKT,UAAaD,IACdC,EAAUD,IAGd,MAQMW,EAAe,KACjBV,EAAU,WACVX,EAAS,CAAEsB,KAAM,CAAEP,aAYvB,OAJAQ,EAAU,KACN5B,EAAM6B,SAAS,CAAEF,KAAM,CAAEP,UAAUF,aACpC,CAACE,EAAQF,IAEG,UAAXH,EAEIe,EAACC,MAAAA,CAAIC,UAAU,gCACXF,EAACG,EAAAA,CACGD,UAAU,mEACVE,IAAKxB,EAAS,CAAEyB,YAAa,eAAxBzB,CAAyC,SAC9C0B,IAAK5B,EAAK6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,OACVJ,SAAU,CAAA,EACVK,kBAAkB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","sources":["../../../../../src/components/Donation/components/utils.ts"],"sourcesContent":["import Language from '../../../language';\nimport { DonationAmount } from './types';\n\ninterface RoundupAmount {\n maxRoundupAmount: number;\n commercialTxAmount: number;\n currency: string;\n}\n\nconst getRoundupAmount = (maxRoundupAmount: number, commercialTxAmount: number) => maxRoundupAmount - (commercialTxAmount % maxRoundupAmount);\n\nconst getAmountLabel = (i18n: Language, { value, currency }: DonationAmount) => i18n.amount(value, currency);\n\nconst getRoundupAmountLabel = (i18n: Language, { maxRoundupAmount, commercialTxAmount, currency }: RoundupAmount) =>\n getAmountLabel(i18n, { value: getRoundupAmount(maxRoundupAmount, commercialTxAmount), currency });\n\nexport { getAmountLabel, getRoundupAmount, getRoundupAmountLabel };\n"],"names":["getRoundupAmount","maxRoundupAmount","commercialTxAmount","getAmountLabel","i18n","value","currency","amount","getRoundupAmountLabel"],"mappings":"AASA,MAAMA,EAAmB,CAACC,EAA0BC,IAA+BD,EAAoBC,EAAqBD,EAEtHE,EAAiB,CAACC,GAAkBC,QAAOC,cAA+BF,EAAKG,OAAOF,EAAOC,GAE7FE,EAAwB,CAACJ,GAAkBH,mBAAkBC,qBAAoBI,cACnFH,EAAeC,EAAM,CAAEC,MAAOL,EAAiBC,EAAkBC,GAAqBI"}
|
|
1
|
+
{"version":3,"file":"utils.js","sources":["../../../../../src/components/Donation/components/utils.ts"],"sourcesContent":["import Language from '../../../language';\nimport type { DonationAmount } from './types';\n\ninterface RoundupAmount {\n maxRoundupAmount: number;\n commercialTxAmount: number;\n currency: string;\n}\n\nconst getRoundupAmount = (maxRoundupAmount: number, commercialTxAmount: number) => maxRoundupAmount - (commercialTxAmount % maxRoundupAmount);\n\nconst getAmountLabel = (i18n: Language, { value, currency }: DonationAmount) => i18n.amount(value, currency);\n\nconst getRoundupAmountLabel = (i18n: Language, { maxRoundupAmount, commercialTxAmount, currency }: RoundupAmount) =>\n getAmountLabel(i18n, { value: getRoundupAmount(maxRoundupAmount, commercialTxAmount), currency });\n\nexport { getAmountLabel, getRoundupAmount, getRoundupAmountLabel };\n"],"names":["getRoundupAmount","maxRoundupAmount","commercialTxAmount","getAmountLabel","i18n","value","currency","amount","getRoundupAmountLabel"],"mappings":"AASA,MAAMA,EAAmB,CAACC,EAA0BC,IAA+BD,EAAoBC,EAAqBD,EAEtHE,EAAiB,CAACC,GAAkBC,QAAOC,cAA+BF,EAAKG,OAAOF,EAAOC,GAE7FE,EAAwB,CAACJ,GAAkBH,mBAAkBC,qBAAoBI,cACnFH,EAAeC,EAAM,CAAEC,MAAOL,EAAiBC,EAAkBC,GAAqBI"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createElement as t}from"../../external/preact/dist/preact.js";import
|
|
1
|
+
import{createElement as t}from"../../external/preact/dist/preact.js";import e from"../../utils/isMobile.js";import o from"../helpers/IssuerListContainer/IssuerListContainer.js";import{QRLoader as r}from"../internal/QRLoader/QRLoader.js";import"../../core/Context/CoreProvider.js";import"../../external/preact/hooks/dist/hooks.js";import"../../core/Errors/SRPanelContext.js";import"../internal/Button/Button.js";import"../internal/QRLoader/QRLoaderDetailsProvider.js";import{TxVariants as s}from"../tx-variants.js";import i from"./components/IrisComponent.js";import{IrisQrCodeInstructions as n}from"./components/IrisQrCodeInstructions.js";import{IrisMode as a}from"./types.js";import{DEFAULT_IRIS_COUNTDOWN_TIME as p}from"./constants.js";function d(t,e,o){return e in t?Object.defineProperty(t,e,{value:o,enumerable:!0,configurable:!0,writable:!0}):t[e]=o,t}class m extends o{renderIssuerList(){return super.componentToRender()}formatData(){return this.state.mode===a.BANK_LIST?{paymentMethod:{type:this.type,issuer:this.state?.data?.issuer}}:{paymentMethod:{type:this.type}}}formatProps(t){return{...super.formatProps(t),countdownTime:t.countdownTime??p}}get isValid(){return this.state.mode!==a.BANK_LIST||super.isValid}componentToRender(){return"qrCode"===this.props.type?t(r,{type:s.iris,brandLogo:this.icon,clientKey:this.props.clientKey,qrCodeData:this.props.qrCodeData?encodeURIComponent(this.props.qrCodeData):void 0,countdownTime:this.props.countdownTime,paymentData:this.props.paymentData,delay:this.props.delay,onActionHandled:this.onActionHandled,onError:this.props.onError,onComplete:this.onComplete,introduction:n,showAmount:!0,copyBtn:!1}):t(i,{setComponentRef:this.setComponentRef,defaultMode:this.defaultMode,onUpdateMode:t=>{this.setState({mode:t})},issuerListUI:this.renderIssuerList(),showPayButton:this.props.showPayButton,payButton:this.payButton,issuers:this.props.issuers||[]})}constructor(...t){super(...t),d(this,"defaultMode",e()?a.BANK_LIST:a.QR_CODE),d(this,"state",{isValid:this.defaultMode===a.QR_CODE,mode:this.defaultMode,data:{}})}}d(m,"type",s.iris);export{m as Iris,m as default};
|
|
2
2
|
//# sourceMappingURL=Iris.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Iris.js","sources":["../../../../src/components/Iris/Iris.tsx"],"sourcesContent":["import { h } from 'preact';\nimport
|
|
1
|
+
{"version":3,"file":"Iris.js","sources":["../../../../src/components/Iris/Iris.tsx"],"sourcesContent":["import { h } from 'preact';\nimport isMobile from '../../utils/isMobile';\nimport IssuerListContainer from '../helpers/IssuerListContainer/IssuerListContainer';\nimport { QRLoader } from '../internal/QRLoader';\nimport { TxVariants } from '../tx-variants';\nimport IrisComponent from './components/IrisComponent';\nimport { IrisQrCodeInstructions } from './components/IrisQrCodeInstructions';\nimport { IrisConfiguration, IrisData, IrisMode, IrisState } from './types';\nimport { DEFAULT_IRIS_COUNTDOWN_TIME } from './constants';\n\nexport class Iris extends IssuerListContainer<IrisConfiguration, IrisData> {\n public static readonly type = TxVariants.iris;\n\n private readonly defaultMode = isMobile() ? IrisMode.BANK_LIST : IrisMode.QR_CODE;\n\n public state: IrisState = {\n isValid: this.defaultMode === IrisMode.QR_CODE,\n mode: this.defaultMode,\n data: {}\n };\n\n private renderIssuerList(): h.JSX.Element {\n return super.componentToRender();\n }\n\n formatData(): IrisData {\n if (this.state.mode === IrisMode.BANK_LIST) {\n return {\n paymentMethod: {\n type: this.type,\n issuer: this.state?.data?.issuer\n }\n };\n }\n\n return {\n paymentMethod: {\n type: this.type\n }\n };\n }\n\n formatProps(props: IrisConfiguration): IrisConfiguration {\n return {\n ...super.formatProps(props),\n countdownTime: props.countdownTime ?? DEFAULT_IRIS_COUNTDOWN_TIME\n };\n }\n\n get isValid() {\n if (this.state.mode === IrisMode.BANK_LIST) {\n return super.isValid;\n }\n\n return true;\n }\n\n protected override componentToRender(): h.JSX.Element {\n if (this.props.type === 'qrCode') {\n return (\n <QRLoader\n type={TxVariants.iris}\n brandLogo={this.icon}\n clientKey={this.props.clientKey}\n qrCodeData={this.props.qrCodeData ? encodeURIComponent(this.props.qrCodeData) : undefined}\n countdownTime={this.props.countdownTime}\n paymentData={this.props.paymentData}\n delay={this.props.delay}\n onActionHandled={this.onActionHandled}\n onError={this.props.onError}\n onComplete={this.onComplete}\n introduction={IrisQrCodeInstructions}\n showAmount\n copyBtn={false}\n />\n );\n }\n\n return (\n <IrisComponent\n setComponentRef={this.setComponentRef}\n defaultMode={this.defaultMode}\n onUpdateMode={mode => {\n this.setState({ mode });\n }}\n issuerListUI={this.renderIssuerList()}\n showPayButton={this.props.showPayButton}\n payButton={this.payButton}\n issuers={this.props.issuers || []}\n />\n );\n }\n}\n\nexport default Iris;\n"],"names":["Iris","IssuerListContainer","renderIssuerList","super","componentToRender","formatData","this","state","mode","IrisMode","BANK_LIST","paymentMethod","type","issuer","data","formatProps","props","countdownTime","DEFAULT_IRIS_COUNTDOWN_TIME","isValid","h","QRLoader","TxVariants","iris","brandLogo","icon","clientKey","qrCodeData","encodeURIComponent","undefined","paymentData","delay","onActionHandled","onError","onComplete","introduction","IrisQrCodeInstructions","showAmount","copyBtn","IrisComponent","setComponentRef","defaultMode","onUpdateMode","setState","issuerListUI","showPayButton","payButton","issuers","args","_define_property","isMobile","QR_CODE"],"mappings":"01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vC3C,KAAMF,KAAKmC,YACX3B,KAAM,CAAA,KAPVmC,EADSjD,EACcY,OAAOU,EAAWC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sources":["../../../../src/components/Iris/types.ts"],"sourcesContent":["import { IssuerListConfiguration, QRLoaderConfiguration } from '../types';\n\nexport type IrisConfiguration = IssuerListConfiguration & Pick<QRLoaderConfiguration, 'countdownTime' | 'qrCodeData' | 'paymentData' | 'delay'>;\n\n/**\n * Iris data format for /payment request\n * @internal\n */\nexport interface IrisData {\n paymentMethod: {\n type: string;\n issuer?: string;\n };\n}\n\n/**\n * Iris component display modes\n * @internal\n */\nexport enum IrisMode {\n QR_CODE = 'qrCode',\n BANK_LIST = 'bankList'\n}\n"],"names":["IrisMode"],"mappings":"AAmBO,IAAKA,EAAAA,SAAAA,GAAAA,iDAAAA,CAGX,CAHWA,CAGX,CAAA"}
|
|
1
|
+
{"version":3,"file":"types.js","sources":["../../../../src/components/Iris/types.ts"],"sourcesContent":["import { IssuerListConfiguration, QRLoaderConfiguration } from '../types';\n\nexport type IrisConfiguration = IssuerListConfiguration & Pick<QRLoaderConfiguration, 'countdownTime' | 'qrCodeData' | 'paymentData' | 'delay'>;\n\n/**\n * Iris data format for /payment request\n * @internal\n */\nexport interface IrisData {\n paymentMethod: {\n type: string;\n issuer?: string;\n };\n}\n\n/**\n * Iris component display modes\n * @internal\n */\nexport enum IrisMode {\n QR_CODE = 'qrCode',\n BANK_LIST = 'bankList'\n}\n\n/**\n * Iris component state\n * @internal\n */\nexport type IrisState = {\n isValid: boolean;\n mode: IrisMode;\n data: {\n issuer?: string;\n };\n};\n"],"names":["IrisMode"],"mappings":"AAmBO,IAAKA,EAAAA,SAAAA,GAAAA,iDAAAA,CAGX,CAHWA,CAGX,CAAA"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createElement as t}from"../../../../external/preact/dist/preact.js";import{useRef as e,useState as n,useEffect as a}from"../../../../external/preact/hooks/dist/hooks.js";import{useCoreContext as o}from"../../../../core/Context/CoreProvider.js";import i from"../../../internal/IssuerList/IssuerList.js";import{useIssuerWithLogo as s}from"./useIssuerWithLogo.js";import r from"./getEnrollmentStatus.js";import l from"./components/IssuerListIntroduction.js";import m from"./components/PayByBankPixAwait.js";import p from"../../../../core/Context/useImage.js";import{LabelOnlyDisclaimerMessage as c}from"../../../internal/DisclaimerMessage/DisclaimerMessage.js";import{TxVariants as u}from"../../../tx-variants.js";function y(y){const{i18n:d,loadingContext:b}=o(),g=p(),w=e(null),[x,f]=n(null),k=[{name:"open-finance",alt:d.get("paybybankpix.await.logoAlt.openFinance"),src:`${g({parentFolder
|
|
1
|
+
import{createElement as t}from"../../../../external/preact/dist/preact.js";import{useRef as e,useState as n,useEffect as a}from"../../../../external/preact/hooks/dist/hooks.js";import{useCoreContext as o}from"../../../../core/Context/CoreProvider.js";import i from"../../../internal/IssuerList/IssuerList.js";import{useIssuerWithLogo as s}from"./useIssuerWithLogo.js";import r from"./getEnrollmentStatus.js";import l from"./components/IssuerListIntroduction.js";import m from"./components/PayByBankPixAwait.js";import p from"../../../../core/Context/useImage.js";import{LabelOnlyDisclaimerMessage as c}from"../../../internal/DisclaimerMessage/DisclaimerMessage.js";import{TxVariants as u}from"../../../tx-variants.js";function y(y){const{i18n:d,loadingContext:b}=o(),g=p(),w=e(null),[x,f]=n(null),k=[{name:"open-finance",alt:d.get("paybybankpix.await.logoAlt.openFinance"),src:`${g({parentFolder:y.txVariant})("open-finance")}`},{name:"arrow-down",alt:d.get("paybybankpix.await.logoAlt.arrowDown"),src:`${g({imageFolder:"components/"})("arrow_down")}`},{name:"bank",alt:d.get("paybybankpix.await.logoAlt.bank"),src:`${g({imageFolder:"components/"})("bank")}`}],h=e({showValidation:()=>{w?.current?.showValidation()},setStatus:t=>{w?.current?.setStatus(t)}});return a(()=>{y.setComponentRef(h.current)},[y.setComponentRef]),a(()=>{x&&y.onEnroll(x)},[x]),t("div",{className:"adyen-checkout-pix-enrollment"},(t=>"await"===t.type)(y)?t(m,{logos:k,type:y.txVariant,countdownTime:y.countdownTime,clientKey:y.clientKey,onError:y.onError,awaitText:d.get("paybybankpix.await.waitForConfirmation"),instructions:d.get("paybybankpix.await.timeToPay",{values:{numberOfMin:y.countdownTime}}),pollStatus:async()=>{if(x)return;const{enrollmentId:t,clientKey:e}=y,n=await r({enrollmentId:t,clientKey:e,loadingContext:b});return n.registrationOptions&&f(n.registrationOptions),n},endSlot:()=>t("span",null,d.get("paybybankpix.await.withOpenFinance"))}):t("div",{className:"adyen-checkout-pix-enrollment-issuer-list"},t(l,{txVariant:y.txVariant}),t(i,{items:s({issuers:y.issuers,txVariant:y.txVariant}),selectFieldLabel:d.get("paybybankpix.issuerList.selectField.label"),onSubmitAnalytics:y.onSubmitAnalytics,onChange:y.onChange,payButton:y.payButton,showPayButton:!0,setComponentRef:t=>{w.current=t},type:u.paybybank_pix}),t("span",{className:"adyen-checkout-disclaimer__label"},t(c,{message:d.get("paybybankpix.issuerList.disclaimer"),urls:["https://www.adyen.com/pt_BR/legal/termo-de-consentimento-br"]}))))}export{y as default};
|
|
2
2
|
//# sourceMappingURL=Enrollment.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Enrollment.js","sources":["../../../../../../src/components/PayByBankPix/components/Enrollment/Enrollment.tsx"],"sourcesContent":["import { h } from 'preact';\nimport { useRef, useState, useEffect } from 'preact/hooks';\nimport { AwaitProps, EnrollmentProps } from './types';\nimport { useCoreContext } from '../../../../core/Context/CoreProvider';\nimport IssuerList from '../../../internal/IssuerList';\nimport { useIssuerWithLogo } from './useIssuerWithLogo';\nimport getEnrollmentStatus from './getEnrollmentStatus';\nimport IssuerListIntroduction from './components/IssuerListIntroduction';\nimport PayByBankPixAwait from './components/PayByBankPixAwait';\nimport useImage from '../../../../core/Context/useImage';\nimport './Enrollment.scss';\nimport { LabelOnlyDisclaimerMessage } from '../../../internal/DisclaimerMessage/DisclaimerMessage';\nimport { ComponentMethodsRef, UIElementStatus } from '../../../internal/UIElement/types';\nimport { TxVariants } from '../../../tx-variants';\n\nconst TERMS_CONDITIONS_URL = 'https://www.adyen.com/pt_BR/legal/termo-de-consentimento-br';\n\nfunction Enrollment(props: Readonly<EnrollmentProps>) {\n const { i18n, loadingContext } = useCoreContext();\n const getImage = useImage();\n const issuerListRef = useRef<ComponentMethodsRef>(null);\n const [registrationOptions, setRegistrationOptions] = useState<string>(null);\n const logos = [\n {\n name: 'open-finance',\n alt: i18n.get('paybybankpix.await.logoAlt.openFinance'),\n src: `${getImage({ parentFolder:
|
|
1
|
+
{"version":3,"file":"Enrollment.js","sources":["../../../../../../src/components/PayByBankPix/components/Enrollment/Enrollment.tsx"],"sourcesContent":["import { h } from 'preact';\nimport { useRef, useState, useEffect } from 'preact/hooks';\nimport { AwaitProps, EnrollmentProps } from './types';\nimport { useCoreContext } from '../../../../core/Context/CoreProvider';\nimport IssuerList from '../../../internal/IssuerList';\nimport { useIssuerWithLogo } from './useIssuerWithLogo';\nimport getEnrollmentStatus from './getEnrollmentStatus';\nimport IssuerListIntroduction from './components/IssuerListIntroduction';\nimport PayByBankPixAwait from './components/PayByBankPixAwait';\nimport useImage from '../../../../core/Context/useImage';\nimport './Enrollment.scss';\nimport { LabelOnlyDisclaimerMessage } from '../../../internal/DisclaimerMessage/DisclaimerMessage';\nimport { ComponentMethodsRef, UIElementStatus } from '../../../internal/UIElement/types';\nimport { TxVariants } from '../../../tx-variants';\n\nconst TERMS_CONDITIONS_URL = 'https://www.adyen.com/pt_BR/legal/termo-de-consentimento-br';\n\nfunction Enrollment(props: Readonly<EnrollmentProps>) {\n const { i18n, loadingContext } = useCoreContext();\n const getImage = useImage();\n const issuerListRef = useRef<ComponentMethodsRef | null>(null);\n const [registrationOptions, setRegistrationOptions] = useState<string>(null);\n const logos = [\n {\n name: 'open-finance',\n alt: i18n.get('paybybankpix.await.logoAlt.openFinance'),\n src: `${getImage({ parentFolder: props.txVariant })('open-finance')}`\n },\n {\n name: 'arrow-down',\n alt: i18n.get('paybybankpix.await.logoAlt.arrowDown'),\n src: `${getImage({ imageFolder: 'components/' })('arrow_down')}`\n },\n { name: 'bank', alt: i18n.get('paybybankpix.await.logoAlt.bank'), src: `${getImage({ imageFolder: 'components/' })('bank')}` }\n ];\n const self = useRef({\n showValidation: () => {\n issuerListRef?.current?.showValidation();\n },\n setStatus: (newStatus: UIElementStatus) => {\n issuerListRef?.current?.setStatus(newStatus);\n }\n });\n\n const pollStatus = async () => {\n if (registrationOptions) return;\n\n const { enrollmentId, clientKey } = props as AwaitProps;\n const response = await getEnrollmentStatus({ enrollmentId, clientKey, loadingContext });\n if (response.registrationOptions) {\n setRegistrationOptions(response.registrationOptions);\n }\n return response;\n };\n // Assist typescript to narrow down the type.\n const isAwait = (props: EnrollmentProps): props is AwaitProps => props.type === 'await';\n const awaitEndSlot = () => <span>{i18n.get('paybybankpix.await.withOpenFinance')}</span>;\n\n useEffect(() => {\n props.setComponentRef(self.current);\n }, [props.setComponentRef]);\n\n useEffect(() => {\n if (registrationOptions) {\n props.onEnroll(registrationOptions);\n }\n }, [registrationOptions]);\n\n return (\n <div className={'adyen-checkout-pix-enrollment'}>\n {isAwait(props) ? (\n <PayByBankPixAwait\n logos={logos}\n type={props.txVariant}\n countdownTime={props.countdownTime}\n clientKey={props.clientKey}\n onError={props.onError}\n awaitText={i18n.get('paybybankpix.await.waitForConfirmation')}\n instructions={i18n.get('paybybankpix.await.timeToPay', {\n values: { numberOfMin: props.countdownTime }\n })}\n pollStatus={pollStatus}\n endSlot={awaitEndSlot}\n ></PayByBankPixAwait>\n ) : (\n <div className=\"adyen-checkout-pix-enrollment-issuer-list\">\n <IssuerListIntroduction txVariant={props.txVariant} />\n <IssuerList\n items={useIssuerWithLogo({ issuers: props.issuers, txVariant: props.txVariant })}\n selectFieldLabel={i18n.get('paybybankpix.issuerList.selectField.label')}\n onSubmitAnalytics={props.onSubmitAnalytics}\n onChange={props.onChange}\n payButton={props.payButton}\n showPayButton={true}\n setComponentRef={ref => {\n issuerListRef.current = ref;\n }}\n type={TxVariants.paybybank_pix}\n ></IssuerList>\n <span className=\"adyen-checkout-disclaimer__label\">\n <LabelOnlyDisclaimerMessage message={i18n.get('paybybankpix.issuerList.disclaimer')} urls={[TERMS_CONDITIONS_URL]} />\n </span>\n </div>\n )}\n </div>\n );\n}\n\nexport default Enrollment;\n"],"names":["Enrollment","props","i18n","loadingContext","useCoreContext","getImage","useImage","issuerListRef","useRef","registrationOptions","setRegistrationOptions","useState","logos","name","alt","get","src","parentFolder","txVariant","imageFolder","self","showValidation","current","setStatus","newStatus","useEffect","setComponentRef","onEnroll","h","div","className","type","isAwait","PayByBankPixAwait","countdownTime","clientKey","onError","awaitText","instructions","values","numberOfMin","pollStatus","async","enrollmentId","response","getEnrollmentStatus","endSlot","span","IssuerListIntroduction","IssuerList","items","useIssuerWithLogo","issuers","selectFieldLabel","onSubmitAnalytics","onChange","payButton","showPayButton","ref","TxVariants","paybybank_pix","LabelOnlyDisclaimerMessage","message","urls"],"mappings":"8sBAiBA,SAASA,EAAWC,GAChB,MAAMC,KAAEA,EAAIC,eAAEA,GAAmBC,IAC3BC,EAAWC,IACXC,EAAgBC,EAAmC,OAClDC,EAAqBC,GAA0BC,EAAiB,MACjEC,EAAQ,CACV,CACIC,KAAM,eACNC,IAAKZ,EAAKa,IAAI,0CACdC,IAAK,GAAGX,EAAS,CAAEY,aAAchB,EAAMiB,WAA/Bb,CAA4C,mBAExD,CACIQ,KAAM,aACNC,IAAKZ,EAAKa,IAAI,wCACdC,IAAK,GAAGX,EAAS,CAAEc,YAAa,eAAxBd,CAAyC,iBAErD,CAAEQ,KAAM,OAAQC,IAAKZ,EAAKa,IAAI,mCAAoCC,IAAK,GAAGX,EAAS,CAAEc,YAAa,eAAxBd,CAAyC,YAEjHe,EAAOZ,EAAO,CAChBa,eAAgB,KACZd,GAAee,SAASD,kBAE5BE,UAAYC,IACRjB,GAAee,SAASC,UAAUC,MA4B1C,OAVA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as t}from"../../../external/preact/dist/preact.js";import{UIElement as s}from"../../internal/UIElement/UIElement.js";import e from"../../internal/IssuerList/IssuerList.js";import i from"../../../utils/get-issuer-image.js";import{FALLBACK_CONTEXT as
|
|
1
|
+
import{createElement as t}from"../../../external/preact/dist/preact.js";import{UIElement as s}from"../../internal/UIElement/UIElement.js";import e from"../../internal/IssuerList/IssuerList.js";import i from"../../../utils/get-issuer-image.js";import{FALLBACK_CONTEXT as o}from"../../../core/config.js";import r from"../../internal/RedirectButton/RedirectButton.js";class n extends s{formatProps(t){const s=t?.details?.length&&t.details.find(t=>"issuer"===t.key)?.items||t.issuers||[];return{...t,issuers:s}}formatData(){return{paymentMethod:{type:this.type,issuer:this.state?.data?.issuer}}}get isValid(){return 0===this.props.issuers.length||Boolean(this.state?.isValid)}get brands(){return this.props.showPaymentMethodItemImages?this.props.issuers.map(t=>({icon:t.icon,name:t.id})):[]}componentToRender(){return this.props.issuers.length>0?t(e,{items:this.props.issuers,highlightedIds:this.props.highlightedIssuers,...this.props,...this.state,setComponentRef:this.setComponentRef,showImage:this.props.showImage,type:this.constructor.type,onChange:this.setState,onSubmit:this.submit,payButton:this.payButton,contextualText:this.props.i18n.get("issuerList.selectField.contextualText"),onSubmitAnalytics:this.submitAnalytics}):t(r,{showPayButton:this.props.showPayButton,name:this.props.name,...this.props,onSubmit:this.submit,payButton:this.payButton,ref:t=>{this.componentRef=t}})}constructor(t,s){super(t,s);const e=t=>this.resources.getImage(t);if(this.props.showImage){const t=i({loadingContext:this.props.loadingContext},this.constructor.type,e);this.props.issuers=this.props.issuers.map(s=>({...s,icon:t(s.id)}))}}}var a,p,h;h={showImage:!0,issuers:[],highlightedIssuers:[],loadingContext:o,showPaymentMethodItemImages:!1},(p="defaultProps")in(a=n)?Object.defineProperty(a,p,{value:h,enumerable:!0,configurable:!0,writable:!0}):a[p]=h;export{n as default};
|
|
2
2
|
//# sourceMappingURL=IssuerListContainer.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"IssuerListContainer.js","sources":["../../../../../src/components/helpers/IssuerListContainer/IssuerListContainer.tsx"],"sourcesContent":["import { h } from 'preact';\nimport UIElement from '../../internal/UIElement/UIElement';\nimport IssuerList from '../../internal/IssuerList';\nimport getIssuerImageUrl from '../../../utils/get-issuer-image';\nimport { FALLBACK_CONTEXT } from '../../../core/config';\nimport RedirectButton from '../../internal/RedirectButton';\nimport { IssuerListConfiguration, IssuerListData } from './types';\nimport type { ICore } from '../../../core/types';\nimport { PaymentMethodBrand } from '../../../types/global-types';\n\nclass IssuerListContainer<TProps extends IssuerListConfiguration = IssuerListConfiguration, TData = IssuerListData> extends UIElement<TProps> {\n protected static readonly defaultProps = {\n showImage: true,\n issuers: [],\n highlightedIssuers: [],\n loadingContext: FALLBACK_CONTEXT,\n showPaymentMethodItemImages: false\n };\n\n constructor(checkout: ICore, props?: TProps) {\n super(checkout, props);\n\n const getImage = props => this.resources.getImage(props);\n\n if (this.props.showImage) {\n const getIssuerIcon = getIssuerImageUrl({ loadingContext: this.props.loadingContext }, this.constructor['type'], getImage);\n\n this.props.issuers = this.props.issuers.map(item => ({\n ...item,\n icon: getIssuerIcon(item.id)\n }));\n }\n }\n\n formatProps(props) {\n const issuers
|
|
1
|
+
{"version":3,"file":"IssuerListContainer.js","sources":["../../../../../src/components/helpers/IssuerListContainer/IssuerListContainer.tsx"],"sourcesContent":["import { h } from 'preact';\nimport UIElement from '../../internal/UIElement/UIElement';\nimport IssuerList from '../../internal/IssuerList';\nimport getIssuerImageUrl from '../../../utils/get-issuer-image';\nimport { FALLBACK_CONTEXT } from '../../../core/config';\nimport RedirectButton from '../../internal/RedirectButton';\nimport { IssuerListConfiguration, IssuerListData } from './types';\nimport type { ICore } from '../../../core/types';\nimport { PaymentMethodBrand } from '../../../types/global-types';\nimport { ImageOptions } from '../../../core/Context/Resources';\n\nclass IssuerListContainer<TProps extends IssuerListConfiguration = IssuerListConfiguration, TData = IssuerListData> extends UIElement<TProps> {\n protected static readonly defaultProps = {\n showImage: true,\n issuers: [],\n highlightedIssuers: [],\n loadingContext: FALLBACK_CONTEXT,\n showPaymentMethodItemImages: false\n };\n\n constructor(checkout: ICore, props?: TProps) {\n super(checkout, props);\n\n const getImage = (props: ImageOptions) => this.resources.getImage(props);\n\n if (this.props.showImage) {\n const getIssuerIcon = getIssuerImageUrl({ loadingContext: this.props.loadingContext }, this.constructor['type'], getImage);\n\n this.props.issuers = this.props.issuers.map(item => ({\n ...item,\n icon: getIssuerIcon(item.id)\n }));\n }\n }\n\n formatProps(props: TProps): TProps {\n const issuers =\n // @ts-expect-error - details is not in the props type but we need it for backward compatibility\n (props?.details?.length && props.details.find((d: Record<string, unknown>) => d.key === 'issuer')?.items) || props.issuers || [];\n return { ...props, issuers };\n }\n\n /**\n * Formats the component data output\n */\n formatData(): TData {\n return {\n paymentMethod: {\n type: this.type,\n issuer: this.state?.data?.issuer\n }\n } as TData;\n }\n\n /**\n * Returns whether the component state is valid or not\n */\n get isValid() {\n if (this.props.issuers.length === 0) {\n return true;\n }\n return Boolean(this.state?.isValid);\n }\n\n /**\n * Returns brands array (similar to card) depending on showPaymentMethodItemImages\n * This is used to show the brands in the PaymentMethodItem\n * Requires brands icons to be loaded in the payment method\n */\n get brands(): PaymentMethodBrand[] {\n if (this.props.showPaymentMethodItemImages) {\n return this.props.issuers.map(brand => {\n const brandIcon = brand.icon;\n return { icon: brandIcon, name: brand.id };\n });\n }\n\n return [];\n }\n\n protected override componentToRender(): h.JSX.Element {\n return this.props.issuers.length > 0 ? (\n <IssuerList\n items={this.props.issuers}\n highlightedIds={this.props.highlightedIssuers}\n {...this.props}\n {...this.state}\n setComponentRef={this.setComponentRef}\n showImage={this.props.showImage}\n type={this.constructor['type']}\n onChange={this.setState}\n onSubmit={this.submit}\n payButton={this.payButton}\n contextualText={this.props.i18n.get('issuerList.selectField.contextualText')}\n onSubmitAnalytics={this.submitAnalytics}\n />\n ) : (\n <RedirectButton\n showPayButton={this.props.showPayButton}\n name={this.props.name}\n {...this.props}\n onSubmit={this.submit}\n payButton={this.payButton}\n ref={ref => {\n this.componentRef = ref;\n }}\n />\n );\n }\n}\n\nexport default IssuerListContainer;\n"],"names":["IssuerListContainer","UIElement","formatProps","props","issuers","details","length","find","d","key","items","formatData","paymentMethod","type","this","issuer","state","data","isValid","Boolean","brands","showPaymentMethodItemImages","map","brand","icon","name","id","componentToRender","h","IssuerList","highlightedIds","highlightedIssuers","setComponentRef","showImage","constructor","onChange","setState","onSubmit","submit","payButton","contextualText","i18n","get","onSubmitAnalytics","submitAnalytics","RedirectButton","showPayButton","ref","componentRef","checkout","super","getImage","resources","getIssuerIcon","getIssuerImageUrl","loadingContext","item","FALLBACK_CONTEXT","defaultProps"],"mappings":"6WAWA,MAAMA,UAAsHC,EAwBxHC,WAAAA,CAAYC,GACR,MAAMC,EAEDD,GAAOE,SAASC,QAAUH,EAAME,QAAQE,KAAMC,GAAyC,WAAVA,EAAEC,MAAmBC,OAAUP,EAAMC,SAAW,GAClI,MAAO,IAAKD,EAAOC,UACvB,CAKAO,UAAAA,GACI,MAAO,CACHC,cAAe,CACXC,KAAMC,KAAKD,KACXE,OAAQD,KAAKE,OAAOC,MAAMF,QAGtC,CAKA,WAAIG,GACA,OAAkC,IAA9BJ,KAAKX,MAAMC,QAAQE,QAGhBa,QAAQL,KAAKE,OAAOE,QAC/B,CAOA,UAAIE,GACA,OAAIN,KAAKX,MAAMkB,4BACJP,KAAKX,MAAMC,QAAQkB,IAAIC,IAEnB,CAAEC,KADSD,EAAMC,KACEC,KAAMF,EAAMG,MAIvC,EACX,CAEmBC,iBAAAA,GACf,OAAOb,KAAKX,MAAMC,QAAQE,OAAS,EAC/BsB,EAACC,EAAAA,CACGnB,MAAOI,KAAKX,MAAMC,QAClB0B,eAAgBhB,KAAKX,MAAM4B,sBACvBjB,KAAKX,SACLW,KAAKE,MACTgB,gBAAiBlB,KAAKkB,gBACtBC,UAAWnB,KAAKX,MAAM8B,UACtBpB,KAAMC,KAAKoB,YAAY,KACvBC,SAAUrB,KAAKsB,SACfC,SAAUvB,KAAKwB,OACfC,UAAWzB,KAAKyB,UAChBC,eAAgB1B,KAAKX,MAAMsC,KAAKC,IAAI,yCACpCC,kBAAmB7B,KAAK8B,kBAG5BhB,EAACiB,EAAAA,CACGC,cAAehC,KAAKX,MAAM2C,cAC1BrB,KAAMX,KAAKX,MAAMsB,QACbX,KAAKX,MACTkC,SAAUvB,KAAKwB,OACfC,UAAWzB,KAAKyB,UAChBQ,IAAKA,IACDjC,KAAKkC,aAAeD,IAIpC,CAxFA,WAAAb,CAAYe,EAAiB9C,GACzB+C,MAAMD,EAAU9C,GAEhB,MAAMgD,EAAYhD,GAAwBW,KAAKsC,UAAUD,SAAShD,GAElE,GAAIW,KAAKX,MAAM8B,UAAW,CACtB,MAAMoB,EAAgBC,EAAkB,CAAEC,eAAgBzC,KAAKX,MAAMoD,gBAAkBzC,KAAKoB,iBAAqBiB,GAEjHrC,KAAKX,MAAMC,QAAUU,KAAKX,MAAMC,QAAQkB,IAAIkC,QACrCA,EACHhC,KAAM6B,EAAcG,EAAK9B,MAEjC,CACJ,cArByC,CACrCO,WAAW,EACX7B,QAAS,GACT2B,mBAAoB,GACpBwB,eAAgBE,EAChBpC,6BAA6B,MALPqC,oBADxB1D"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createElement as e,Fragment as t}from"../../../external/preact/dist/preact.js";import{useRef as
|
|
1
|
+
import{createElement as e,Fragment as t}from"../../../external/preact/dist/preact.js";import{useRef as r,useMemo as o,useState as s,useCallback as n,useEffect as a}from"../../../external/preact/hooks/dist/hooks.js";import i from"../FormFields/Fieldset/Fieldset.js";import l from"./components/ReadOnlyAddress.js";import{getAddressValidationRules as d}from"./validate.js";import{addressFormatters as c,countrySpecificFormatters as u}from"./validate.formats.js";import m from"./components/FieldContainer.js";import p from"../../../utils/useForm/useForm.js";import f from"./Specifications.js";import{ADDRESS_SCHEMA as y,FALLBACK_VALUE as F}from"./constants.js";import{getMaxLengthByFieldAndCountry as h}from"../../../utils/validator-utils.js";import{useCoreContext as C}from"../../../core/Context/CoreProvider.js";import g from"./components/AddressSearch.js";function A(A){const{i18n:v}=C(),{label:b="",requiredFields:j,visibility:S,iOSFocusedField:x=null,showContextualElement:k}=A,M=r({});Object.keys(M.current).length||A.setComponentRef?.(M.current);const O=o(()=>new f(A.specifications),[A.specifications]),D=O.getAddressSchemaForCountryFlat(A.countryCode).filter(e=>j.includes(e)),[w,B]=s(!1),[E,L]=s(!1),[N,P]=s(""),R=!!A.onAddressLookup,[V,H]=s(!1),q=!A.onAddressLookup||(w||E),{data:T,errors:_,valid:I,isValid:U,handleChangeFor:$,triggerValidation:z,setData:G,mergeData:J}=p({schema:D,defaultData:A.data,rules:{...d(O),...A.validationRules},formatters:c}),K=r(A.data?.country),Q=(T.country||K.current)?.toUpperCase(),W=o(()=>({...T,country:Q}),[T,Q]),X=n(e=>{const t=y.reduce((t,r)=>{const o=e[r];return null!=o&&(t[r]=String(o)),t},{});J(t),H(!0),z(),B(!0)},[B,z,G]),Y=n(()=>{L(!0)},[]);M.current.showValidation=()=>{z(),P(!R||q||U?"":v.get("address.errors.incomplete"))};const Z=D.filter(e=>!x||e===x);if(a(()=>{if(V)return void H(!1);const e=O.countryHasDataset(T.country)?"":F,t={...T,stateOrProvince:e};j.forEach(e=>{$(e,"input")(t[e]??"")}),t.postalCode&&$("postalCode","blur")(T.postalCode)},[T.country]),a(()=>{const e=j.includes("stateOrProvince"),t=T.country&&O.countryHasDataset(T.country),r=e&&t,o=T.stateOrProvince||(r?"":F);$("stateOrProvince","input")(o)},[]),a(()=>{const e=O.getOptionalFieldsForCountry(T.country),t=y.reduce((t,r)=>{const o=e.includes(r),s=j.includes(r),n=T[r],a=A.data[r],i=o&&!n||!s?s||n||!a?F:a:n;return i?.length&&(t[r]=i),t},{});!t.country&&K.current&&(t.country=K.current),A.onChange({data:t,valid:I,errors:_,isValid:U})},[T,I,_,U]),"hidden"===S)return null;if("readOnly"===S)return e(l,{data:T,label:b});const ee=(t,{classNameModifiers:r=[]})=>j.includes(t)?e(m,{key:t,allowedCountries:A.allowedCountries,classNameModifiers:[...r,t],data:W,errors:_,valid:I,fieldName:t,onInput:$(t,"input"),onBlur:$(t,"blur"),onDropdownChange:$(t,"blur"),specifications:O,maxLength:h(u,t,Q),trimOnBlur:!0,disabled:!Z.includes(t),onFieldFocusAnalytics:A.onFieldFocusAnalytics,onFieldBlurAnalytics:A.onFieldBlurAnalytics}):null,te=O.getAddressSchemaForCountry(T.country);return e(t,null,e(i,{classNameModifiers:[b,"address"],label:b,renderLabelAsSectionHeading:!0},R&&e(g,{onAddressLookup:A.onAddressLookup,onAddressSelected:A.onAddressSelected,onSelect:X,onManualAddress:Y,externalErrorMessage:N,hideManualButton:q,showContextualElement:k,contextualText:v.get("address.search.contextualText"),addressSearchDebounceMs:A.addressSearchDebounceMs}),q&&e(t,null,te.map(t=>t instanceof Array?e("div",{className:"adyen-checkout__field-group"},t.map(([e,t])=>ee(e,{classNameModifiers:[`col-${t}`]}))):ee(t,{})))))}A.defaultProps={countryCode:null,validationRules:null,data:{},onChange:()=>{},visibility:"editable",requiredFields:y,specifications:{},onFieldFocusAnalytics:()=>{},onFieldBlurAnalytics:()=>{}};export{A as default};
|
|
2
2
|
//# sourceMappingURL=Address.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Address.js","sources":["../../../../../src/components/internal/Address/Address.tsx"],"sourcesContent":["import { Fragment, h } from 'preact';\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'preact/hooks';\nimport Fieldset from '../FormFields/Fieldset';\nimport ReadOnlyAddress from './components/ReadOnlyAddress';\nimport { getAddressValidationRules } from './validate';\nimport { addressFormatters, countrySpecificFormatters } from './validate.formats';\nimport { AddressProps } from './types';\nimport { AddressData } from '../../../types/global-types';\nimport FieldContainer from './components/FieldContainer';\nimport useForm from '../../../utils/useForm';\nimport Specifications from './Specifications';\nimport { ADDRESS_SCHEMA, FALLBACK_VALUE } from './constants';\nimport { getMaxLengthByFieldAndCountry } from '../../../utils/validator-utils';\nimport { useCoreContext } from '../../../core/Context/CoreProvider';\nimport AddressSearch from './components/AddressSearch';\nimport { ComponentMethodsRef } from '../UIElement/types';\nimport './Address.scss';\n\nexport default function Address(props: Readonly<AddressProps>) {\n const { i18n } = useCoreContext();\n\n const { label = '', requiredFields, visibility, iOSFocusedField = null, showContextualElement } = props;\n\n /** An object by which to expose 'public' members to the parent UIElement */\n const addressRef = useRef<ComponentMethodsRef>({});\n // Just call once\n if (!Object.keys(addressRef.current).length) {\n props.setComponentRef?.(addressRef.current);\n }\n\n const specifications = useMemo(() => new Specifications(props.specifications), [props.specifications]);\n\n const requiredFieldsSchema = specifications.getAddressSchemaForCountryFlat(props.countryCode).filter(field => requiredFields.includes(field));\n\n const [hasSelectedAddress, setHasSelectedAddress] = useState(false);\n\n const [useManualAddress, setUseManualAddress] = useState(false);\n\n const [searchErrorMessage, setSearchErrorMessage] = useState('');\n\n const showAddressSearch = !!props.onAddressLookup;\n\n const [ignoreCountryChange, setIgnoreCountryChange] = useState(false);\n\n const showAddressFields = props.onAddressLookup ? hasSelectedAddress || useManualAddress : true;\n\n const { data, errors, valid, isValid, handleChangeFor, triggerValidation, setData, mergeData } = useForm<AddressData>({\n schema: requiredFieldsSchema,\n defaultData: props.data,\n // Ensure any passed validation rules are merged with the default ones\n rules: { ...getAddressValidationRules(specifications), ...props.validationRules },\n formatters: addressFormatters\n });\n\n // In partial address mode, country is not in the form schema but we need it for regionalized labels.\n // Store the merchant's country config once at mount, then use it if form data doesn't have country.\n const initialCountryRef = useRef<string | undefined>((props.data as AddressData)?.country);\n const effectiveCountry = (data.country || initialCountryRef.current)?.toUpperCase();\n const dataWithCountry = useMemo(() => ({ ...data, country: effectiveCountry }), [data, effectiveCountry]);\n\n const setSearchData = useCallback(\n (selectedAddress: AddressData) => {\n const propsKeysToProcess = ADDRESS_SCHEMA;\n const newStateData = propsKeysToProcess.reduce((acc: AddressData, propKey) => {\n // Make sure the data provided by the merchant is always strings\n const providedValue = selectedAddress[propKey];\n if (providedValue !== null && providedValue !== undefined) {\n // Cast everything to string\n acc[propKey] = String(providedValue);\n }\n return acc;\n }, {});\n mergeData(newStateData);\n setIgnoreCountryChange(true);\n triggerValidation();\n setHasSelectedAddress(true);\n },\n [setHasSelectedAddress, triggerValidation, setData]\n );\n\n const onManualAddress = useCallback(() => {\n setUseManualAddress(true);\n }, []);\n\n // Expose method expected by (parent) Address.tsx\n addressRef.current.showValidation = () => {\n triggerValidation();\n if (showAddressSearch && !showAddressFields && !isValid) {\n setSearchErrorMessage(i18n.get('address.errors.incomplete'));\n } else {\n setSearchErrorMessage('');\n }\n };\n\n /**\n * For iOS: iOSFocusedField is the name of the element calling for other elements to be disabled\n * - so if it is set (meaning we are in iOS *and* an input has been focussed) only enable the field that corresponds to this element\n */\n const enabledFields: string[] = requiredFieldsSchema.filter(item => {\n return !iOSFocusedField ? true : item === iOSFocusedField;\n });\n\n /**\n * Effect that:\n * - Resets validation for all fields by triggering handleChangeFor(fieldName, 'input')\n * - Applies validation on postalCode field in case it has any value\n */\n useEffect((): void => {\n // if the country was set via setSearchData we don't want to trigger this\n if (ignoreCountryChange) {\n setIgnoreCountryChange(false);\n return;\n }\n\n const stateOrProvince = specifications.countryHasDataset(data.country) ? '' : FALLBACK_VALUE;\n const newData = { ...data, stateOrProvince };\n\n requiredFields.forEach(fieldName => {\n handleChangeFor(fieldName, 'input')(newData[fieldName] ?? '');\n });\n\n if (newData.postalCode) {\n handleChangeFor('postalCode', 'blur')(data.postalCode);\n }\n }, [data.country]);\n\n /**\n * Set the value of 'stateOrProvince' during the initial render if\n * property is provided during the creation of the payment method\n */\n useEffect((): void => {\n const stateFieldIsRequired = requiredFields.includes('stateOrProvince');\n const countryHasStatesDataset = data.country && specifications.countryHasDataset(data.country);\n const addressShouldHaveState = stateFieldIsRequired && countryHasStatesDataset;\n const stateOrProvince = data.stateOrProvince || (addressShouldHaveState ? '' : FALLBACK_VALUE);\n\n handleChangeFor('stateOrProvince', 'input')(stateOrProvince);\n }, []);\n\n useEffect((): void => {\n const optionalFields = specifications.getOptionalFieldsForCountry(data.country);\n const processedData = ADDRESS_SCHEMA.reduce((acc, cur) => {\n const isOptional = optionalFields.includes(cur);\n const isRequired = requiredFields.includes(cur);\n const newValue = data[cur];\n const initialValue = props.data[cur];\n // recover default data values which are not requiredFields, or prefill with 'N/A'\n const fallbackValue = !isRequired && !newValue && !!initialValue ? initialValue : FALLBACK_VALUE;\n const value = (isOptional && !newValue) || !isRequired ? fallbackValue : newValue;\n if (value?.length) acc[cur] = value;\n return acc;\n }, {});\n\n // In partial address mode, ensure country is included in output for regionalized labels/validation.\n if (!(processedData as AddressData).country && initialCountryRef.current) {\n (processedData as AddressData).country = initialCountryRef.current;\n }\n\n props.onChange({ data: processedData, valid, errors, isValid });\n }, [data, valid, errors, isValid]);\n\n if (visibility === 'hidden') return null;\n if (visibility === 'readOnly') return <ReadOnlyAddress data={data} label={label} />;\n\n const getComponent = (fieldName: string, { classNameModifiers = [] }) => {\n if (!requiredFields.includes(fieldName)) return null;\n\n return (\n <FieldContainer\n key={fieldName}\n allowedCountries={props.allowedCountries}\n classNameModifiers={[...classNameModifiers, fieldName]}\n data={dataWithCountry}\n errors={errors}\n valid={valid}\n fieldName={fieldName}\n onInput={handleChangeFor(fieldName, 'input')}\n onBlur={handleChangeFor(fieldName, 'blur')}\n onDropdownChange={handleChangeFor(fieldName, 'blur')}\n specifications={specifications}\n maxLength={getMaxLengthByFieldAndCountry(countrySpecificFormatters, fieldName, effectiveCountry, true)}\n trimOnBlur={true}\n disabled={!enabledFields.includes(fieldName)}\n onFieldFocusAnalytics={props.onFieldFocusAnalytics}\n onFieldBlurAnalytics={props.onFieldBlurAnalytics}\n />\n );\n };\n\n const getWrapper = group => (\n <div className=\"adyen-checkout__field-group\">\n {group.map(([field, size]) => getComponent(field, { classNameModifiers: [`col-${size}`] }))}\n </div>\n );\n\n const addressSchema = specifications.getAddressSchemaForCountry(data.country);\n\n return (\n <Fragment>\n <Fieldset classNameModifiers={[label, 'address']} label={label}>\n {showAddressSearch && (\n <AddressSearch\n onAddressLookup={props.onAddressLookup}\n onAddressSelected={props.onAddressSelected}\n onSelect={setSearchData}\n onManualAddress={onManualAddress}\n externalErrorMessage={searchErrorMessage}\n hideManualButton={showAddressFields}\n showContextualElement={showContextualElement}\n contextualText={i18n.get('address.search.contextualText')}\n addressSearchDebounceMs={props.addressSearchDebounceMs}\n />\n )}\n {showAddressFields && (\n <Fragment>{addressSchema.map(field => (field instanceof Array ? getWrapper(field) : getComponent(field, {})))}</Fragment>\n )}\n </Fieldset>\n </Fragment>\n );\n}\n\nAddress.defaultProps = {\n countryCode: null,\n validationRules: null,\n data: {},\n onChange: () => {},\n visibility: 'editable',\n requiredFields: ADDRESS_SCHEMA,\n specifications: {},\n onFieldFocusAnalytics: () => {},\n onFieldBlurAnalytics: () => {}\n};\n"],"names":["Address","props","i18n","useCoreContext","label","requiredFields","visibility","iOSFocusedField","showContextualElement","addressRef","useRef","Object","keys","current","length","setComponentRef","specifications","useMemo","Specifications","requiredFieldsSchema","getAddressSchemaForCountryFlat","countryCode","filter","field","includes","hasSelectedAddress","setHasSelectedAddress","useState","useManualAddress","setUseManualAddress","searchErrorMessage","setSearchErrorMessage","showAddressSearch","onAddressLookup","ignoreCountryChange","setIgnoreCountryChange","showAddressFields","data","errors","valid","isValid","handleChangeFor","triggerValidation","setData","mergeData","useForm","schema","defaultData","rules","getAddressValidationRules","validationRules","formatters","addressFormatters","initialCountryRef","country","effectiveCountry","toUpperCase","dataWithCountry","setSearchData","useCallback","selectedAddress","newStateData","ADDRESS_SCHEMA","reduce","acc","propKey","providedValue","String","onManualAddress","showValidation","get","enabledFields","item","useEffect","stateOrProvince","countryHasDataset","FALLBACK_VALUE","newData","forEach","fieldName","postalCode","stateFieldIsRequired","countryHasStatesDataset","addressShouldHaveState","optionalFields","getOptionalFieldsForCountry","processedData","cur","isOptional","isRequired","newValue","initialValue","value","onChange","h","ReadOnlyAddress","getComponent","classNameModifiers","FieldContainer","key","allowedCountries","onInput","onBlur","onDropdownChange","maxLength","getMaxLengthByFieldAndCountry","countrySpecificFormatters","trimOnBlur","disabled","onFieldFocusAnalytics","onFieldBlurAnalytics","addressSchema","getAddressSchemaForCountry","Fragment","Fieldset","AddressSearch","onAddressSelected","onSelect","externalErrorMessage","hideManualButton","contextualText","addressSearchDebounceMs","map","Array","div","className","size","defaultProps"],"mappings":"u1BAkBe,SAASA,EAAQC,GAC5B,MAAMC,KAAEA,GAASC,KAEXC,MAAEA,EAAQ,GAAEC,eAAEA,EAAcC,WAAEA,EAAUC,gBAAEA,EAAkB,KAAIC,sBAAEA,GAA0BP,EAG5FQ,EAAaC,EAA4B,IAE1CC,OAAOC,KAAKH,EAAWI,SAASC,QACjCb,EAAMc,kBAAkBN,EAAWI,SAGvC,MAAMG,EAAiBC,EAAQ,IAAM,IAAIC,EAAejB,EAAMe,gBAAiB,CAACf,EAAMe,iBAEhFG,EAAuBH,EAAeI,+BAA+BnB,EAAMoB,aAAaC,OAAOC,GAASlB,EAAemB,SAASD,KAE/HE,EAAoBC,GAAyBC,GAAS,IAEtDC,EAAkBC,GAAuBF,GAAS,IAElDG,EAAoBC,GAAyBJ,EAAS,IAEvDK,IAAsB/B,EAAMgC,iBAE3BC,EAAqBC,GAA0BR,GAAS,GAEzDS,GAAoBnC,EAAMgC,kBAAkBR,GAAsBG,IAElES,KAAEA,EAAIC,OAAEA,EAAMC,MAAEA,EAAKC,QAAEA,EAAOC,gBAAEA,EAAeC,kBAAEA,EAAiBC,QAAEA,EAAOC,UAAEA,GAAcC,EAAqB,CAClHC,OAAQ3B,EACR4B,YAAa9C,EAAMoC,KAEnBW,MAAO,IAAKC,EAA0BjC,MAAoBf,EAAMiD,iBAChEC,WAAYC,IAKVC,EAAoB3C,EAA4BT,EAAMoC,MAAsBiB,SAC5EC,GAAoBlB,EAAKiB,SAAWD,E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kBAAmBnH,EAAMmH,kBACzBC,SAAU3D,EACVU,gBAAiBA,EACjBkD,qBAAsBxF,EACtByF,iBAAkBnF,EAClB5B,sBAAuBA,EACvBgH,eAAgBtH,EAAKoE,IAAI,iCACzBmD,wBAAyBxH,EAAMwH,0BAGtCrF,GACG0D,EAACmB,EAAAA,KAAUF,GAAcW,IAAInG,GAAUA,aAAiBoG,MAxBpE7B,EAAC8B,MAAAA,CAAIC,UAAU,+BAwBwEtG,EAvB5EmG,IAAI,EAAEnG,EAAOuG,KAAU9B,GAAazE,EAAO,CAAE0E,mBAAoB,CAAC,OAAO6B,SAuBY9B,GAAazE,EAAO,CAAA,MAK5H,CAEAvB,EAAQ+H,aAAe,CACnB1G,YAAa,KACb6B,gBAAiB,KACjBb,KAAM,CAAA,EACNwD,SAAU,OACVvF,WAAY,WACZD,eAAgByD,EAChB9C,eAAgB,CAAA,EAChB6F,sBAAuB,OACvBC,qBAAsB"}
|
|
1
|
+
{"version":3,"file":"Address.js","sources":["../../../../../src/components/internal/Address/Address.tsx"],"sourcesContent":["import { Fragment, h } from 'preact';\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'preact/hooks';\nimport Fieldset from '../FormFields/Fieldset';\nimport ReadOnlyAddress from './components/ReadOnlyAddress';\nimport { getAddressValidationRules } from './validate';\nimport { addressFormatters, countrySpecificFormatters } from './validate.formats';\nimport { AddressProps } from './types';\nimport { AddressData } from '../../../types/global-types';\nimport FieldContainer from './components/FieldContainer';\nimport useForm from '../../../utils/useForm';\nimport Specifications from './Specifications';\nimport { ADDRESS_SCHEMA, FALLBACK_VALUE } from './constants';\nimport { getMaxLengthByFieldAndCountry } from '../../../utils/validator-utils';\nimport { useCoreContext } from '../../../core/Context/CoreProvider';\nimport AddressSearch from './components/AddressSearch';\nimport { ComponentMethodsRef } from '../UIElement/types';\nimport './Address.scss';\n\nexport default function Address(props: Readonly<AddressProps>) {\n const { i18n } = useCoreContext();\n\n const { label = '', requiredFields, visibility, iOSFocusedField = null, showContextualElement } = props;\n\n /** An object by which to expose 'public' members to the parent UIElement */\n const addressRef = useRef<ComponentMethodsRef>({});\n // Just call once\n if (!Object.keys(addressRef.current).length) {\n props.setComponentRef?.(addressRef.current);\n }\n\n const specifications = useMemo(() => new Specifications(props.specifications), [props.specifications]);\n\n const requiredFieldsSchema = specifications.getAddressSchemaForCountryFlat(props.countryCode).filter(field => requiredFields.includes(field));\n\n const [hasSelectedAddress, setHasSelectedAddress] = useState(false);\n\n const [useManualAddress, setUseManualAddress] = useState(false);\n\n const [searchErrorMessage, setSearchErrorMessage] = useState('');\n\n const showAddressSearch = !!props.onAddressLookup;\n\n const [ignoreCountryChange, setIgnoreCountryChange] = useState(false);\n\n const showAddressFields = props.onAddressLookup ? hasSelectedAddress || useManualAddress : true;\n\n const { data, errors, valid, isValid, handleChangeFor, triggerValidation, setData, mergeData } = useForm<AddressData>({\n schema: requiredFieldsSchema,\n defaultData: props.data,\n // Ensure any passed validation rules are merged with the default ones\n rules: { ...getAddressValidationRules(specifications), ...props.validationRules },\n formatters: addressFormatters\n });\n\n // In partial address mode, country is not in the form schema but we need it for regionalized labels.\n // Store the merchant's country config once at mount, then use it if form data doesn't have country.\n const initialCountryRef = useRef<string | undefined>((props.data as AddressData)?.country);\n const effectiveCountry = (data.country || initialCountryRef.current)?.toUpperCase();\n const dataWithCountry = useMemo(() => ({ ...data, country: effectiveCountry }), [data, effectiveCountry]);\n\n const setSearchData = useCallback(\n (selectedAddress: AddressData) => {\n const propsKeysToProcess = ADDRESS_SCHEMA;\n const newStateData = propsKeysToProcess.reduce((acc: AddressData, propKey) => {\n // Make sure the data provided by the merchant is always strings\n const providedValue = selectedAddress[propKey];\n if (providedValue !== null && providedValue !== undefined) {\n // Cast everything to string\n acc[propKey] = String(providedValue);\n }\n return acc;\n }, {});\n mergeData(newStateData);\n setIgnoreCountryChange(true);\n triggerValidation();\n setHasSelectedAddress(true);\n },\n [setHasSelectedAddress, triggerValidation, setData]\n );\n\n const onManualAddress = useCallback(() => {\n setUseManualAddress(true);\n }, []);\n\n // Expose method expected by (parent) Address.tsx\n addressRef.current.showValidation = () => {\n triggerValidation();\n if (showAddressSearch && !showAddressFields && !isValid) {\n setSearchErrorMessage(i18n.get('address.errors.incomplete'));\n } else {\n setSearchErrorMessage('');\n }\n };\n\n /**\n * For iOS: iOSFocusedField is the name of the element calling for other elements to be disabled\n * - so if it is set (meaning we are in iOS *and* an input has been focussed) only enable the field that corresponds to this element\n */\n const enabledFields: string[] = requiredFieldsSchema.filter(item => {\n return !iOSFocusedField ? true : item === iOSFocusedField;\n });\n\n /**\n * Effect that:\n * - Resets validation for all fields by triggering handleChangeFor(fieldName, 'input')\n * - Applies validation on postalCode field in case it has any value\n */\n useEffect((): void => {\n // if the country was set via setSearchData we don't want to trigger this\n if (ignoreCountryChange) {\n setIgnoreCountryChange(false);\n return;\n }\n\n const stateOrProvince = specifications.countryHasDataset(data.country) ? '' : FALLBACK_VALUE;\n const newData = { ...data, stateOrProvince };\n\n requiredFields.forEach(fieldName => {\n handleChangeFor(fieldName, 'input')(newData[fieldName] ?? '');\n });\n\n if (newData.postalCode) {\n handleChangeFor('postalCode', 'blur')(data.postalCode);\n }\n }, [data.country]);\n\n /**\n * Set the value of 'stateOrProvince' during the initial render if\n * property is provided during the creation of the payment method\n */\n useEffect((): void => {\n const stateFieldIsRequired = requiredFields.includes('stateOrProvince');\n const countryHasStatesDataset = data.country && specifications.countryHasDataset(data.country);\n const addressShouldHaveState = stateFieldIsRequired && countryHasStatesDataset;\n const stateOrProvince = data.stateOrProvince || (addressShouldHaveState ? '' : FALLBACK_VALUE);\n\n handleChangeFor('stateOrProvince', 'input')(stateOrProvince);\n }, []);\n\n useEffect((): void => {\n const optionalFields = specifications.getOptionalFieldsForCountry(data.country);\n const processedData = ADDRESS_SCHEMA.reduce((acc, cur) => {\n const isOptional = optionalFields.includes(cur);\n const isRequired = requiredFields.includes(cur);\n const newValue = data[cur];\n const initialValue = props.data[cur];\n // recover default data values which are not requiredFields, or prefill with 'N/A'\n const fallbackValue = !isRequired && !newValue && !!initialValue ? initialValue : FALLBACK_VALUE;\n const value = (isOptional && !newValue) || !isRequired ? fallbackValue : newValue;\n if (value?.length) acc[cur] = value;\n return acc;\n }, {});\n\n // In partial address mode, ensure country is included in output for regionalized labels/validation.\n if (!(processedData as AddressData).country && initialCountryRef.current) {\n (processedData as AddressData).country = initialCountryRef.current;\n }\n\n props.onChange({ data: processedData, valid, errors, isValid });\n }, [data, valid, errors, isValid]);\n\n if (visibility === 'hidden') return null;\n if (visibility === 'readOnly') return <ReadOnlyAddress data={data} label={label} />;\n\n const getComponent = (fieldName: string, { classNameModifiers = [] }) => {\n if (!requiredFields.includes(fieldName)) return null;\n\n return (\n <FieldContainer\n key={fieldName}\n allowedCountries={props.allowedCountries}\n classNameModifiers={[...classNameModifiers, fieldName]}\n data={dataWithCountry}\n errors={errors}\n valid={valid}\n fieldName={fieldName}\n onInput={handleChangeFor(fieldName, 'input')}\n onBlur={handleChangeFor(fieldName, 'blur')}\n onDropdownChange={handleChangeFor(fieldName, 'blur')}\n specifications={specifications}\n maxLength={getMaxLengthByFieldAndCountry(countrySpecificFormatters, fieldName, effectiveCountry, true)}\n trimOnBlur={true}\n disabled={!enabledFields.includes(fieldName)}\n onFieldFocusAnalytics={props.onFieldFocusAnalytics}\n onFieldBlurAnalytics={props.onFieldBlurAnalytics}\n />\n );\n };\n\n const getWrapper = group => (\n <div className=\"adyen-checkout__field-group\">\n {group.map(([field, size]) => getComponent(field, { classNameModifiers: [`col-${size}`] }))}\n </div>\n );\n\n const addressSchema = specifications.getAddressSchemaForCountry(data.country);\n\n return (\n <Fragment>\n <Fieldset classNameModifiers={[label, 'address']} label={label} renderLabelAsSectionHeading>\n {showAddressSearch && (\n <AddressSearch\n onAddressLookup={props.onAddressLookup}\n onAddressSelected={props.onAddressSelected}\n onSelect={setSearchData}\n onManualAddress={onManualAddress}\n externalErrorMessage={searchErrorMessage}\n hideManualButton={showAddressFields}\n showContextualElement={showContextualElement}\n contextualText={i18n.get('address.search.contextualText')}\n addressSearchDebounceMs={props.addressSearchDebounceMs}\n />\n )}\n {showAddressFields && (\n <Fragment>{addressSchema.map(field => (field instanceof Array ? getWrapper(field) : getComponent(field, {})))}</Fragment>\n )}\n </Fieldset>\n </Fragment>\n );\n}\n\nAddress.defaultProps = {\n countryCode: null,\n validationRules: null,\n data: {},\n onChange: () => {},\n visibility: 'editable',\n requiredFields: ADDRESS_SCHEMA,\n specifications: {},\n onFieldFocusAnalytics: () => {},\n onFieldBlurAnalytics: () => {}\n};\n"],"names":["Address","props","i18n","useCoreContext","label","requiredFields","visibility","iOSFocusedField","showContextualElement","addressRef","useRef","Object","keys","current","length","setComponentRef","specifications","useMemo","Specifications","requiredFieldsSchema","getAddressSchemaForCountryFlat","countryCode","filter","field","includes","hasSelectedAddress","setHasSelectedAddress","useState","useManualAddress","setUseManualAddress","searchErrorMessage","setSearchErrorMessage","showAddressSearch","onAddressLookup","ignoreCountryChange","setIgnoreCountryChange","showAddressFields","data","errors","valid","isValid","handleChangeFor","triggerValidation","setData","mergeData","useForm","schema","defaultData","rules","getAddressValidationRules","validationRules","formatters","addressFormatters","initialCountryRef","country","effectiveCountry","toUpperCase","dataWithCountry","setSearchData","useCallback","selectedAddress","newStateData","ADDRESS_SCHEMA","reduce","acc","propKey","providedValue","String","onManualAddress","showValidation","get","enabledFields","item","useEffect","stateOrProvince","countryHasDataset","FALLBACK_VALUE","newData","forEach","fieldName","postalCode","stateFieldIsRequired","countryHasStatesDataset","addressShouldHaveState","optionalFields","getOptionalFieldsForCountry","processedData","cur","isOptional","isRequired","newValue","initialValue","value","onChange","h","ReadOnlyAddress","getComponent","classNameModifiers","FieldContainer","key","allowedCountries","onInput","onBlur","onDropdownChange","maxLength","getMaxLengthByFieldAndCountry","countrySpecificFormatters","trimOnBlur","disabled","onFieldFocusAnalytics","onFieldBlurAnalytics","addressSchema","getAddressSchemaForCountry","Fragment","Fieldset","renderLabelAsSectionHeading","AddressSearch","onAddressSelected","onSelect","externalErrorMessage","hideManualButton","contextualText","addressSearchDebounceMs","map","Array","div","className","size","defaultProps"],"mappings":"u1BAkBe,SAASA,EAAQC,GAC5B,MAAMC,KAAEA,GAASC,KAEXC,MAAEA,EAAQ,GAAEC,eAAEA,EAAcC,WAAEA,EAAUC,gBAAEA,EAAkB,KAAIC,sBAAEA,GAA0BP,EAG5FQ,EAAaC,EAA4B,IAE1CC,OAAOC,KAAKH,EAAWI,SAASC,QACjCb,EAAMc,kBAAkBN,EAAWI,SAGvC,MAAMG,EAAiBC,EAAQ,IAAM,IAAIC,EAAejB,EAAMe,gBAAiB,CAACf,EAAMe,iBAEhFG,EAAuBH,EAAeI,+BAA+BnB,EAAMoB,aAAaC,OAAOC,GAASlB,EAAemB,SAASD,KAE/HE,EAAoBC,GAAyBC,GAAS,IAEtDC,EAAkBC,GAAuBF,GAAS,IAElDG,EAAoBC,GAAyBJ,EAAS,IAEvDK,IAAsB/B,EAAMgC,iBAE3BC,EAAqBC,GAA0BR,GAAS,GAEzDS,GAAoBnC,EAAMgC,kBAAkBR,GAAsBG,IAElES,KAAEA,EAAIC,OAAEA,EAAMC,MAAEA,EAAKC,QAAEA,EAAOC,gBAAEA,EAAeC,kBAAEA,EAAiBC,QAAEA,EAAOC,UAAEA,GAAcC,EAAqB,CAClHC,OAAQ3B,EACR4B,YAAa9C,EAAMoC,KAEnBW,MAAO,IAAKC,EAA0BjC,MAAoBf,EAAMiD,iBAChEC,WAAYC,IAKVC,EAAoB3C,EAA4BT,EAAMoC,MAAsBiB,SAC5EC,GAAoBlB,EAAKiB,SAAWD,EAAkBxC,UAAU2C,cAChEC,EAAkBxC,EAAQ,KAAA,IAAYoB,EAAMiB,QAASC,IAAqB,CAAClB,EAAMkB,IAEjFG,EAAgBC,EACjBC,IACG,MACMC,EADqBC,EACaC,OAAO,CAACC,EAAkBC,KAE9D,MAAMC,EAAgBN,EAAgBK,GAKtC,OAJIC,UAEAF,EAAIC,GAAWE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GAAcY,IAAIpG,GAAUA,aAAiBqG,MAxBpE9B,EAAC+B,MAAAA,CAAIC,UAAU,+BAwBwEvG,EAvB5EoG,IAAI,EAAEpG,EAAOwG,KAAU/B,GAAazE,EAAO,CAAE0E,mBAAoB,CAAC,OAAO8B,SAuBY/B,GAAazE,EAAO,CAAA,MAK5H,CAEAvB,EAAQgI,aAAe,CACnB3G,YAAa,KACb6B,gBAAiB,KACjBb,KAAM,CAAA,EACNwD,SAAU,OACVvF,WAAY,WACZD,eAAgByD,EAChB9C,eAAgB,CAAA,EAChB6F,sBAAuB,OACvBC,qBAAsB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AddressSearch.js","sources":["../../../../../../src/components/internal/Address/components/AddressSearch.tsx"],"sourcesContent":["import Field from '../../FormFields/Field';\nimport { h } from 'preact';\nimport { AddressLookupItem } from '../types';\nimport { useCallback, useEffect, useState, useMemo } from 'preact/hooks';\nimport './AddressSearch.scss';\nimport { useCoreContext } from '../../../../core/Context/CoreProvider';\nimport { debounce } from '../../../../utils/debounce';\nimport Select from '../../FormFields/Select';\nimport { AddressData } from '../../../../types';\n\nexport type OnAddressLookupType = (\n value: string,\n actions: {\n resolve: (value: Array<AddressLookupItem>) => void;\n reject: (reason?: any) => void;\n }\n) => Promise<void>;\n\nexport type OnAddressSelectedType = (\n value: AddressLookupItem,\n actions: {\n resolve: (value: AddressLookupItem) => void;\n reject: (reason?: any) => void;\n }\n) => Promise<void>;\n\ninterface AddressSearchProps {\n onAddressLookup?: OnAddressLookupType;\n onAddressSelected?: OnAddressSelectedType;\n onSelect: (addressItem: AddressData) => void;\n onManualAddress: any;\n externalErrorMessage: string;\n hideManualButton: boolean;\n showContextualElement?: boolean;\n contextualText?: string;\n placeholder?: string;\n addressSearchDebounceMs?: number;\n}\n\ninterface RejectionReason {\n errorMessage: string;\n}\n\nexport default function AddressSearch({\n onAddressLookup,\n onAddressSelected,\n onSelect,\n onManualAddress,\n externalErrorMessage,\n hideManualButton,\n showContextualElement,\n contextualText,\n placeholder,\n addressSearchDebounceMs\n}: Readonly<AddressSearchProps>) {\n const [formattedData, setFormattedData] = useState<AddressLookupItem[]>([]);\n const [originalData, setOriginalData] = useState<AddressLookupItem[]>([]);\n\n const [errorMessage, setErrorMessage] = useState('');\n\n const { i18n } = useCoreContext();\n const mapDataToSelect = data => data.map(({ id, name }) => ({ id, name }));\n\n const handlePromiseReject = useCallback((reason: RejectionReason) => {\n if (reason?.errorMessage) {\n setErrorMessage(reason.errorMessage);\n }\n }, []);\n\n const onTextInput = useCallback(\n (inputValue: string) => {\n new Promise<Array<AddressLookupItem>>((resolve, reject) => {\n void onAddressLookup(inputValue, { resolve, reject });\n })\n .then(searchArray => {\n setOriginalData(searchArray);\n setFormattedData(mapDataToSelect(searchArray));\n setErrorMessage('');\n })\n .catch(reason => handlePromiseReject(reason));\n },\n [onAddressLookup]\n );\n\n // update error message when there's a new one\n useEffect(() => {\n setErrorMessage(externalErrorMessage);\n }, [externalErrorMessage]);\n\n const onSelectItem = event => {\n if (!event.target.value) {\n setErrorMessage(i18n.get('address.errors.incomplete'));\n return;\n }\n const value = originalData.find(item => item.id === event.target.value);\n\n // 1. in case we don't get a function just select item\n if (typeof onAddressSelected !== 'function') {\n onSelect(value);\n setFormattedData([]);\n return;\n }\n\n // 2. in case callback is provided, create and call onAddressSelected\n new Promise<AddressLookupItem>((resolve, reject) => {\n void onAddressSelected(value, { resolve, reject });\n })\n .then(fullData => {\n onSelect(fullData);\n setFormattedData([]);\n })\n .catch(reason => handlePromiseReject(reason));\n };\n\n const debounceInputHandler = useMemo(() => debounce(onTextInput, addressSearchDebounceMs), []);\n\n return (\n <div className={'adyen-checkout__address-search adyen-checkout__field-group'}>\n <Field\n label={i18n.get('address')}\n classNameModifiers={['address-search']}\n errorMessage={errorMessage}\n name={'address-search'}\n showContextualElement={showContextualElement}\n contextualText={contextualText}\n >\n <Select\n name={'address-search'}\n className={'adyen-checkout__address-search__dropdown'}\n placeholder={placeholder}\n onInput={debounceInputHandler}\n items={formattedData}\n onChange={onSelectItem}\n disableTextFilter={true}\n blurOnClose={true}\n />\n </Field>\n {!hideManualButton && (\n <span className=\"adyen-checkout__address-search__manual-add\">\n <button\n type=\"button\"\n className=\"adyen-checkout__button adyen-checkout__button--inline adyen-checkout__button--link adyen-checkout__address-search__manual-add__button\"\n onClick={onManualAddress}\n >\n {'+ ' + i18n.get('address.enterManually')}\n </button>\n </span>\n )}\n </div>\n );\n}\n"],"names":["AddressSearch","onAddressLookup","onAddressSelected","onSelect","onManualAddress","externalErrorMessage","hideManualButton","showContextualElement","contextualText","placeholder","addressSearchDebounceMs","formattedData","setFormattedData","useState","originalData","setOriginalData","errorMessage","setErrorMessage","i18n","useCoreContext","handlePromiseReject","useCallback","reason","onTextInput","inputValue","Promise","resolve","reject","then","searchArray","map","id","name","catch","useEffect","debounceInputHandler","useMemo","debounce","h","div","className","Field","label","get","classNameModifiers","Select","onInput","items","onChange","event","target","value","find","item","fullData","disableTextFilter","blurOnClose","span","button","type","onClick"],"mappings":"saA2Ce,SAASA,GAAcC,gBAClCA,EAAeC,kBACfA,EAAiBC,SACjBA,EAAQC,gBACRA,EAAeC,qBACfA,EAAoBC,iBACpBA,EAAgBC,sBAChBA,EAAqBC,eACrBA,EAAcC,YACdA,EAAWC,wBACXA,IAEA,MAAOC,EAAeC,GAAoBC,EAA8B,KACjEC,EAAcC,GAAmBF,EAA8B,KAE/DG,EAAcC,GAAmBJ,EAAS,KAE3CK,KAAEA,GAASC,IAGXC,EAAsBC,EAAaC,IACjCA,GAAQN,cACRC,EAAgBK,EAAON,eAE5B,IAEGO,EAAcF,EACfG,IACG,IAAIC,QAAkC,CAACC,EAASC,KACvC1B,EAAgBuB,EAAY,CAAEE,UAASC,aAE3CC,KAAKC,IACFd,EAAgBc,GAChBjB,EAAiCiB,EAfZC,IAAI,EAAGC,KAAIC,WAAM,CAAQD,KAAIC,WAgBlDf,EAAgB,MAEnBgB,MAAMX,GAAUF,EAAoBE,KAE7C,CAACrB,IAILiC,EAAU,KACNjB,EAAgBZ,IACjB,CAACA,IAEJ,MAyBM8B,EAAuBC,EAAQ,IAAMC,EAASd,EAAab,GAA0B,IAE3F,
|
|
1
|
+
{"version":3,"file":"AddressSearch.js","sources":["../../../../../../src/components/internal/Address/components/AddressSearch.tsx"],"sourcesContent":["import Field from '../../FormFields/Field';\nimport { h } from 'preact';\nimport { AddressLookupItem } from '../types';\nimport { useCallback, useEffect, useState, useMemo } from 'preact/hooks';\nimport './AddressSearch.scss';\nimport { useCoreContext } from '../../../../core/Context/CoreProvider';\nimport { debounce } from '../../../../utils/debounce';\nimport Select from '../../FormFields/Select';\nimport { AddressData } from '../../../../types';\n\nexport type OnAddressLookupType = (\n value: string,\n actions: {\n resolve: (value: Array<AddressLookupItem>) => void;\n reject: (reason?: any) => void;\n }\n) => Promise<void>;\n\nexport type OnAddressSelectedType = (\n value: AddressLookupItem,\n actions: {\n resolve: (value: AddressLookupItem) => void;\n reject: (reason?: any) => void;\n }\n) => Promise<void>;\n\ninterface AddressSearchProps {\n onAddressLookup?: OnAddressLookupType;\n onAddressSelected?: OnAddressSelectedType;\n onSelect: (addressItem: AddressData) => void;\n onManualAddress: any;\n externalErrorMessage: string;\n hideManualButton: boolean;\n showContextualElement?: boolean;\n contextualText?: string;\n placeholder?: string;\n addressSearchDebounceMs?: number;\n}\n\ninterface RejectionReason {\n errorMessage: string;\n}\n\nexport default function AddressSearch({\n onAddressLookup,\n onAddressSelected,\n onSelect,\n onManualAddress,\n externalErrorMessage,\n hideManualButton,\n showContextualElement,\n contextualText,\n placeholder,\n addressSearchDebounceMs\n}: Readonly<AddressSearchProps>) {\n const [formattedData, setFormattedData] = useState<AddressLookupItem[]>([]);\n const [originalData, setOriginalData] = useState<AddressLookupItem[]>([]);\n\n const [errorMessage, setErrorMessage] = useState('');\n\n const { i18n } = useCoreContext();\n const mapDataToSelect = data => data.map(({ id, name }) => ({ id, name }));\n\n const handlePromiseReject = useCallback((reason: RejectionReason) => {\n if (reason?.errorMessage) {\n setErrorMessage(reason.errorMessage);\n }\n }, []);\n\n const onTextInput = useCallback(\n (inputValue: string) => {\n new Promise<Array<AddressLookupItem>>((resolve, reject) => {\n void onAddressLookup(inputValue, { resolve, reject });\n })\n .then(searchArray => {\n setOriginalData(searchArray);\n setFormattedData(mapDataToSelect(searchArray));\n setErrorMessage('');\n })\n .catch(reason => handlePromiseReject(reason));\n },\n [onAddressLookup]\n );\n\n // update error message when there's a new one\n useEffect(() => {\n setErrorMessage(externalErrorMessage);\n }, [externalErrorMessage]);\n\n const onSelectItem = event => {\n if (!event.target.value) {\n setErrorMessage(i18n.get('address.errors.incomplete'));\n return;\n }\n const value = originalData.find(item => item.id === event.target.value);\n\n // 1. in case we don't get a function just select item\n if (typeof onAddressSelected !== 'function') {\n onSelect(value);\n setFormattedData([]);\n return;\n }\n\n // 2. in case callback is provided, create and call onAddressSelected\n new Promise<AddressLookupItem>((resolve, reject) => {\n void onAddressSelected(value, { resolve, reject });\n })\n .then(fullData => {\n onSelect(fullData);\n setFormattedData([]);\n })\n .catch(reason => handlePromiseReject(reason));\n };\n\n const debounceInputHandler = useMemo(() => debounce(onTextInput, addressSearchDebounceMs), []);\n\n return (\n // The search field is intentionally rendered before the manual entry button in the DOM.\n // See: ../a11y.md\n <div className={'adyen-checkout__address-search adyen-checkout__field-group'}>\n <Field\n label={i18n.get('address')}\n classNameModifiers={['address-search']}\n errorMessage={errorMessage}\n name={'address-search'}\n showContextualElement={showContextualElement}\n contextualText={contextualText}\n >\n <Select\n name={'address-search'}\n className={'adyen-checkout__address-search__dropdown'}\n placeholder={placeholder}\n onInput={debounceInputHandler}\n items={formattedData}\n onChange={onSelectItem}\n disableTextFilter={true}\n blurOnClose={true}\n />\n </Field>\n {!hideManualButton && (\n <span className=\"adyen-checkout__address-search__manual-add\">\n <button\n type=\"button\"\n className=\"adyen-checkout__button adyen-checkout__button--inline adyen-checkout__button--link adyen-checkout__address-search__manual-add__button\"\n onClick={onManualAddress}\n >\n {'+ ' + i18n.get('address.enterManually')}\n </button>\n </span>\n )}\n </div>\n );\n}\n"],"names":["AddressSearch","onAddressLookup","onAddressSelected","onSelect","onManualAddress","externalErrorMessage","hideManualButton","showContextualElement","contextualText","placeholder","addressSearchDebounceMs","formattedData","setFormattedData","useState","originalData","setOriginalData","errorMessage","setErrorMessage","i18n","useCoreContext","handlePromiseReject","useCallback","reason","onTextInput","inputValue","Promise","resolve","reject","then","searchArray","map","id","name","catch","useEffect","debounceInputHandler","useMemo","debounce","h","div","className","Field","label","get","classNameModifiers","Select","onInput","items","onChange","event","target","value","find","item","fullData","disableTextFilter","blurOnClose","span","button","type","onClick"],"mappings":"saA2Ce,SAASA,GAAcC,gBAClCA,EAAeC,kBACfA,EAAiBC,SACjBA,EAAQC,gBACRA,EAAeC,qBACfA,EAAoBC,iBACpBA,EAAgBC,sBAChBA,EAAqBC,eACrBA,EAAcC,YACdA,EAAWC,wBACXA,IAEA,MAAOC,EAAeC,GAAoBC,EAA8B,KACjEC,EAAcC,GAAmBF,EAA8B,KAE/DG,EAAcC,GAAmBJ,EAAS,KAE3CK,KAAEA,GAASC,IAGXC,EAAsBC,EAAaC,IACjCA,GAAQN,cACRC,EAAgBK,EAAON,eAE5B,IAEGO,EAAcF,EACfG,IACG,IAAIC,QAAkC,CAACC,EAASC,KACvC1B,EAAgBuB,EAAY,CAAEE,UAASC,aAE3CC,KAAKC,IACFd,EAAgBc,GAChBjB,EAAiCiB,EAfZC,IAAI,EAAGC,KAAIC,WAAM,CAAQD,KAAIC,WAgBlDf,EAAgB,MAEnBgB,MAAMX,GAAUF,EAAoBE,KAE7C,CAACrB,IAILiC,EAAU,KACNjB,EAAgBZ,IACjB,CAACA,IAEJ,MAyBM8B,EAAuBC,EAAQ,IAAMC,EAASd,EAAab,GAA0B,IAE3F,OAGI4B,EAACC,MAAAA,CAAIC,UAAW,8DACZF,EAACG,EAAAA,CACGC,MAAOxB,EAAKyB,IAAI,WAChBC,m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