@adyen/adyen-web 6.19.0 → 6.21.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/README.md +1 -1
- package/dist/cjs/adyen.css +10 -11
- 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 +43 -65
- package/dist/es/adyen.css +10 -11
- package/dist/es/adyen.css.map +1 -1
- package/dist/es/components/Ach/Ach.js +1 -1
- package/dist/es/components/Ach/Ach.js.map +1 -1
- package/dist/es/components/Ach/components/AchComponent.js +1 -1
- package/dist/es/components/Ach/components/AchComponent.js.map +1 -1
- package/dist/es/components/Ach/components/useSRPanelForACHErrors.js.map +1 -1
- package/dist/es/components/Card/Card.js +1 -1
- package/dist/es/components/Card/Card.js.map +1 -1
- package/dist/es/components/Card/components/CardInput/components/CardFieldsWrapper.js +1 -1
- package/dist/es/components/Card/components/CardInput/components/CardFieldsWrapper.js.map +1 -1
- package/dist/es/components/Card/components/CardInput/components/Installments/Installments.js +1 -1
- package/dist/es/components/Card/components/CardInput/components/Installments/Installments.js.map +1 -1
- package/dist/es/components/Card/components/CardInput/handlers.js.map +1 -1
- package/dist/es/components/Card/components/CardInput/useSRPanelForCardInputErrors.js.map +1 -1
- package/dist/es/components/Card/components/CardInput/utils.js +1 -1
- package/dist/es/components/Card/components/CardInput/utils.js.map +1 -1
- package/dist/es/components/Dropin/Dropin.js +1 -1
- package/dist/es/components/Dropin/Dropin.js.map +1 -1
- package/dist/es/components/Giftcard/components/useSRPanelForGiftcardErrors.js.map +1 -1
- package/dist/es/components/PayByBankPix/PayByBankPix.js +1 -1
- package/dist/es/components/PayByBankPix/PayByBankPix.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/PayByBankPix/components/Enrollment/components/IssuerListIntroduction.js +1 -1
- package/dist/es/components/PayByBankPix/components/Enrollment/components/IssuerListIntroduction.js.map +1 -1
- package/dist/es/components/PayByBankPix/components/Enrollment/useIssuerWithLogo.js +1 -1
- package/dist/es/components/PayByBankPix/components/Enrollment/useIssuerWithLogo.js.map +1 -1
- package/dist/es/components/PayByBankPix/components/StoredPayment/StoredPayment.js +1 -1
- package/dist/es/components/PayByBankPix/components/StoredPayment/StoredPayment.js.map +1 -1
- package/dist/es/components/PayPal/utils/get-paypal-styles.js.map +1 -1
- package/dist/es/components/PayPalFastlane/FastlaneSDK.js.map +1 -1
- package/dist/es/components/ThreeDS2/components/Challenge/PrepareChallenge3DS2.js.map +1 -1
- package/dist/es/components/ThreeDS2/components/DeviceFingerprint/PrepareFingerprint3DS2.js.map +1 -1
- package/dist/es/components/UPI/UPI.js +1 -1
- package/dist/es/components/UPI/UPI.js.map +1 -1
- package/dist/es/components/UPI/components/UPIComponent/UPIComponent.js +1 -1
- package/dist/es/components/UPI/components/UPIComponent/UPIComponent.js.map +1 -1
- package/dist/es/components/UPI/components/UPIIntentAppList/UPIIntentAppItem/UPIIntentAppItem.js +1 -1
- package/dist/es/components/UPI/components/UPIIntentAppList/UPIIntentAppItem/UPIIntentAppItem.js.map +1 -1
- package/dist/es/components/UPI/components/UPIIntentAppList/UPIIntentAppList.js +1 -1
- package/dist/es/components/UPI/components/UPIIntentAppList/UPIIntentAppList.js.map +1 -1
- package/dist/es/components/UPI/constants.js +2 -0
- package/dist/es/components/UPI/constants.js.map +1 -0
- package/dist/es/components/internal/Address/Address.js.map +1 -1
- package/dist/es/components/internal/Alert/Alert.js +1 -1
- package/dist/es/components/internal/Alert/Alert.js.map +1 -1
- package/dist/es/components/internal/ClickToPay/models/ShopperCard.js +1 -1
- package/dist/es/components/internal/ClickToPay/models/ShopperCard.js.map +1 -1
- package/dist/es/components/internal/IbanInput/IbanInput.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/OpenInvoice/useSRPanelForOpenInvoiceErrors.js.map +1 -1
- package/dist/es/components/internal/PayButton/PayButton.js +1 -1
- package/dist/es/components/internal/PayButton/PayButton.js.map +1 -1
- package/dist/es/components/internal/PayButton/components/SecondaryButtonLabel.js.map +1 -1
- package/dist/es/components/internal/SecuredFields/SFP/SecuredFieldsProvider.js.map +1 -1
- package/dist/es/components/internal/SecuredFields/binLookup/createCardVariantSwitcher.js +1 -1
- package/dist/es/components/internal/SecuredFields/binLookup/createCardVariantSwitcher.js.map +1 -1
- package/dist/es/components/internal/SecuredFields/binLookup/extensions.js +1 -1
- package/dist/es/components/internal/SecuredFields/binLookup/extensions.js.map +1 -1
- package/dist/es/components/internal/SecuredFields/binLookup/triggerBinLookUp.js.map +1 -1
- package/dist/es/components/internal/SecuredFields/lib/CSF/extensions/handleIOSTouchEvents.js.map +1 -1
- package/dist/es/components/internal/SegmentedControl/SegmentedControl.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.map +1 -1
- package/dist/es/core/Analytics/utils.js.map +1 -1
- package/dist/es/core/Errors/SRPanel.js.map +1 -1
- package/dist/es/core/Errors/utils.js.map +1 -1
- package/dist/es/core/Services/analytics/collect-id.js +1 -1
- package/dist/es/core/core.js +1 -1
- package/dist/es/core/core.registry.js.map +1 -1
- package/dist/es/core/utils.js.map +1 -1
- package/dist/es/external/preact/compat/dist/compat.js.map +1 -1
- package/dist/es/external/preact/dist/preact.js.map +1 -1
- package/dist/es/index.d.ts +43 -65
- package/dist/es/language/utils.js.map +1 -1
- package/dist/es/utils/clipboard.js.map +1 -1
- package/dist/es/utils/setFocus.js.map +1 -1
- package/dist/es/utils/useForm/reducer.js.map +1 -1
- package/dist/es-legacy/adyen.css +10 -11
- package/dist/es-legacy/adyen.css.map +1 -1
- package/dist/es-legacy/components/Ach/Ach.js +1 -1
- package/dist/es-legacy/components/Ach/Ach.js.map +1 -1
- package/dist/es-legacy/components/Ach/components/AchComponent.js +1 -1
- package/dist/es-legacy/components/Ach/components/AchComponent.js.map +1 -1
- package/dist/es-legacy/components/Ach/components/useSRPanelForACHErrors.js.map +1 -1
- package/dist/es-legacy/components/Card/Card.js +1 -1
- package/dist/es-legacy/components/Card/Card.js.map +1 -1
- package/dist/es-legacy/components/Card/components/CardInput/components/CardFieldsWrapper.js +1 -1
- package/dist/es-legacy/components/Card/components/CardInput/components/CardFieldsWrapper.js.map +1 -1
- package/dist/es-legacy/components/Card/components/CardInput/components/Installments/Installments.js +1 -1
- package/dist/es-legacy/components/Card/components/CardInput/components/Installments/Installments.js.map +1 -1
- package/dist/es-legacy/components/Card/components/CardInput/handlers.js.map +1 -1
- package/dist/es-legacy/components/Card/components/CardInput/useSRPanelForCardInputErrors.js.map +1 -1
- package/dist/es-legacy/components/Card/components/CardInput/utils.js +1 -1
- package/dist/es-legacy/components/Card/components/CardInput/utils.js.map +1 -1
- package/dist/es-legacy/components/Dropin/Dropin.js +1 -1
- package/dist/es-legacy/components/Dropin/Dropin.js.map +1 -1
- package/dist/es-legacy/components/Giftcard/components/useSRPanelForGiftcardErrors.js.map +1 -1
- package/dist/es-legacy/components/PayByBankPix/PayByBankPix.js +1 -1
- package/dist/es-legacy/components/PayByBankPix/PayByBankPix.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/PayByBankPix/components/Enrollment/components/IssuerListIntroduction.js +1 -1
- package/dist/es-legacy/components/PayByBankPix/components/Enrollment/components/IssuerListIntroduction.js.map +1 -1
- package/dist/es-legacy/components/PayByBankPix/components/Enrollment/useIssuerWithLogo.js +1 -1
- package/dist/es-legacy/components/PayByBankPix/components/Enrollment/useIssuerWithLogo.js.map +1 -1
- package/dist/es-legacy/components/PayByBankPix/components/StoredPayment/StoredPayment.js +1 -1
- package/dist/es-legacy/components/PayByBankPix/components/StoredPayment/StoredPayment.js.map +1 -1
- package/dist/es-legacy/components/PayPal/utils/get-paypal-styles.js.map +1 -1
- package/dist/es-legacy/components/PayPalFastlane/FastlaneSDK.js.map +1 -1
- package/dist/es-legacy/components/ThreeDS2/components/Challenge/PrepareChallenge3DS2.js.map +1 -1
- package/dist/es-legacy/components/ThreeDS2/components/DeviceFingerprint/PrepareFingerprint3DS2.js.map +1 -1
- package/dist/es-legacy/components/UPI/UPI.js +1 -1
- package/dist/es-legacy/components/UPI/UPI.js.map +1 -1
- package/dist/es-legacy/components/UPI/components/UPIComponent/UPIComponent.js +1 -1
- package/dist/es-legacy/components/UPI/components/UPIComponent/UPIComponent.js.map +1 -1
- package/dist/es-legacy/components/UPI/components/UPIIntentAppList/UPIIntentAppItem/UPIIntentAppItem.js +1 -1
- package/dist/es-legacy/components/UPI/components/UPIIntentAppList/UPIIntentAppItem/UPIIntentAppItem.js.map +1 -1
- package/dist/es-legacy/components/UPI/components/UPIIntentAppList/UPIIntentAppList.js +1 -1
- package/dist/es-legacy/components/UPI/components/UPIIntentAppList/UPIIntentAppList.js.map +1 -1
- package/dist/es-legacy/components/UPI/constants.js +2 -0
- package/dist/es-legacy/components/UPI/constants.js.map +1 -0
- package/dist/es-legacy/components/internal/Address/Address.js.map +1 -1
- package/dist/es-legacy/components/internal/Alert/Alert.js +1 -1
- package/dist/es-legacy/components/internal/Alert/Alert.js.map +1 -1
- package/dist/es-legacy/components/internal/ClickToPay/models/ShopperCard.js +1 -1
- package/dist/es-legacy/components/internal/ClickToPay/models/ShopperCard.js.map +1 -1
- package/dist/es-legacy/components/internal/IbanInput/IbanInput.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/OpenInvoice/useSRPanelForOpenInvoiceErrors.js.map +1 -1
- package/dist/es-legacy/components/internal/PayButton/PayButton.js +1 -1
- package/dist/es-legacy/components/internal/PayButton/PayButton.js.map +1 -1
- package/dist/es-legacy/components/internal/PayButton/components/SecondaryButtonLabel.js.map +1 -1
- package/dist/es-legacy/components/internal/SecuredFields/SFP/SecuredFieldsProvider.js.map +1 -1
- package/dist/es-legacy/components/internal/SecuredFields/binLookup/createCardVariantSwitcher.js +1 -1
- package/dist/es-legacy/components/internal/SecuredFields/binLookup/createCardVariantSwitcher.js.map +1 -1
- package/dist/es-legacy/components/internal/SecuredFields/binLookup/extensions.js +1 -1
- package/dist/es-legacy/components/internal/SecuredFields/binLookup/extensions.js.map +1 -1
- package/dist/es-legacy/components/internal/SecuredFields/binLookup/triggerBinLookUp.js.map +1 -1
- package/dist/es-legacy/components/internal/SecuredFields/lib/CSF/extensions/handleIOSTouchEvents.js.map +1 -1
- package/dist/es-legacy/components/internal/SegmentedControl/SegmentedControl.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.map +1 -1
- package/dist/es-legacy/core/Analytics/utils.js.map +1 -1
- package/dist/es-legacy/core/Errors/SRPanel.js.map +1 -1
- package/dist/es-legacy/core/Errors/utils.js.map +1 -1
- package/dist/es-legacy/core/Services/analytics/collect-id.js +1 -1
- package/dist/es-legacy/core/core.js +1 -1
- package/dist/es-legacy/core/core.registry.js.map +1 -1
- package/dist/es-legacy/core/utils.js.map +1 -1
- package/dist/es-legacy/external/preact/compat/dist/compat.js.map +1 -1
- package/dist/es-legacy/external/preact/dist/preact.js.map +1 -1
- package/dist/es-legacy/language/utils.js.map +1 -1
- package/dist/es-legacy/utils/clipboard.js.map +1 -1
- package/dist/es-legacy/utils/setFocus.js.map +1 -1
- package/dist/es-legacy/utils/useForm/reducer.js.map +1 -1
- package/package.json +159 -159
- package/styles/adyen.css +10 -11
- package/dist/es/components/UPI/components/UPIComponent/constants.js +0 -2
- package/dist/es/components/UPI/components/UPIComponent/constants.js.map +0 -1
- package/dist/es/components/UPI/components/UPIComponent/useUpiSegmentedControlOptions.js +0 -2
- package/dist/es/components/UPI/components/UPIComponent/useUpiSegmentedControlOptions.js.map +0 -1
- package/dist/es-legacy/components/UPI/components/UPIComponent/constants.js +0 -2
- package/dist/es-legacy/components/UPI/components/UPIComponent/constants.js.map +0 -1
- package/dist/es-legacy/components/UPI/components/UPIComponent/useUpiSegmentedControlOptions.js +0 -2
- package/dist/es-legacy/components/UPI/components/UPIComponent/useUpiSegmentedControlOptions.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"handlers.js","sources":["../../../../../../src/components/Card/components/CardInput/handlers.ts"],"sourcesContent":["import { ENCRYPTED_CARD_NUMBER, CREDIT_CARD_SF_FIELDS } from '../../../internal/SecuredFields/lib/constants';\nimport { selectOne } from '../../../internal/SecuredFields/lib/utilities/dom';\nimport { CardFocusData } from '../../../internal/SecuredFields/lib/types';\n\n/**\n * Helper for CardInput - gets a field name and sets focus on it\n */\nexport const setFocusOnFirstField = (isValidating, sfp, fieldToFocus) => {\n if (isValidating) {\n // If not a cardInput related securedField - find field and set focus on it\n if (!CREDIT_CARD_SF_FIELDS.includes(fieldToFocus)) {\n setFocusOnNonSF(fieldToFocus, sfp);\n } else {\n // Is a securedField - so it has its own focus procedures\n sfp.current.setFocusOn(fieldToFocus);\n }\n }\n};\n\nexport const getAddressHandler = (setFormData, setFormValid, setFormErrors) => {\n // Return Handler fn:\n return address => {\n setFormData('billingAddress', address.data);\n setFormValid('billingAddress', address.isValid);\n setFormErrors('billingAddress', address.errors);\n };\n};\n\nexport const getFocusHandler = (setFocusedElement, onFocus, onBlur) => {\n // Return Handler fn:\n return (e: CardFocusData) => {\n setFocusedElement(e.currentFocusObject);\n e.focus === true ? onFocus(e.fieldType, e) : onBlur(e.fieldType, e);\n };\n};\n\nexport const getAutoJumpHandler = (isAutoJumping, sfp, layout) => {\n return () => {\n if (!isAutoJumping.current) {\n isAutoJumping.current = true;\n\n // CardInput can call this more than once in quick succession\n // e.g. if field was in error (error + fieldValid) or other SFs are optional (fieldValid + allValid) etc\n // - so make async to avoid double setFocus call\n void Promise.resolve().then(() => {\n const panIndex = layout.findIndex(elem => elem === ENCRYPTED_CARD_NUMBER);\n const subsequentFields = layout.slice(panIndex + 1);\n\n /**\n * Investigate subsequent fields to see if they can/should accept focus\n */\n for (const field of subsequentFields) {\n // Is the next field a credit card related securedField?\n if (CREDIT_CARD_SF_FIELDS.includes(field)) {\n const isOptionalOrHidden = sfp.current.sfIsOptionalOrHidden(field);\n if (!isOptionalOrHidden) {\n sfp.current.setFocusOn(field);\n break;\n }\n } else {\n // If it isn't an SF - shift focus to it (we're currently not concerned with whether the field is optional)\n\n setFocusOnNonSF(field, sfp);\n break;\n }\n }\n\n isAutoJumping.current = false;\n });\n }\n };\n};\n\nconst setFocusOnNonSF = (field, sfp) => {\n let nameVal: string = field;\n\n // We have an exception with the kcp taxNumber where the name of the field ('kcpTaxNumberOrDOB') doesn't match\n // the value by which the field is referred to internally ('taxNumber')\n if (nameVal === 'taxNumber') nameVal = 'kcpTaxNumberOrDOB';\n\n if (nameVal === 'country' || nameVal === 'stateOrProvince') {\n // Set focus on dropdown\n const field: HTMLElement = selectOne(sfp.current.rootNode, `.adyen-checkout__field--${nameVal} .adyen-checkout__filter-input`);\n field?.focus();\n } else {\n // Set focus on input\n const field: HTMLElement = selectOne(sfp.current.rootNode, `[name=\"${nameVal}\"]`);\n field?.focus();\n }\n};\n"],"names":["setFocusOnFirstField","isValidating","sfp","fieldToFocus","CREDIT_CARD_SF_FIELDS","includes","current","setFocusOn","setFocusOnNonSF","getAddressHandler","setFormData","setFormValid","setFormErrors","address","data","isValid","errors","getFocusHandler","setFocusedElement","onFocus","onBlur","e","currentFocusObject","focus","fieldType","getAutoJumpHandler","isAutoJumping","layout","Promise","resolve","then","panIndex","findIndex","elem","ENCRYPTED_CARD_NUMBER","subsequentFields","slice","field","sfIsOptionalOrHidden","nameVal","selectOne","rootNode"],"mappings":"qMAOO,MAAMA,EAAuB,CAACC,EAAcC,EAAKC,KAChDF,IAEKG,EAAsBC,SAASF,GAIhCD,EAAII,QAAQC,WAAWJ,GAHvBK,EAAgBL,EAAcD,KAQ7BO,EAAoB,CAACC,EAAaC,EAAcC,IAElDC,IACHH,EAAY,iBAAkBG,EAAQC,MACtCH,EAAa,iBAAkBE,EAAQE,SACvCH,EAAc,iBAAkBC,EAAQG,SAInCC,EAAkB,CAACC,EAAmBC,EAASC,IAEhDC,IACJH,EAAkBG,EAAEC,qBACR,IAAZD,EAAEE,MAAiBJ,EAAQE,EAAEG,UAAWH,GAAKD,EAAOC,EAAEG,UAAWH,IAI5DI,EAAqB,CAACC,EAAexB,EAAKyB,IAC5C,KACED,EAAcpB,UACfoB,EAAcpB,SAAU,EAKnBsB,QAAQC,UAAUC,KAAK,KACxB,MAAMC,EAAWJ,EAAOK,UAAUC,GAAQA,IAASC,GAC7CC,EAAmBR,EAAOS,MAAML,EAAW,GAKjD,IAAK,MAAMM,KAASF,EAAkB,CAElC,IAAI/B,EAAsBC,SAASgC,GAM5B,CAGH7B,EAAgB6B,EAAOnC,GACvB,KACJ,CATI,IAD2BA,EAAII,QAAQgC,qBAAqBD,GACnC,CACrBnC,EAAII,QAAQC,WAAW8B,GACvB,KACJ,CAOR,CAEAX,EAAcpB,SAAU,MAMlCE,EAAkB,CAAC6B,EAAOnC,KAC5B,IAAIqC,EAAkBF,EAMtB,GAFgB,cAAZE,IAAyBA,EAAU,qBAEvB,YAAZA,GAAqC,oBAAZA,EAA+B,CAExD,MAAMF,EAAqBG,EAAUtC,EAAII,QAAQmC,SAAU,2BAA2BF,mCACtFF,GAAOd,
|
|
1
|
+
{"version":3,"file":"handlers.js","sources":["../../../../../../src/components/Card/components/CardInput/handlers.ts"],"sourcesContent":["import { ENCRYPTED_CARD_NUMBER, CREDIT_CARD_SF_FIELDS } from '../../../internal/SecuredFields/lib/constants';\nimport { selectOne } from '../../../internal/SecuredFields/lib/utilities/dom';\nimport { CardFocusData } from '../../../internal/SecuredFields/lib/types';\n\n/**\n * Helper for CardInput - gets a field name and sets focus on it\n */\nexport const setFocusOnFirstField = (isValidating, sfp, fieldToFocus) => {\n if (isValidating) {\n // If not a cardInput related securedField - find field and set focus on it\n if (!CREDIT_CARD_SF_FIELDS.includes(fieldToFocus)) {\n setFocusOnNonSF(fieldToFocus, sfp);\n } else {\n // Is a securedField - so it has its own focus procedures\n sfp.current.setFocusOn(fieldToFocus);\n }\n }\n};\n\nexport const getAddressHandler = (setFormData, setFormValid, setFormErrors) => {\n // Return Handler fn:\n return address => {\n setFormData('billingAddress', address.data);\n setFormValid('billingAddress', address.isValid);\n setFormErrors('billingAddress', address.errors);\n };\n};\n\nexport const getFocusHandler = (setFocusedElement, onFocus, onBlur) => {\n // Return Handler fn:\n return (e: CardFocusData) => {\n setFocusedElement(e.currentFocusObject);\n e.focus === true ? onFocus(e.fieldType, e) : onBlur(e.fieldType, e);\n };\n};\n\nexport const getAutoJumpHandler = (isAutoJumping, sfp, layout) => {\n return () => {\n if (!isAutoJumping.current) {\n isAutoJumping.current = true;\n\n // CardInput can call this more than once in quick succession\n // e.g. if field was in error (error + fieldValid) or other SFs are optional (fieldValid + allValid) etc\n // - so make async to avoid double setFocus call\n void Promise.resolve().then(() => {\n const panIndex = layout.findIndex(elem => elem === ENCRYPTED_CARD_NUMBER);\n const subsequentFields = layout.slice(panIndex + 1);\n\n /**\n * Investigate subsequent fields to see if they can/should accept focus\n */\n for (const field of subsequentFields) {\n // Is the next field a credit card related securedField?\n if (CREDIT_CARD_SF_FIELDS.includes(field)) {\n const isOptionalOrHidden = sfp.current.sfIsOptionalOrHidden(field);\n if (!isOptionalOrHidden) {\n sfp.current.setFocusOn(field);\n break;\n }\n } else {\n // If it isn't an SF - shift focus to it (we're currently not concerned with whether the field is optional)\n\n setFocusOnNonSF(field, sfp);\n break;\n }\n }\n\n isAutoJumping.current = false;\n });\n }\n };\n};\n\nconst setFocusOnNonSF = (field, sfp) => {\n let nameVal: string = field;\n\n // We have an exception with the kcp taxNumber where the name of the field ('kcpTaxNumberOrDOB') doesn't match\n // the value by which the field is referred to internally ('taxNumber')\n if (nameVal === 'taxNumber') nameVal = 'kcpTaxNumberOrDOB';\n\n if (nameVal === 'country' || nameVal === 'stateOrProvince') {\n // Set focus on dropdown\n const field: HTMLElement = selectOne(sfp.current.rootNode, `.adyen-checkout__field--${nameVal} .adyen-checkout__filter-input`);\n field?.focus();\n } else {\n // Set focus on input\n const field: HTMLElement = selectOne(sfp.current.rootNode, `[name=\"${nameVal}\"]`);\n field?.focus();\n }\n};\n"],"names":["setFocusOnFirstField","isValidating","sfp","fieldToFocus","CREDIT_CARD_SF_FIELDS","includes","current","setFocusOn","setFocusOnNonSF","getAddressHandler","setFormData","setFormValid","setFormErrors","address","data","isValid","errors","getFocusHandler","setFocusedElement","onFocus","onBlur","e","currentFocusObject","focus","fieldType","getAutoJumpHandler","isAutoJumping","layout","Promise","resolve","then","panIndex","findIndex","elem","ENCRYPTED_CARD_NUMBER","subsequentFields","slice","field","sfIsOptionalOrHidden","nameVal","selectOne","rootNode"],"mappings":"qMAOO,MAAMA,EAAuB,CAACC,EAAcC,EAAKC,KAChDF,IAEKG,EAAsBC,SAASF,GAIhCD,EAAII,QAAQC,WAAWJ,GAHvBK,EAAgBL,EAAcD,KAQ7BO,EAAoB,CAACC,EAAaC,EAAcC,IAElDC,IACHH,EAAY,iBAAkBG,EAAQC,MACtCH,EAAa,iBAAkBE,EAAQE,SACvCH,EAAc,iBAAkBC,EAAQG,SAInCC,EAAkB,CAACC,EAAmBC,EAASC,IAEhDC,IACJH,EAAkBG,EAAEC,qBACR,IAAZD,EAAEE,MAAiBJ,EAAQE,EAAEG,UAAWH,GAAKD,EAAOC,EAAEG,UAAWH,IAI5DI,EAAqB,CAACC,EAAexB,EAAKyB,IAC5C,KACED,EAAcpB,UACfoB,EAAcpB,SAAU,EAKnBsB,QAAQC,UAAUC,KAAK,KACxB,MAAMC,EAAWJ,EAAOK,UAAUC,GAAQA,IAASC,GAC7CC,EAAmBR,EAAOS,MAAML,EAAW,GAKjD,IAAK,MAAMM,KAASF,EAAkB,CAElC,IAAI/B,EAAsBC,SAASgC,GAM5B,CAGH7B,EAAgB6B,EAAOnC,GACvB,KACJ,CATI,IAD2BA,EAAII,QAAQgC,qBAAqBD,GACnC,CACrBnC,EAAII,QAAQC,WAAW8B,GACvB,KACJ,CAOR,CAEAX,EAAcpB,SAAU,MAMlCE,EAAkB,CAAC6B,EAAOnC,KAC5B,IAAIqC,EAAkBF,EAMtB,GAFgB,cAAZE,IAAyBA,EAAU,qBAEvB,YAAZA,GAAqC,oBAAZA,EAA+B,CAExD,MAAMF,EAAqBG,EAAUtC,EAAII,QAAQmC,SAAU,2BAA2BF,mCACtFF,GAAOd,OACX,KAAO,CAEH,MAAMc,EAAqBG,EAAUtC,EAAII,QAAQmC,SAAU,UAAUF,OACrEF,GAAOd,OACX"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useSRPanelForCardInputErrors.js","sources":["../../../../../../src/components/Card/components/CardInput/useSRPanelForCardInputErrors.ts"],"sourcesContent":["import { useEffect, useState } from 'preact/hooks';\nimport useSRPanelContext from '../../../../core/Errors/useSRPanelContext';\nimport { SetSRMessagesReturnFn } from '../../../../core/Errors/SRPanelProvider';\nimport { handlePartialAddressMode, lookupBlurBasedErrors, mapFieldKey } from './utils';\nimport { usePrevious } from '../../../../utils/hookUtils';\nimport { SetSRMessagesReturnObject, SortedErrorObject } from '../../../../core/Errors/types';\nimport { ERROR_ACTION_BLUR_SCENARIO, ERROR_ACTION_FOCUS_FIELD } from '../../../../core/Errors/constants';\nimport { setFocusOnFirstField } from './handlers';\nimport { getArrayDifferences } from '../../../../utils/arrayUtils';\n\nconst useSRPanelForCardInputErrors = ({ errors, props, isValidating, retrieveLayout, specifications, billingAddress, sfp }) => {\n // Extract fns from context\n const { setSRMessagesFromObjects, setSRMessagesFromStrings, clearSRPanel, shouldMoveFocusSR } = useSRPanelContext();\n\n // Generate a setSRMessages function - implemented as a partial, since the initial set of arguments don't change.\n const setSRMessages: SetSRMessagesReturnFn = setSRMessagesFromObjects?.({\n fieldTypeMappingFn: mapFieldKey\n });\n\n const partialAddressSchema = handlePartialAddressMode(props.billingAddressMode);\n\n const [sortedErrorList, setSortedErrorList] = useState<SortedErrorObject[]>(null);\n\n // Get the previous list of errors\n const previousSortedErrors = usePrevious(sortedErrorList);\n\n const sfStateErrorsObj = sfp.current?.mapErrorsToValidationRuleResult();\n const mergedErrors = { ...errors, ...sfStateErrorsObj };\n\n useEffect(() => {\n try {\n // Extract and then flatten billingAddress errors into a new object with *all* the field errors at top level\n const { billingAddress: extractedAddressErrors, ...errorsWithoutAddress } = mergedErrors;\n\n const errorsForPanel = { ...errorsWithoutAddress, ...extractedAddressErrors };\n\n // Pass dynamic props (errors, layout etc) to SRPanel via partial\n const srPanelResp: SetSRMessagesReturnObject = setSRMessages?.({\n errors: errorsForPanel,\n isValidating: isValidating.current,\n layout: retrieveLayout(),\n // If we don't have country specific address labels, we might have a label related to a partialAddressSchema (i.e. zipCode)\n countrySpecificLabels: specifications.getAddressLabelsForCountry(billingAddress?.country) ?? partialAddressSchema?.default?.labels\n });\n\n // Store the array of sorted error objects separately so that we can use it to make comparisons between the old and new arrays\n const currentErrorsSortedByLayout = srPanelResp?.currentErrorsSortedByLayout;\n setSortedErrorList(currentErrorsSortedByLayout);\n\n /**\n * Need extra actions after setting SRPanel messages in order to focus field (if required) and because we have some errors that are fired onBlur\n */\n switch (srPanelResp?.action) {\n // A call to focus the first field in error will always follow the call to validate the whole form\n case ERROR_ACTION_FOCUS_FIELD:\n if (shouldMoveFocusSR) setFocusOnFirstField(isValidating.current, sfp, srPanelResp?.fieldToFocus);\n // Remove 'showValidation' mode - allowing time for collation of all the fields in error whilst it is 'showValidation' mode (some errors come in a second render pass)\n setTimeout(() => {\n isValidating.current = false;\n }, 300);\n break;\n\n /**\n * Relates to errors triggered by a field blurring (some pm forms have this, some don't) - check if there is an error to either set or to clear\n */\n case ERROR_ACTION_BLUR_SCENARIO: {\n const difference = getArrayDifferences<SortedErrorObject, string>(currentErrorsSortedByLayout, previousSortedErrors, 'field');\n\n const latestErrorMsg = difference?.[0];\n\n if (latestErrorMsg) {\n // Use the error code to look up whether error is actually a blur based one (most are but some SF ones aren't)\n const isBlurBasedError = lookupBlurBasedErrors(latestErrorMsg.errorCode);\n\n /**\n * ONLY ADD BLUR BASED ERRORS TO THE ERROR PANEL - doing this step prevents the non-blur based errors from being read out twice\n * (once from the aria-live, error panel & once from the aria-describedby element)\n */\n const latestSRError = isBlurBasedError ? latestErrorMsg.errorMessage : null;\n // console.log('### CardInput2::componentDidUpdate:: #2 (not validating) single error:: latestSRError', latestSRError);\n setSRMessagesFromStrings(latestSRError);\n } else {\n // called when previousSortedErrors.length >= currentErrorsSortedByLayout.length\n // console.log('### CardInput2::componentDidUpdate:: #3(not validating) clearing errors:: NO latestErrorMsg');\n clearSRPanel();\n }\n break;\n }\n default:\n break;\n }\n } catch (_) {\n // We don't handle the error related to the sr panel, let it fail silently.\n }\n }, [errors]);\n\n return { sortedErrorList, previousSortedErrors, clearSRPanel };\n};\n\nexport default useSRPanelForCardInputErrors;\n"],"names":["useSRPanelForCardInputErrors","errors","props","isValidating","retrieveLayout","specifications","billingAddress","sfp","setSRMessagesFromObjects","setSRMessagesFromStrings","clearSRPanel","shouldMoveFocusSR","useSRPanelContext","setSRMessages","fieldTypeMappingFn","mapFieldKey","partialAddressSchema","handlePartialAddressMode","billingAddressMode","sortedErrorList","setSortedErrorList","useState","previousSortedErrors","usePrevious","sfStateErrorsObj","current","mapErrorsToValidationRuleResult","mergedErrors","useEffect","extractedAddressErrors","errorsWithoutAddress","errorsForPanel","srPanelResp","layout","countrySpecificLabels","getAddressLabelsForCountry","country","default","labels","currentErrorsSortedByLayout","action","ERROR_ACTION_FOCUS_FIELD","setFocusOnFirstField","fieldToFocus","setTimeout","ERROR_ACTION_BLUR_SCENARIO","difference","getArrayDifferences","latestErrorMsg","latestSRError","lookupBlurBasedErrors","errorCode","errorMessage","_"],"mappings":"giBAUA,MAAMA,EAA+B,EAAGC,SAAQC,QAAOC,eAAcC,iBAAgBC,iBAAgBC,iBAAgBC,UAEjH,MAAMC,yBAAEA,EAAwBC,yBAAEA,EAAwBC,aAAEA,EAAYC,kBAAEA,GAAsBC,IAG1FC,EAAuCL,IAA2B,CACpEM,mBAAoBC,IAGlBC,EAAuBC,EAAyBf,EAAMgB,qBAErDC,EAAiBC,GAAsBC,EAA8B,MAGtEC,EAAuBC,EAAYJ,GAEnCK,EAAmBjB,EAAIkB,SAASC,kCAChCC,EAAe,IAAK1B,KAAWuB,GAqErC,OAnEAI,EAAU,KACN,IAEI,MAAQtB,eAAgBuB,KAA2BC,GAAyBH,EAEtEI,EAAiB,IAAKD,KAAyBD,GAG/CG,EAAyCnB,IAAgB,CAC3DZ,OAAQ8B,EACR5B,aAAcA,EAAasB,QAC3BQ,OAAQ7B,IAER8B,sBAAuB7B,EAAe8B,2BAA2B7B,GAAgB8B,UAAYpB,GAAsBqB,SAASC,SAI1HC,EAA8BP,GAAaO,4BAMjD,OALAnB,EAAmBmB,GAKXP,GAAaQ,QAEjB,KAAKC,EACG9B,GAAmB+B,EAAqBvC,EAAasB,QAASlB,EAAKyB,GAAaW,cAEpFC,WAAW,KACPzC,EAAasB,SAAU,GACxB,KACH,MAKJ,KAAKoB,EAA4B,CAC7B,MAAMC,EAAaC,EAA+CR,EAA6BjB,EAAsB,SAE/G0B,EAAiBF,IAAa,GAEpC,GAAIE,EAAgB,CAEhB,MAMMC,EANmBC,EAAsBF,EAAeG,WAMrBH,EAAeI,aAAe,KAEvE3C,EAAyBwC,
|
|
1
|
+
{"version":3,"file":"useSRPanelForCardInputErrors.js","sources":["../../../../../../src/components/Card/components/CardInput/useSRPanelForCardInputErrors.ts"],"sourcesContent":["import { useEffect, useState } from 'preact/hooks';\nimport useSRPanelContext from '../../../../core/Errors/useSRPanelContext';\nimport { SetSRMessagesReturnFn } from '../../../../core/Errors/SRPanelProvider';\nimport { handlePartialAddressMode, lookupBlurBasedErrors, mapFieldKey } from './utils';\nimport { usePrevious } from '../../../../utils/hookUtils';\nimport { SetSRMessagesReturnObject, SortedErrorObject } from '../../../../core/Errors/types';\nimport { ERROR_ACTION_BLUR_SCENARIO, ERROR_ACTION_FOCUS_FIELD } from '../../../../core/Errors/constants';\nimport { setFocusOnFirstField } from './handlers';\nimport { getArrayDifferences } from '../../../../utils/arrayUtils';\n\nconst useSRPanelForCardInputErrors = ({ errors, props, isValidating, retrieveLayout, specifications, billingAddress, sfp }) => {\n // Extract fns from context\n const { setSRMessagesFromObjects, setSRMessagesFromStrings, clearSRPanel, shouldMoveFocusSR } = useSRPanelContext();\n\n // Generate a setSRMessages function - implemented as a partial, since the initial set of arguments don't change.\n const setSRMessages: SetSRMessagesReturnFn = setSRMessagesFromObjects?.({\n fieldTypeMappingFn: mapFieldKey\n });\n\n const partialAddressSchema = handlePartialAddressMode(props.billingAddressMode);\n\n const [sortedErrorList, setSortedErrorList] = useState<SortedErrorObject[]>(null);\n\n // Get the previous list of errors\n const previousSortedErrors = usePrevious(sortedErrorList);\n\n const sfStateErrorsObj = sfp.current?.mapErrorsToValidationRuleResult();\n const mergedErrors = { ...errors, ...sfStateErrorsObj };\n\n useEffect(() => {\n try {\n // Extract and then flatten billingAddress errors into a new object with *all* the field errors at top level\n const { billingAddress: extractedAddressErrors, ...errorsWithoutAddress } = mergedErrors;\n\n const errorsForPanel = { ...errorsWithoutAddress, ...extractedAddressErrors };\n\n // Pass dynamic props (errors, layout etc) to SRPanel via partial\n const srPanelResp: SetSRMessagesReturnObject = setSRMessages?.({\n errors: errorsForPanel,\n isValidating: isValidating.current,\n layout: retrieveLayout(),\n // If we don't have country specific address labels, we might have a label related to a partialAddressSchema (i.e. zipCode)\n countrySpecificLabels: specifications.getAddressLabelsForCountry(billingAddress?.country) ?? partialAddressSchema?.default?.labels\n });\n\n // Store the array of sorted error objects separately so that we can use it to make comparisons between the old and new arrays\n const currentErrorsSortedByLayout = srPanelResp?.currentErrorsSortedByLayout;\n setSortedErrorList(currentErrorsSortedByLayout);\n\n /**\n * Need extra actions after setting SRPanel messages in order to focus field (if required) and because we have some errors that are fired onBlur\n */\n switch (srPanelResp?.action) {\n // A call to focus the first field in error will always follow the call to validate the whole form\n case ERROR_ACTION_FOCUS_FIELD:\n if (shouldMoveFocusSR) setFocusOnFirstField(isValidating.current, sfp, srPanelResp?.fieldToFocus);\n // Remove 'showValidation' mode - allowing time for collation of all the fields in error whilst it is 'showValidation' mode (some errors come in a second render pass)\n setTimeout(() => {\n isValidating.current = false;\n }, 300);\n break;\n\n /**\n * Relates to errors triggered by a field blurring (some pm forms have this, some don't) - check if there is an error to either set or to clear\n */\n case ERROR_ACTION_BLUR_SCENARIO: {\n const difference = getArrayDifferences<SortedErrorObject, string>(currentErrorsSortedByLayout, previousSortedErrors, 'field');\n\n const latestErrorMsg = difference?.[0];\n\n if (latestErrorMsg) {\n // Use the error code to look up whether error is actually a blur based one (most are but some SF ones aren't)\n const isBlurBasedError = lookupBlurBasedErrors(latestErrorMsg.errorCode);\n\n /**\n * ONLY ADD BLUR BASED ERRORS TO THE ERROR PANEL - doing this step prevents the non-blur based errors from being read out twice\n * (once from the aria-live, error panel & once from the aria-describedby element)\n */\n const latestSRError = isBlurBasedError ? latestErrorMsg.errorMessage : null;\n // console.log('### CardInput2::componentDidUpdate:: #2 (not validating) single error:: latestSRError', latestSRError);\n setSRMessagesFromStrings(latestSRError);\n } else {\n // called when previousSortedErrors.length >= currentErrorsSortedByLayout.length\n // console.log('### CardInput2::componentDidUpdate:: #3(not validating) clearing errors:: NO latestErrorMsg');\n clearSRPanel();\n }\n break;\n }\n default:\n break;\n }\n } catch (_) {\n // We don't handle the error related to the sr panel, let it fail silently.\n }\n }, [errors]);\n\n return { sortedErrorList, previousSortedErrors, clearSRPanel };\n};\n\nexport default useSRPanelForCardInputErrors;\n"],"names":["useSRPanelForCardInputErrors","errors","props","isValidating","retrieveLayout","specifications","billingAddress","sfp","setSRMessagesFromObjects","setSRMessagesFromStrings","clearSRPanel","shouldMoveFocusSR","useSRPanelContext","setSRMessages","fieldTypeMappingFn","mapFieldKey","partialAddressSchema","handlePartialAddressMode","billingAddressMode","sortedErrorList","setSortedErrorList","useState","previousSortedErrors","usePrevious","sfStateErrorsObj","current","mapErrorsToValidationRuleResult","mergedErrors","useEffect","extractedAddressErrors","errorsWithoutAddress","errorsForPanel","srPanelResp","layout","countrySpecificLabels","getAddressLabelsForCountry","country","default","labels","currentErrorsSortedByLayout","action","ERROR_ACTION_FOCUS_FIELD","setFocusOnFirstField","fieldToFocus","setTimeout","ERROR_ACTION_BLUR_SCENARIO","difference","getArrayDifferences","latestErrorMsg","latestSRError","lookupBlurBasedErrors","errorCode","errorMessage","_"],"mappings":"giBAUA,MAAMA,EAA+B,EAAGC,SAAQC,QAAOC,eAAcC,iBAAgBC,iBAAgBC,iBAAgBC,UAEjH,MAAMC,yBAAEA,EAAwBC,yBAAEA,EAAwBC,aAAEA,EAAYC,kBAAEA,GAAsBC,IAG1FC,EAAuCL,IAA2B,CACpEM,mBAAoBC,IAGlBC,EAAuBC,EAAyBf,EAAMgB,qBAErDC,EAAiBC,GAAsBC,EAA8B,MAGtEC,EAAuBC,EAAYJ,GAEnCK,EAAmBjB,EAAIkB,SAASC,kCAChCC,EAAe,IAAK1B,KAAWuB,GAqErC,OAnEAI,EAAU,KACN,IAEI,MAAQtB,eAAgBuB,KAA2BC,GAAyBH,EAEtEI,EAAiB,IAAKD,KAAyBD,GAG/CG,EAAyCnB,IAAgB,CAC3DZ,OAAQ8B,EACR5B,aAAcA,EAAasB,QAC3BQ,OAAQ7B,IAER8B,sBAAuB7B,EAAe8B,2BAA2B7B,GAAgB8B,UAAYpB,GAAsBqB,SAASC,SAI1HC,EAA8BP,GAAaO,4BAMjD,OALAnB,EAAmBmB,GAKXP,GAAaQ,QAEjB,KAAKC,EACG9B,GAAmB+B,EAAqBvC,EAAasB,QAASlB,EAAKyB,GAAaW,cAEpFC,WAAW,KACPzC,EAAasB,SAAU,GACxB,KACH,MAKJ,KAAKoB,EAA4B,CAC7B,MAAMC,EAAaC,EAA+CR,EAA6BjB,EAAsB,SAE/G0B,EAAiBF,IAAa,GAEpC,GAAIE,EAAgB,CAEhB,MAMMC,EANmBC,EAAsBF,EAAeG,WAMrBH,EAAeI,aAAe,KAEvE3C,EAAyBwC,EAC7B,MAGIvC,IAEJ,KACJ,EAIR,CAAE,MAAO2C,GAET,GACD,CAACpD,IAEG,CAAEkB,kBAAiBG,uBAAsBZ"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{AddressModeOptions as e}from"./types.js";import{CREDIT_CARD_NAME_TOP as o,CREDIT_CARD_NAME_BOTTOM as n,KCP_CARD_NAME_TOP as s,KCP_CARD_NAME_BOTTOM as i,SSN_CARD_NAME_TOP as a,SSN_CARD_NAME_BOTTOM as r,CREDIT_CARD as t,KCP_CARD as l,SSN_CARD as d}from"./layouts.js";import{PARTIAL_ADDRESS_SCHEMA as u}from"../../../internal/Address/constants.js";import{DEFAULT_CARD_GROUP_TYPES as c,BRAND_READABLE_NAME_MAP as m}from"../../../internal/SecuredFields/lib/constants.js";import p from"../../../../core/Context/useImage.js";import{SF_ErrorCodes as h}from"../../../../core/Errors/constants.js";import{DEFAULT_CHALLENGE_WINDOW_SIZE as g}from"../../../ThreeDS2/constants.js";import C from"./defaultProps.js";import{isConfigurationValid as y}from"../Fastlane/utils/validate-configuration.js";import{notFalsy as b}from"../../../../utils/commonUtils.js";const f=(e,o)=>o({type:"card"===e?"nocard":e||"nocard",extension:"svg"})(e),S=e=>"revolving"===e?.plan||e?.value>1,O=({props:e,showKCP:u,showBrazilianSSN:c,countrySpecificSchemas:m=null,billingAddressRequiredFields:p=null})=>{let h=t;const g=e.hasHolderName&&e.holderNameRequired;if(g&&(h=e.positionHolderNameOnTop?o:n),u&&(h=l,g&&(h=e.positionHolderNameOnTop?s:i)),c&&(h=d,g&&(h=e.positionHolderNameOnTop?a:r)),m){const s=m.flat(2).filter(e=>"number"!=typeof e);let i=s;p&&(i=s.filter(e=>p.includes(e))),h=t.concat(i),g&&(h=e.positionHolderNameOnTop?o.concat(i):n.concat(i))}return h},A=(e,o,n)=>{switch(e){case"socialSecurityNumber":return o.get(`boleto.${e}`);case"street":case"houseNumberOrName":case"postalCode":case"stateOrProvince":case"city":case"country":return n?.[e]?o.get(n?.[e]):o.get(e);default:return null}},R=e=>({amount:e.amount,billingAddressRequired:e.billingAddressRequired,billingAddressRequiredFields:e.billingAddressRequiredFields,billingAddressAllowedCountries:e.billingAddressAllowedCountries,brandsConfiguration:e.brandsConfiguration,showStoreDetailsCheckbox:e.showStoreDetailsCheckbox,hasCVC:e.hasCVC,hasHolderName:e.hasHolderName,holderNameRequired:e.holderNameRequired,installmentOptions:e.installmentOptions,placeholders:e.placeholders,positionHolderNameOnTop:e.positionHolderNameOnTop,showBrandIcon:e.showBrandIcon,showContextualElement:e.showContextualElement,lastFour:e.lastFour,expiryMonth:e.expiryMonth,expiryYear:e.expiryYear,disclaimerMessage:e.disclaimerMessage}),F=e=>({autoFocus:e.autoFocus,brands:e.brands,brandsConfiguration:e.brandsConfiguration,clientKey:e.clientKey,countryCode:e.countryCode,forceCompat:e.forceCompat,i18n:e.i18n,implementationType:e.implementationType,keypadFix:e.keypadFix,legacyInputMode:e.legacyInputMode,loadingContext:e.loadingContext,maskSecurityCode:e.maskSecurityCode,exposeExpiryDate:e.exposeExpiryDate,minimumExpiryDate:e.minimumExpiryDate,onAdditionalSFConfig:e.onAdditionalSFConfig,onAdditionalSFRemoved:e.onAdditionalSFRemoved,onAllValid:e.onAllValid,onAutoComplete:e.onAutoComplete,onBinValue:e.onBinValue,onConfigSuccess:e.onConfigSuccess,handleKeyPress:e.handleKeyPress,onError:e.onError,onFieldValid:e.onFieldValid,onLoad:e.onLoad,placeholders:e.placeholders,resources:e.resources,showContextualElement:e.showContextualElement,showWarnings:e.showWarnings,trimTrailingSeparator:e.trimTrailingSeparator}),x=o=>o==e.partial?u:null;function N(e){return![h.ERROR_MSG_UNSUPPORTED_CARD_ENTERED,h.ERROR_MSG_CARD_TOO_OLD,h.ERROR_MSG_CARD_TOO_FAR_IN_FUTURE,h.ERROR_MSG_CARD_EXPIRES_TOO_SOON].includes(e)}function E(e){return m[e]??e}const w=e=>{const{autoFocus:o,billingAddressAllowedCountries:n,billingAddressMode:s,billingAddressRequired:i,billingAddressRequiredFields:a,brands:r=c,brandsConfiguration:t,challengeWindowSize:l=g,configuration:d,countryCode:u,data:m,disclaimerMessage:p,disableIOSArrowKeys:h,doBinLookup:f,enableStoreDetails:S,exposeExpiryDate:O,fastlaneConfiguration:A,forceCompat:R,hasHolderName:F,hideCVC:x,holderNameRequired:N,installmentOptions:E,keypadFix:w,legacyInputMode:B,maskSecurityCode:D,minimumExpiryDate:T,name:k,placeholders:M,positionHolderNameOnTop:V,showBrandIcon:_,showInstallmentAmounts:P,showPayButton:I=!1,styles:q,onAllValid:H,onBinLookup:L,onBinValue:j,onBlur:v,onBrand:K,onConfigSuccess:U,onEnterKeyPressed:G,onFieldValid:W,onFocus:z,onLoad:J}=e,Y=JSON.stringify(C.data),X=e.modules?.srPanel?.enabled,$=e.modules?.srPanel?.moveFocus,Q=e.modules?.risk?.enabled,Z=y(A),ee=e.onAddressLookup?"lookup":s;let oe="none";!0===d?.koreanAuthenticationRequired&&(oe="kr"===u?.toLowerCase()?"atStart":"auto");return{autoFocus:o,...n?.length>0&&{billingAddressAllowedCountries:n.toString().substring(0,128)},billingAddressMode:ee,billingAddressRequired:i,billingAddressRequiredFields:a?.toString()?.substring(0,128),brands:r?.toString()?.substring(0,128),challengeWindowSize:l,disableIOSArrowKeys:h,doBinLookup:f,enableStoreDetails:S,exposeExpiryDate:O,forceCompat:R,hasBrandsConfiguration:b(t),hasData:m&&JSON.stringify(e.data)!==Y,hasDisclaimerMessage:!!p,hasHolderName:F,hasInstallmentOptions:b(E),hasPlaceholders:b(M),hasStylesConfigured:b(q),hideCVC:x,holderNameRequired:N,keypadFix:w,legacyInputMode:B,maskSecurityCode:D,minimumExpiryDate:!!T,name:k,positionHolderNameOnTop:V,riskEnabled:Q,showBrandIcon:_,showInstallmentAmounts:!!P,showKCPType:oe,showPayButton:I,socialSecurityNumberMode:d?.socialSecurityNumberMode,srPanelEnabled:X,srPanelMoveFocus:$,hasOnAllValid:H!==C.onAllValid,hasOnBinValue:j!==C.onBinValue,hasOnBlur:v!==C.onBlur,hasOnBrand:K!==C.onBrand,hasOnConfigSuccess:U!==C.onConfigSuccess,hasOnFieldValid:W!==C.onFieldValid,hasOnFocus:z!==C.onFocus,hasOnLoad:J!==C.onLoad,hasOnBinLookup:!!L,hasOnEnterKeyPressed:!!G,...Z&&{hasFastlaneConfigured:!0,isFastlaneConsentDefaultOn:A.defaultToggleState}}},B=(e,o)=>e.map(e=>{const n=e.id,s=p(),i="card"===n?"nocard":n,a=o[n]?.icon??f(i,s);return{id:e.id,name:e.brandObject.localeBrand||e.brandObject.brand,imageURL:a,altName:E(n)}});export{R as extractPropsForCardFields,F as extractPropsForSFP,w as getCardConfigData,f as getCardImageUrl,E as getFullBrandName,O as getLayout,x as handlePartialAddressMode,S as hasValidInstallmentsObject,N as lookupBlurBasedErrors,B as mapDualBrandButtons,A as mapFieldKey};
|
|
1
|
+
import{AddressModeOptions as e}from"./types.js";import{CREDIT_CARD_NAME_TOP as o,CREDIT_CARD_NAME_BOTTOM as n,KCP_CARD_NAME_TOP as s,KCP_CARD_NAME_BOTTOM as i,SSN_CARD_NAME_TOP as a,SSN_CARD_NAME_BOTTOM as r,CREDIT_CARD as t,KCP_CARD as l,SSN_CARD as d}from"./layouts.js";import{PARTIAL_ADDRESS_SCHEMA as u}from"../../../internal/Address/constants.js";import{DEFAULT_CARD_GROUP_TYPES as c,BRAND_READABLE_NAME_MAP as m}from"../../../internal/SecuredFields/lib/constants.js";import p from"../../../../core/Context/useImage.js";import{SF_ErrorCodes as h}from"../../../../core/Errors/constants.js";import{DEFAULT_CHALLENGE_WINDOW_SIZE as g}from"../../../ThreeDS2/constants.js";import C from"./defaultProps.js";import{isConfigurationValid as y}from"../Fastlane/utils/validate-configuration.js";import{notFalsy as b}from"../../../../utils/commonUtils.js";const f=(e,o)=>o({type:"card"===e?"nocard":e||"nocard",extension:"svg"})(e),S=e=>"revolving"===e?.plan||e?.value>1,O=({props:e,showKCP:u,showBrazilianSSN:c,countrySpecificSchemas:m=null,billingAddressRequiredFields:p=null})=>{let h=t;const g=e.hasHolderName&&e.holderNameRequired;if(g&&(h=e.positionHolderNameOnTop?o:n),u&&(h=l,g&&(h=e.positionHolderNameOnTop?s:i)),c&&(h=d,g&&(h=e.positionHolderNameOnTop?a:r)),m){const s=m.flat(2).filter(e=>"number"!=typeof e);let i=s;p&&(i=s.filter(e=>p.includes(e))),h=t.concat(i),g&&(h=e.positionHolderNameOnTop?o.concat(i):n.concat(i))}return h},A=(e,o,n)=>{switch(e){case"socialSecurityNumber":return o.get(`boleto.${e}`);case"street":case"houseNumberOrName":case"postalCode":case"stateOrProvince":case"city":case"country":return n?.[e]?o.get(n?.[e]):o.get(e);default:return null}},R=e=>({amount:e.amount,billingAddressRequired:e.billingAddressRequired,billingAddressRequiredFields:e.billingAddressRequiredFields,billingAddressAllowedCountries:e.billingAddressAllowedCountries,brandsConfiguration:e.brandsConfiguration,showStoreDetailsCheckbox:e.showStoreDetailsCheckbox,hasCVC:e.hasCVC,hasHolderName:e.hasHolderName,holderNameRequired:e.holderNameRequired,installmentOptions:e.installmentOptions,placeholders:e.placeholders,positionHolderNameOnTop:e.positionHolderNameOnTop,showBrandIcon:e.showBrandIcon,showContextualElement:e.showContextualElement,lastFour:e.lastFour,expiryMonth:e.expiryMonth,expiryYear:e.expiryYear,disclaimerMessage:e.disclaimerMessage}),F=e=>({autoFocus:e.autoFocus,brands:e.brands,brandsConfiguration:e.brandsConfiguration,clientKey:e.clientKey,countryCode:e.countryCode,forceCompat:e.forceCompat,i18n:e.i18n,implementationType:e.implementationType,keypadFix:e.keypadFix,legacyInputMode:e.legacyInputMode,loadingContext:e.loadingContext,maskSecurityCode:e.maskSecurityCode,exposeExpiryDate:e.exposeExpiryDate,minimumExpiryDate:e.minimumExpiryDate,onAdditionalSFConfig:e.onAdditionalSFConfig,onAdditionalSFRemoved:e.onAdditionalSFRemoved,onAllValid:e.onAllValid,onAutoComplete:e.onAutoComplete,onBinValue:e.onBinValue,onConfigSuccess:e.onConfigSuccess,handleKeyPress:e.handleKeyPress,onError:e.onError,onFieldValid:e.onFieldValid,onLoad:e.onLoad,placeholders:e.placeholders,resources:e.resources,showContextualElement:e.showContextualElement,showWarnings:e.showWarnings,trimTrailingSeparator:e.trimTrailingSeparator}),x=o=>o==e.partial?u:null;function N(e){return![h.ERROR_MSG_UNSUPPORTED_CARD_ENTERED,h.ERROR_MSG_CARD_TOO_OLD,h.ERROR_MSG_CARD_TOO_FAR_IN_FUTURE,h.ERROR_MSG_CARD_EXPIRES_TOO_SOON].includes(e)}function E(e){return m[e]??e}const w=e=>{const{autoFocus:o,billingAddressAllowedCountries:n,billingAddressMode:s,billingAddressRequired:i,billingAddressRequiredFields:a,brands:r=c,brandsConfiguration:t,challengeWindowSize:l=g,configuration:d,countryCode:u,data:m,disclaimerMessage:p,disableIOSArrowKeys:h,doBinLookup:f,enableStoreDetails:S,exposeExpiryDate:O,fastlaneConfiguration:A,forceCompat:R,hasHolderName:F,hideCVC:x,holderNameRequired:N,installmentOptions:E,keypadFix:w,legacyInputMode:B,maskSecurityCode:D,minimumExpiryDate:T,name:k,placeholders:M,positionHolderNameOnTop:V,showBrandIcon:_,showInstallmentAmounts:P,showPayButton:I=!1,styles:q,onAllValid:H,onBinLookup:L,onBinValue:j,onBlur:v,onBrand:K,onConfigSuccess:U,onEnterKeyPressed:G,onFieldValid:W,onFocus:z,onLoad:J}=e,Y=JSON.stringify(C.data),X=e.modules?.srPanel?.enabled,$=e.modules?.srPanel?.moveFocus,Q=e.modules?.risk?.enabled,Z=y(A),ee=e.onAddressLookup?"lookup":s;let oe="none";!0===d?.koreanAuthenticationRequired&&(oe="kr"===u?.toLowerCase()?"atStart":"auto");return{autoFocus:o,...n?.length>0&&{billingAddressAllowedCountries:n.toString().substring(0,128)},billingAddressMode:ee,billingAddressRequired:i,billingAddressRequiredFields:a?.toString()?.substring(0,128),brands:r?.toString()?.substring(0,128),challengeWindowSize:l,disableIOSArrowKeys:h,doBinLookup:f,enableStoreDetails:S,exposeExpiryDate:O,forceCompat:R,hasBrandsConfiguration:b(t),hasData:m&&JSON.stringify(e.data)!==Y,hasDisclaimerMessage:!!p,hasHolderName:F,hasInstallmentOptions:b(E),hasPlaceholders:b(M),hasStylesConfigured:b(q),hideCVC:x,holderNameRequired:N,keypadFix:w,legacyInputMode:B,maskSecurityCode:D,minimumExpiryDate:!!T,name:k,positionHolderNameOnTop:V,riskEnabled:Q,showBrandIcon:_,showInstallmentAmounts:!!P,showKCPType:oe,showPayButton:I,socialSecurityNumberMode:d?.socialSecurityNumberMode,srPanelEnabled:X,srPanelMoveFocus:$,hasOnAllValid:H!==C.onAllValid,hasOnBinValue:j!==C.onBinValue,hasOnBlur:v!==C.onBlur,hasOnBrand:K!==C.onBrand,hasOnConfigSuccess:U!==C.onConfigSuccess,hasOnFieldValid:W!==C.onFieldValid,hasOnFocus:z!==C.onFocus,hasOnLoad:J!==C.onLoad,hasOnBinLookup:!!L,hasOnEnterKeyPressed:!!G,...Z&&{hasFastlaneConfigured:!0,isFastlaneConsentDefaultOn:A.defaultToggleState}}},B=(e,o)=>e.map(e=>{const n=e.id,s=p(),i="card"===n?"nocard":n,a=o[n]?.icon??f(i,s);return{id:e.id,name:e.brandObject.localeBrand||e.brandObject.brand,imageURL:a,altName:E(n)}}),D=(e,o,n)=>!!o.filter(o=>e.includes(o[n])).length;export{R as extractPropsForCardFields,F as extractPropsForSFP,w as getCardConfigData,f as getCardImageUrl,E as getFullBrandName,O as getLayout,x as handlePartialAddressMode,S as hasValidInstallmentsObject,N as lookupBlurBasedErrors,B as mapDualBrandButtons,A as mapFieldKey,D as mustHandleDualBrandingAccordingToEURegulations};
|
|
2
2
|
//# sourceMappingURL=utils.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","sources":["../../../../../../src/components/Card/components/CardInput/utils.ts"],"sourcesContent":["import Language from '../../../../language/Language';\nimport { AddressModeOptions, CardInputProps, LayoutObj } from './types';\nimport {\n CREDIT_CARD,\n CREDIT_CARD_NAME_BOTTOM,\n CREDIT_CARD_NAME_TOP,\n KCP_CARD,\n KCP_CARD_NAME_BOTTOM,\n KCP_CARD_NAME_TOP,\n SSN_CARD,\n SSN_CARD_NAME_BOTTOM,\n SSN_CARD_NAME_TOP\n} from './layouts';\nimport { AddressSpecifications, StringObject } from '../../../internal/Address/types';\nimport { PARTIAL_ADDRESS_SCHEMA } from '../../../internal/Address/constants';\nimport { InstallmentsObj } from './components/Installments/Installments';\nimport { SFPProps } from '../../../internal/SecuredFields/SFP/types';\nimport { BRAND_READABLE_NAME_MAP, DEFAULT_CARD_GROUP_TYPES } from '../../../internal/SecuredFields/lib/constants';\nimport useImage, { UseImageHookType } from '../../../../core/Context/useImage';\nimport { SF_ErrorCodes } from '../../../../core/Errors/constants';\nimport { CardBrandsConfiguration, CardConfiguration, DualBrandSelectElement } from '../../types';\nimport { CardConfigData } from '../../../../core/Analytics/types';\nimport { DEFAULT_CHALLENGE_WINDOW_SIZE } from '../../../ThreeDS2/constants';\nimport CardInputDefaultProps from './defaultProps';\nimport { isConfigurationValid as isFastlaneComponentConfigValid } from '../Fastlane/utils/validate-configuration';\nimport { notFalsy } from '../../../../utils/commonUtils';\n\nexport const getCardImageUrl = (brand: string, getImage: UseImageHookType): string => {\n const imageOptions = {\n type: brand === 'card' ? 'nocard' : brand || 'nocard',\n extension: 'svg'\n };\n\n return getImage(imageOptions)(brand);\n};\n\n/**\n * Verifies that installment object is valid to send to the Backend.\n * Valid means that it has 'revolving' plan set, or the number of installments is bigger than one\n */\nexport const hasValidInstallmentsObject = (installments?: InstallmentsObj) => {\n return installments?.plan === 'revolving' || installments?.value > 1;\n};\n\nexport const getLayout = ({\n props,\n showKCP,\n showBrazilianSSN,\n countrySpecificSchemas = null,\n billingAddressRequiredFields = null\n}: LayoutObj): string[] => {\n let layout = CREDIT_CARD;\n const hasRequiredHolderName = props.hasHolderName && props.holderNameRequired;\n\n if (hasRequiredHolderName) {\n layout = props.positionHolderNameOnTop ? CREDIT_CARD_NAME_TOP : CREDIT_CARD_NAME_BOTTOM;\n }\n\n if (showKCP) {\n layout = KCP_CARD;\n if (hasRequiredHolderName) {\n layout = props.positionHolderNameOnTop ? KCP_CARD_NAME_TOP : KCP_CARD_NAME_BOTTOM;\n }\n }\n\n if (showBrazilianSSN) {\n layout = SSN_CARD;\n if (hasRequiredHolderName) {\n layout = props.positionHolderNameOnTop ? SSN_CARD_NAME_TOP : SSN_CARD_NAME_BOTTOM;\n }\n }\n\n // w. Billing address\n if (countrySpecificSchemas) {\n // Flatten array and remove any numbers that describe how fields should be aligned\n const countrySpecificSchemasFlat: string[] = countrySpecificSchemas['flat'](2).filter(item => typeof item !== 'number') as string[];\n\n let countryBasedAddressLayout = countrySpecificSchemasFlat;\n\n if (billingAddressRequiredFields) {\n // Get intersection of the 2 arrays\n countryBasedAddressLayout = countrySpecificSchemasFlat.filter(x => billingAddressRequiredFields.includes(x));\n }\n\n layout = CREDIT_CARD.concat(countryBasedAddressLayout);\n if (hasRequiredHolderName) {\n layout = props.positionHolderNameOnTop\n ? CREDIT_CARD_NAME_TOP.concat(countryBasedAddressLayout)\n : CREDIT_CARD_NAME_BOTTOM.concat(countryBasedAddressLayout);\n }\n // TODO we are not yet creating a layout for AVS + SSN field (w. or w/o holderName) - is AVS + SSN a real world scenario?\n }\n return layout;\n};\n\n/**\n * Lookup service to map local (CardInput) field refs to a key, possibly region specific, by which to retrieve the translation\n */\nexport const mapFieldKey = (key: string, i18n: Language, countrySpecificLabels: StringObject): string => {\n // console.log('### utils::mapFieldKey:: key', key);\n switch (key) {\n case 'socialSecurityNumber':\n return i18n.get(`boleto.${key}`);\n // Address related - if we have a country specific key for the field - use that to get the translation\n case 'street':\n case 'houseNumberOrName':\n case 'postalCode':\n case 'stateOrProvince':\n case 'city':\n case 'country':\n return countrySpecificLabels?.[key] ? i18n.get(countrySpecificLabels?.[key]) : i18n.get(key);\n // We know that the translated error messages do contain a reference to the field they refer to, so we won't need to map them (currently applies mostly to SecuredFields related errors)\n default:\n return null;\n }\n};\n\nexport const extractPropsForCardFields = (props: CardInputProps) => {\n return {\n // Extract props for CardFieldsWrapper & StoredCardFieldsWrapper(just needs amount, hasCVC, installmentOptions)\n amount: props.amount,\n billingAddressRequired: props.billingAddressRequired,\n billingAddressRequiredFields: props.billingAddressRequiredFields,\n billingAddressAllowedCountries: props.billingAddressAllowedCountries,\n brandsConfiguration: props.brandsConfiguration,\n showStoreDetailsCheckbox: props.showStoreDetailsCheckbox,\n hasCVC: props.hasCVC,\n hasHolderName: props.hasHolderName,\n holderNameRequired: props.holderNameRequired,\n installmentOptions: props.installmentOptions,\n placeholders: props.placeholders,\n positionHolderNameOnTop: props.positionHolderNameOnTop,\n // Extract props for CardFields > CardNumber\n showBrandIcon: props.showBrandIcon,\n showContextualElement: props.showContextualElement,\n // Extract props for StoredCardFields\n lastFour: props.lastFour,\n expiryMonth: props.expiryMonth,\n expiryYear: props.expiryYear,\n disclaimerMessage: props.disclaimerMessage\n };\n};\n\nexport const extractPropsForSFP = (props: CardInputProps) => {\n return {\n autoFocus: props.autoFocus,\n brands: props.brands,\n brandsConfiguration: props.brandsConfiguration,\n clientKey: props.clientKey,\n countryCode: props.countryCode,\n forceCompat: props.forceCompat,\n i18n: props.i18n,\n implementationType: props.implementationType,\n keypadFix: props.keypadFix,\n legacyInputMode: props.legacyInputMode,\n loadingContext: props.loadingContext,\n maskSecurityCode: props.maskSecurityCode,\n exposeExpiryDate: props.exposeExpiryDate,\n minimumExpiryDate: props.minimumExpiryDate,\n onAdditionalSFConfig: props.onAdditionalSFConfig,\n onAdditionalSFRemoved: props.onAdditionalSFRemoved,\n onAllValid: props.onAllValid,\n onAutoComplete: props.onAutoComplete,\n onBinValue: props.onBinValue,\n onConfigSuccess: props.onConfigSuccess,\n handleKeyPress: props.handleKeyPress,\n onError: props.onError,\n onFieldValid: props.onFieldValid,\n onLoad: props.onLoad,\n placeholders: props.placeholders,\n resources: props.resources,\n showContextualElement: props.showContextualElement,\n showWarnings: props.showWarnings,\n trimTrailingSeparator: props.trimTrailingSeparator\n } as SFPProps; // Can't set as return type on fn or it will complain about missing, mandatory, props\n};\n\nexport const handlePartialAddressMode = (addressMode: AddressModeOptions): AddressSpecifications | null => {\n return addressMode == AddressModeOptions.partial ? PARTIAL_ADDRESS_SCHEMA : null;\n};\n\n// Almost all errors are blur based, but some SF ones are not i.e. when an unsupported card is entered or the expiry date is out of range\nexport function lookupBlurBasedErrors(errorCode) {\n // If it's NOT one of these, then it's a blur based error\n return ![\n SF_ErrorCodes.ERROR_MSG_UNSUPPORTED_CARD_ENTERED,\n SF_ErrorCodes.ERROR_MSG_CARD_TOO_OLD,\n SF_ErrorCodes.ERROR_MSG_CARD_TOO_FAR_IN_FUTURE,\n SF_ErrorCodes.ERROR_MSG_CARD_EXPIRES_TOO_SOON\n ].includes(errorCode);\n}\n\nexport function getFullBrandName(brand) {\n return BRAND_READABLE_NAME_MAP[brand] ?? brand;\n}\n\nexport const getCardConfigData = (cardProps: CardConfiguration): CardConfigData => {\n const MAX_LENGTH = 128;\n\n // Extract props from cardProps - mostly setting a default value, if prop not found\n const {\n autoFocus,\n billingAddressAllowedCountries,\n billingAddressMode,\n billingAddressRequired,\n billingAddressRequiredFields,\n brands = DEFAULT_CARD_GROUP_TYPES,\n brandsConfiguration,\n challengeWindowSize = DEFAULT_CHALLENGE_WINDOW_SIZE,\n configuration,\n countryCode,\n data,\n disclaimerMessage,\n disableIOSArrowKeys,\n doBinLookup,\n enableStoreDetails,\n exposeExpiryDate,\n fastlaneConfiguration,\n forceCompat,\n hasHolderName,\n hideCVC,\n holderNameRequired,\n installmentOptions,\n keypadFix,\n legacyInputMode,\n maskSecurityCode,\n minimumExpiryDate,\n name, // = 'none',\n placeholders,\n positionHolderNameOnTop,\n showBrandIcon,\n showInstallmentAmounts,\n showPayButton = false, // hard coded default\n styles,\n onAllValid,\n onBinLookup,\n onBinValue,\n onBlur,\n onBrand,\n onConfigSuccess,\n onEnterKeyPressed,\n onFieldValid,\n onFocus,\n onLoad\n } = cardProps;\n\n const dataString = JSON.stringify(CardInputDefaultProps.data);\n\n const srPanelEnabled = cardProps.modules?.srPanel?.enabled;\n const srPanelMoveFocus = cardProps.modules?.srPanel?.moveFocus;\n\n const riskEnabled = cardProps.modules?.risk?.enabled;\n\n const isFastlaneConfigValid = isFastlaneComponentConfigValid(fastlaneConfiguration);\n\n const billingAddressModeValue = cardProps.onAddressLookup ? 'lookup' : billingAddressMode;\n\n let showKCPType: 'none' | 'auto' | 'atStart' = 'none';\n if (configuration?.koreanAuthenticationRequired === true) {\n showKCPType = countryCode?.toLowerCase() === 'kr' ? 'atStart' : 'auto';\n }\n\n const configData: CardConfigData = {\n autoFocus,\n ...(billingAddressAllowedCountries?.length > 0 && {\n billingAddressAllowedCountries: billingAddressAllowedCountries.toString().substring(0, MAX_LENGTH)\n }),\n billingAddressMode: billingAddressModeValue,\n billingAddressRequired,\n billingAddressRequiredFields: billingAddressRequiredFields?.toString()?.substring(0, MAX_LENGTH),\n // Probably just for development - in real life we wouldn't expect the number of supported brands to push the endpoint limit on 128 chars\n brands: brands?.toString()?.substring(0, MAX_LENGTH),\n challengeWindowSize,\n disableIOSArrowKeys,\n doBinLookup,\n enableStoreDetails,\n exposeExpiryDate,\n forceCompat,\n hasBrandsConfiguration: notFalsy(brandsConfiguration),\n hasData: data && JSON.stringify(cardProps.data) !== dataString,\n hasDisclaimerMessage: !!disclaimerMessage,\n hasHolderName,\n hasInstallmentOptions: notFalsy(installmentOptions),\n hasPlaceholders: notFalsy(placeholders), // has merchant defined placeholders\n hasStylesConfigured: notFalsy(styles),\n hideCVC,\n holderNameRequired,\n keypadFix,\n legacyInputMode,\n maskSecurityCode,\n minimumExpiryDate: !!minimumExpiryDate, // Potentially, in the future, we can send the actual string value\n name,\n positionHolderNameOnTop,\n riskEnabled,\n showBrandIcon,\n showInstallmentAmounts: !!showInstallmentAmounts,\n showKCPType,\n showPayButton,\n socialSecurityNumberMode: configuration?.socialSecurityNumberMode,\n srPanelEnabled,\n srPanelMoveFocus,\n /** callbacks */\n // We need to detect if the merchant themselves has defined these, not if we've set them as a default\n hasOnAllValid: onAllValid !== CardInputDefaultProps.onAllValid,\n hasOnBinValue: onBinValue !== CardInputDefaultProps.onBinValue,\n hasOnBlur: onBlur !== CardInputDefaultProps.onBlur,\n hasOnBrand: onBrand !== CardInputDefaultProps.onBrand,\n hasOnConfigSuccess: onConfigSuccess !== CardInputDefaultProps.onConfigSuccess,\n hasOnFieldValid: onFieldValid !== CardInputDefaultProps.onFieldValid,\n hasOnFocus: onFocus !== CardInputDefaultProps.onFocus,\n hasOnLoad: onLoad !== CardInputDefaultProps.onLoad,\n // Card level props\n hasOnBinLookup: !!onBinLookup,\n hasOnEnterKeyPressed: !!onEnterKeyPressed,\n /**\n * Fastlane\n */\n ...(isFastlaneConfigValid && {\n hasFastlaneConfigured: true,\n isFastlaneConsentDefaultOn: fastlaneConfiguration.defaultToggleState\n })\n };\n\n return configData;\n};\n\nexport const mapDualBrandButtons = (dualBrandSelectElements: DualBrandSelectElement[], brandsConfiguration: CardBrandsConfiguration): any => {\n return dualBrandSelectElements.map(item => {\n const brand = item.id;\n const getImage = useImage();\n const imageName = brand === 'card' ? 'nocard' : brand;\n const imageURL = brandsConfiguration[brand]?.icon ?? getCardImageUrl(imageName, getImage);\n\n // TODO - check below if we have to still generate altName through the mapping function or whether it just\n // corresponds to item.brandObject.localeBrand\n return {\n id: item.id,\n name: item.brandObject.localeBrand || item.brandObject.brand,\n imageURL,\n altName: getFullBrandName(brand)\n };\n });\n};\n"],"names":["getCardImageUrl","brand","getImage","type","extension","hasValidInstallmentsObject","installments","plan","value","getLayout","props","showKCP","showBrazilianSSN","countrySpecificSchemas","billingAddressRequiredFields","layout","CREDIT_CARD","hasRequiredHolderName","hasHolderName","holderNameRequired","positionHolderNameOnTop","CREDIT_CARD_NAME_TOP","CREDIT_CARD_NAME_BOTTOM","KCP_CARD","KCP_CARD_NAME_TOP","KCP_CARD_NAME_BOTTOM","SSN_CARD","SSN_CARD_NAME_TOP","SSN_CARD_NAME_BOTTOM","countrySpecificSchemasFlat","filter","item","countryBasedAddressLayout","x","includes","concat","mapFieldKey","key","i18n","countrySpecificLabels","get","extractPropsForCardFields","amount","billingAddressRequired","billingAddressAllowedCountries","brandsConfiguration","showStoreDetailsCheckbox","hasCVC","installmentOptions","placeholders","showBrandIcon","showContextualElement","lastFour","expiryMonth","expiryYear","disclaimerMessage","extractPropsForSFP","autoFocus","brands","clientKey","countryCode","forceCompat","implementationType","keypadFix","legacyInputMode","loadingContext","maskSecurityCode","exposeExpiryDate","minimumExpiryDate","onAdditionalSFConfig","onAdditionalSFRemoved","onAllValid","onAutoComplete","onBinValue","onConfigSuccess","handleKeyPress","onError","onFieldValid","onLoad","resources","showWarnings","trimTrailingSeparator","handlePartialAddressMode","addressMode","AddressModeOptions","partial","PARTIAL_ADDRESS_SCHEMA","lookupBlurBasedErrors","errorCode","SF_ErrorCodes","ERROR_MSG_UNSUPPORTED_CARD_ENTERED","ERROR_MSG_CARD_TOO_OLD","ERROR_MSG_CARD_TOO_FAR_IN_FUTURE","ERROR_MSG_CARD_EXPIRES_TOO_SOON","getFullBrandName","BRAND_READABLE_NAME_MAP","getCardConfigData","cardProps","billingAddressMode","DEFAULT_CARD_GROUP_TYPES","challengeWindowSize","DEFAULT_CHALLENGE_WINDOW_SIZE","configuration","data","disableIOSArrowKeys","doBinLookup","enableStoreDetails","fastlaneConfiguration","hideCVC","name","showInstallmentAmounts","showPayButton","styles","onBinLookup","onBlur","onBrand","onEnterKeyPressed","onFocus","dataString","JSON","stringify","CardInputDefaultProps","srPanelEnabled","modules","srPanel","enabled","srPanelMoveFocus","moveFocus","riskEnabled","risk","isFastlaneConfigValid","isFastlaneComponentConfigValid","billingAddressModeValue","onAddressLookup","showKCPType","koreanAuthenticationRequired","toLowerCase","length","toString","substring","hasBrandsConfiguration","notFalsy","hasData","hasDisclaimerMessage","hasInstallmentOptions","hasPlaceholders","hasStylesConfigured","socialSecurityNumberMode","hasOnAllValid","hasOnBinValue","hasOnBlur","hasOnBrand","hasOnConfigSuccess","hasOnFieldValid","hasOnFocus","hasOnLoad","hasOnBinLookup","hasOnEnterKeyPressed","hasFastlaneConfigured","isFastlaneConsentDefaultOn","defaultToggleState","mapDualBrandButtons","dualBrandSelectElements","map","id","useImage","imageName","imageURL","icon","brandObject","localeBrand","altName"],"mappings":"i1BA2BO,MAAMA,EAAkB,CAACC,EAAeC,IAMpCA,EALc,CACjBC,KAAgB,SAAVF,EAAmB,SAAWA,GAAS,SAC7CG,UAAW,OAGRF,CAAuBD,GAOrBI,EAA8BC,GACT,cAAvBA,GAAcC,MAAwBD,GAAcE,MAAQ,EAG1DC,EAAY,EACrBC,QACAC,UACAC,mBACAC,yBAAyB,KACzBC,+BAA+B,SAE/B,IAAIC,EAASC,EACb,MAAMC,EAAwBP,EAAMQ,eAAiBR,EAAMS,mBAqB3D,GAnBIF,IACAF,EAASL,EAAMU,wBAA0BC,EAAuBC,GAGhEX,IACAI,EAASQ,EACLN,IACAF,EAASL,EAAMU,wBAA0BI,EAAoBC,IAIjEb,IACAG,EAASW,EACLT,IACAF,EAASL,EAAMU,wBAA0BO,EAAoBC,IAKjEf,EAAwB,CAExB,MAAMgB,EAAuChB,EAAuB,KAAQ,GAAGiB,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BlD,WACpD8E,cAAe5E,IAAegD,EAAsBhD,WACpD6E,UAAWpC,IAAWO,EAAsBP,OAC5CqC,WAAYpC,IAAYM,EAAsBN,QAC9CqC,mBAAoB9E,IAAoB+C,EAAsB/C,gBAC9D+E,gBAAiB5E,IAAiB4C,EAAsB5C,aACxD6E,WAAYrC,IAAYI,EAAsBJ,QAC9CsC,UAAW7E,IAAW2C,EAAsB3C,OAE5C8E,iBAAkB3C,EAClB4C,uBAAwBzC,KAIpBc,GAAyB,CACzB4B,uBAAuB,EACvBC,2BAA4BpD,EAAsBqD,sBAOjDC,EAAsB,CAACC,EAAmDrH,IAC5EqH,EAAwBC,IAAIpI,IAC/B,MAAM9B,EAAQ8B,EAAKqI,GACblK,EAAWmK,IACXC,EAAsB,SAAVrK,EAAmB,SAAWA,EAC1CsK,EAAW1H,EAAoB5C,IAAQuK,MAAQxK,EAAgBsK,EAAWpK,GAIhF,MAAO,CACHkK,GAAIrI,EAAKqI,GACTvD,KAAM9E,EAAK0I,YAAYC,aAAe3I,EAAK0I,YAAYxK,MACvDsK,WACAI,QAAS7E,EAAiB7F"}
|
|
1
|
+
{"version":3,"file":"utils.js","sources":["../../../../../../src/components/Card/components/CardInput/utils.ts"],"sourcesContent":["import Language from '../../../../language/Language';\nimport { AddressModeOptions, CardInputProps, LayoutObj } from './types';\nimport {\n CREDIT_CARD,\n CREDIT_CARD_NAME_BOTTOM,\n CREDIT_CARD_NAME_TOP,\n KCP_CARD,\n KCP_CARD_NAME_BOTTOM,\n KCP_CARD_NAME_TOP,\n SSN_CARD,\n SSN_CARD_NAME_BOTTOM,\n SSN_CARD_NAME_TOP\n} from './layouts';\nimport { AddressSpecifications, StringObject } from '../../../internal/Address/types';\nimport { PARTIAL_ADDRESS_SCHEMA } from '../../../internal/Address/constants';\nimport { InstallmentsObj } from './components/Installments/Installments';\nimport { SFPProps } from '../../../internal/SecuredFields/SFP/types';\nimport { BRAND_READABLE_NAME_MAP, DEFAULT_CARD_GROUP_TYPES } from '../../../internal/SecuredFields/lib/constants';\nimport useImage, { UseImageHookType } from '../../../../core/Context/useImage';\nimport { SF_ErrorCodes } from '../../../../core/Errors/constants';\nimport { BrandObject, CardBrandsConfiguration, CardConfiguration, DualBrandSelectElement } from '../../types';\nimport { CardConfigData } from '../../../../core/Analytics/types';\nimport { DEFAULT_CHALLENGE_WINDOW_SIZE } from '../../../ThreeDS2/constants';\nimport CardInputDefaultProps from './defaultProps';\nimport { isConfigurationValid as isFastlaneComponentConfigValid } from '../Fastlane/utils/validate-configuration';\nimport { notFalsy } from '../../../../utils/commonUtils';\n\nexport const getCardImageUrl = (brand: string, getImage: UseImageHookType): string => {\n const imageOptions = {\n type: brand === 'card' ? 'nocard' : brand || 'nocard',\n extension: 'svg'\n };\n\n return getImage(imageOptions)(brand);\n};\n\n/**\n * Verifies that installment object is valid to send to the Backend.\n * Valid means that it has 'revolving' plan set, or the number of installments is bigger than one\n */\nexport const hasValidInstallmentsObject = (installments?: InstallmentsObj) => {\n return installments?.plan === 'revolving' || installments?.value > 1;\n};\n\nexport const getLayout = ({\n props,\n showKCP,\n showBrazilianSSN,\n countrySpecificSchemas = null,\n billingAddressRequiredFields = null\n}: LayoutObj): string[] => {\n let layout = CREDIT_CARD;\n const hasRequiredHolderName = props.hasHolderName && props.holderNameRequired;\n\n if (hasRequiredHolderName) {\n layout = props.positionHolderNameOnTop ? CREDIT_CARD_NAME_TOP : CREDIT_CARD_NAME_BOTTOM;\n }\n\n if (showKCP) {\n layout = KCP_CARD;\n if (hasRequiredHolderName) {\n layout = props.positionHolderNameOnTop ? KCP_CARD_NAME_TOP : KCP_CARD_NAME_BOTTOM;\n }\n }\n\n if (showBrazilianSSN) {\n layout = SSN_CARD;\n if (hasRequiredHolderName) {\n layout = props.positionHolderNameOnTop ? SSN_CARD_NAME_TOP : SSN_CARD_NAME_BOTTOM;\n }\n }\n\n // w. Billing address\n if (countrySpecificSchemas) {\n // Flatten array and remove any numbers that describe how fields should be aligned\n const countrySpecificSchemasFlat: string[] = countrySpecificSchemas['flat'](2).filter(item => typeof item !== 'number') as string[];\n\n let countryBasedAddressLayout = countrySpecificSchemasFlat;\n\n if (billingAddressRequiredFields) {\n // Get intersection of the 2 arrays\n countryBasedAddressLayout = countrySpecificSchemasFlat.filter(x => billingAddressRequiredFields.includes(x));\n }\n\n layout = CREDIT_CARD.concat(countryBasedAddressLayout);\n if (hasRequiredHolderName) {\n layout = props.positionHolderNameOnTop\n ? CREDIT_CARD_NAME_TOP.concat(countryBasedAddressLayout)\n : CREDIT_CARD_NAME_BOTTOM.concat(countryBasedAddressLayout);\n }\n // TODO we are not yet creating a layout for AVS + SSN field (w. or w/o holderName) - is AVS + SSN a real world scenario?\n }\n return layout;\n};\n\n/**\n * Lookup service to map local (CardInput) field refs to a key, possibly region specific, by which to retrieve the translation\n */\nexport const mapFieldKey = (key: string, i18n: Language, countrySpecificLabels: StringObject): string => {\n // console.log('### utils::mapFieldKey:: key', key);\n switch (key) {\n case 'socialSecurityNumber':\n return i18n.get(`boleto.${key}`);\n // Address related - if we have a country specific key for the field - use that to get the translation\n case 'street':\n case 'houseNumberOrName':\n case 'postalCode':\n case 'stateOrProvince':\n case 'city':\n case 'country':\n return countrySpecificLabels?.[key] ? i18n.get(countrySpecificLabels?.[key]) : i18n.get(key);\n // We know that the translated error messages do contain a reference to the field they refer to, so we won't need to map them (currently applies mostly to SecuredFields related errors)\n default:\n return null;\n }\n};\n\nexport const extractPropsForCardFields = (props: CardInputProps) => {\n return {\n // Extract props for CardFieldsWrapper & StoredCardFieldsWrapper(just needs amount, hasCVC, installmentOptions)\n amount: props.amount,\n billingAddressRequired: props.billingAddressRequired,\n billingAddressRequiredFields: props.billingAddressRequiredFields,\n billingAddressAllowedCountries: props.billingAddressAllowedCountries,\n brandsConfiguration: props.brandsConfiguration,\n showStoreDetailsCheckbox: props.showStoreDetailsCheckbox,\n hasCVC: props.hasCVC,\n hasHolderName: props.hasHolderName,\n holderNameRequired: props.holderNameRequired,\n installmentOptions: props.installmentOptions,\n placeholders: props.placeholders,\n positionHolderNameOnTop: props.positionHolderNameOnTop,\n // Extract props for CardFields > CardNumber\n showBrandIcon: props.showBrandIcon,\n showContextualElement: props.showContextualElement,\n // Extract props for StoredCardFields\n lastFour: props.lastFour,\n expiryMonth: props.expiryMonth,\n expiryYear: props.expiryYear,\n disclaimerMessage: props.disclaimerMessage\n };\n};\n\nexport const extractPropsForSFP = (props: CardInputProps) => {\n return {\n autoFocus: props.autoFocus,\n brands: props.brands,\n brandsConfiguration: props.brandsConfiguration,\n clientKey: props.clientKey,\n countryCode: props.countryCode,\n forceCompat: props.forceCompat,\n i18n: props.i18n,\n implementationType: props.implementationType,\n keypadFix: props.keypadFix,\n legacyInputMode: props.legacyInputMode,\n loadingContext: props.loadingContext,\n maskSecurityCode: props.maskSecurityCode,\n exposeExpiryDate: props.exposeExpiryDate,\n minimumExpiryDate: props.minimumExpiryDate,\n onAdditionalSFConfig: props.onAdditionalSFConfig,\n onAdditionalSFRemoved: props.onAdditionalSFRemoved,\n onAllValid: props.onAllValid,\n onAutoComplete: props.onAutoComplete,\n onBinValue: props.onBinValue,\n onConfigSuccess: props.onConfigSuccess,\n handleKeyPress: props.handleKeyPress,\n onError: props.onError,\n onFieldValid: props.onFieldValid,\n onLoad: props.onLoad,\n placeholders: props.placeholders,\n resources: props.resources,\n showContextualElement: props.showContextualElement,\n showWarnings: props.showWarnings,\n trimTrailingSeparator: props.trimTrailingSeparator\n } as SFPProps; // Can't set as return type on fn or it will complain about missing, mandatory, props\n};\n\nexport const handlePartialAddressMode = (addressMode: AddressModeOptions): AddressSpecifications | null => {\n return addressMode == AddressModeOptions.partial ? PARTIAL_ADDRESS_SCHEMA : null;\n};\n\n// Almost all errors are blur based, but some SF ones are not i.e. when an unsupported card is entered or the expiry date is out of range\nexport function lookupBlurBasedErrors(errorCode) {\n // If it's NOT one of these, then it's a blur based error\n return ![\n SF_ErrorCodes.ERROR_MSG_UNSUPPORTED_CARD_ENTERED,\n SF_ErrorCodes.ERROR_MSG_CARD_TOO_OLD,\n SF_ErrorCodes.ERROR_MSG_CARD_TOO_FAR_IN_FUTURE,\n SF_ErrorCodes.ERROR_MSG_CARD_EXPIRES_TOO_SOON\n ].includes(errorCode);\n}\n\nexport function getFullBrandName(brand) {\n return BRAND_READABLE_NAME_MAP[brand] ?? brand;\n}\n\nexport const getCardConfigData = (cardProps: CardConfiguration): CardConfigData => {\n const MAX_LENGTH = 128;\n\n // Extract props from cardProps - mostly setting a default value, if prop not found\n const {\n autoFocus,\n billingAddressAllowedCountries,\n billingAddressMode,\n billingAddressRequired,\n billingAddressRequiredFields,\n brands = DEFAULT_CARD_GROUP_TYPES,\n brandsConfiguration,\n challengeWindowSize = DEFAULT_CHALLENGE_WINDOW_SIZE,\n configuration,\n countryCode,\n data,\n disclaimerMessage,\n disableIOSArrowKeys,\n doBinLookup,\n enableStoreDetails,\n exposeExpiryDate,\n fastlaneConfiguration,\n forceCompat,\n hasHolderName,\n hideCVC,\n holderNameRequired,\n installmentOptions,\n keypadFix,\n legacyInputMode,\n maskSecurityCode,\n minimumExpiryDate,\n name, // = 'none',\n placeholders,\n positionHolderNameOnTop,\n showBrandIcon,\n showInstallmentAmounts,\n showPayButton = false, // hard coded default\n styles,\n onAllValid,\n onBinLookup,\n onBinValue,\n onBlur,\n onBrand,\n onConfigSuccess,\n onEnterKeyPressed,\n onFieldValid,\n onFocus,\n onLoad\n } = cardProps;\n\n const dataString = JSON.stringify(CardInputDefaultProps.data);\n\n const srPanelEnabled = cardProps.modules?.srPanel?.enabled;\n const srPanelMoveFocus = cardProps.modules?.srPanel?.moveFocus;\n\n const riskEnabled = cardProps.modules?.risk?.enabled;\n\n const isFastlaneConfigValid = isFastlaneComponentConfigValid(fastlaneConfiguration);\n\n const billingAddressModeValue = cardProps.onAddressLookup ? 'lookup' : billingAddressMode;\n\n let showKCPType: 'none' | 'auto' | 'atStart' = 'none';\n if (configuration?.koreanAuthenticationRequired === true) {\n showKCPType = countryCode?.toLowerCase() === 'kr' ? 'atStart' : 'auto';\n }\n\n const configData: CardConfigData = {\n autoFocus,\n ...(billingAddressAllowedCountries?.length > 0 && {\n billingAddressAllowedCountries: billingAddressAllowedCountries.toString().substring(0, MAX_LENGTH)\n }),\n billingAddressMode: billingAddressModeValue,\n billingAddressRequired,\n billingAddressRequiredFields: billingAddressRequiredFields?.toString()?.substring(0, MAX_LENGTH),\n // Probably just for development - in real life we wouldn't expect the number of supported brands to push the endpoint limit on 128 chars\n brands: brands?.toString()?.substring(0, MAX_LENGTH),\n challengeWindowSize,\n disableIOSArrowKeys,\n doBinLookup,\n enableStoreDetails,\n exposeExpiryDate,\n forceCompat,\n hasBrandsConfiguration: notFalsy(brandsConfiguration),\n hasData: data && JSON.stringify(cardProps.data) !== dataString,\n hasDisclaimerMessage: !!disclaimerMessage,\n hasHolderName,\n hasInstallmentOptions: notFalsy(installmentOptions),\n hasPlaceholders: notFalsy(placeholders), // has merchant defined placeholders\n hasStylesConfigured: notFalsy(styles),\n hideCVC,\n holderNameRequired,\n keypadFix,\n legacyInputMode,\n maskSecurityCode,\n minimumExpiryDate: !!minimumExpiryDate, // Potentially, in the future, we can send the actual string value\n name,\n positionHolderNameOnTop,\n riskEnabled,\n showBrandIcon,\n showInstallmentAmounts: !!showInstallmentAmounts,\n showKCPType,\n showPayButton,\n socialSecurityNumberMode: configuration?.socialSecurityNumberMode,\n srPanelEnabled,\n srPanelMoveFocus,\n /** callbacks */\n // We need to detect if the merchant themselves has defined these, not if we've set them as a default\n hasOnAllValid: onAllValid !== CardInputDefaultProps.onAllValid,\n hasOnBinValue: onBinValue !== CardInputDefaultProps.onBinValue,\n hasOnBlur: onBlur !== CardInputDefaultProps.onBlur,\n hasOnBrand: onBrand !== CardInputDefaultProps.onBrand,\n hasOnConfigSuccess: onConfigSuccess !== CardInputDefaultProps.onConfigSuccess,\n hasOnFieldValid: onFieldValid !== CardInputDefaultProps.onFieldValid,\n hasOnFocus: onFocus !== CardInputDefaultProps.onFocus,\n hasOnLoad: onLoad !== CardInputDefaultProps.onLoad,\n // Card level props\n hasOnBinLookup: !!onBinLookup,\n hasOnEnterKeyPressed: !!onEnterKeyPressed,\n /**\n * Fastlane\n */\n ...(isFastlaneConfigValid && {\n hasFastlaneConfigured: true,\n isFastlaneConsentDefaultOn: fastlaneConfiguration.defaultToggleState\n })\n };\n\n return configData;\n};\n\nexport const mapDualBrandButtons = (dualBrandSelectElements: DualBrandSelectElement[], brandsConfiguration: CardBrandsConfiguration): any => {\n return dualBrandSelectElements.map(item => {\n const brand = item.id;\n const getImage = useImage();\n const imageName = brand === 'card' ? 'nocard' : brand;\n const imageURL = brandsConfiguration[brand]?.icon ?? getCardImageUrl(imageName, getImage);\n\n // TODO - check below if we have to still generate altName through the mapping function or whether it just\n // corresponds to item.brandObject.localeBrand\n return {\n id: item.id,\n name: item.brandObject.localeBrand || item.brandObject.brand,\n imageURL,\n altName: getFullBrandName(brand)\n };\n });\n};\n\n/**\n * Only if the brands in EU_BrandArray are present in the binLookup response should we handle dual branding based on EU regulations\n *\n * If the result from Array.filter contains anything - then we are in a EU dual branding regulation scenario, i.e.\n * - Show the new dualBranding UI Buttons\n * - Preselect a card brand\n */\nexport const mustHandleDualBrandingAccordingToEURegulations = (\n EU_BrandArray: string[],\n returnedDualBrandingObjects: DualBrandSelectElement[] | BrandObject[],\n key: string\n) => !!returnedDualBrandingObjects.filter(item => EU_BrandArray.includes(item[key])).length;\n"],"names":["getCardImageUrl","brand","getImage","type","extension","hasValidInstallmentsObject","installments","plan","value","getLayout","props","showKCP","showBrazilianSSN","countrySpecificSchemas","billingAddressRequiredFields","layout","CREDIT_CARD","hasRequiredHolderName","hasHolderName","holderNameRequired","positionHolderNameOnTop","CREDIT_CARD_NAME_TOP","CREDIT_CARD_NAME_BOTTOM","KCP_CARD","KCP_CARD_NAME_TOP","KCP_CARD_NAME_BOTTOM","SSN_CARD","SSN_CARD_NAME_TOP","SSN_CARD_NAME_BOTTOM","countrySpecificSchemasFlat","filter","item","countryBasedAddressLayout","x","includes","concat","mapFieldKey","key","i18n","countrySpecificLabels","get","extractPropsForCardFields","amount","billingAddressRequired","billingAddressAllowedCountries","brandsConfiguration","showStoreDetailsCheckbox","hasCVC","installmentOptions","placeholders","showBrandIcon","showContextualElement","lastFour","expiryMonth","expiryYear","disclaimerMessage","extractPropsForSFP","autoFocus","brands","clientKey","countryCode","forceCompat","implementationType","keypadFix","legacyInputMode","loadingContext","maskSecurityCode","exposeExpiryDate","minimumExpiryDate","onAdditionalSFConfig","onAdditionalSFRemoved","onAllValid","onAutoComplete","onBinValue","onConfigSuccess","handleKeyPress","onError","onFieldValid","onLoad","resources","showWarnings","trimTrailingSeparator","handlePartialAddressMode","addressMode","AddressModeOptions","partial","PARTIAL_ADDRESS_SCHEMA","lookupBlurBasedErrors","errorCode","SF_ErrorCodes","ERROR_MSG_UNSUPPORTED_CARD_ENTERED","ERROR_MSG_CARD_TOO_OLD","ERROR_MSG_CARD_TOO_FAR_IN_FUTURE","ERROR_MSG_CARD_EXPIRES_TOO_SOON","getFullBrandName","BRAND_READABLE_NAME_MAP","getCardConfigData","cardProps","billingAddressMode","DEFAULT_CARD_GROUP_TYPES","challengeWindowSize","DEFAULT_CHALLENGE_WINDOW_SIZE","configuration","data","disableIOSArrowKeys","doBinLookup","enableStoreDetails","fastlaneConfiguration","hideCVC","name","showInstallmentAmounts","showPayButton","styles","onBinLookup","onBlur","onBrand","onEnterKeyPressed","onFocus","dataString","JSON","stringify","CardInputDefaultProps","srPanelEnabled","modules","srPanel","enabled","srPanelMoveFocus","moveFocus","riskEnabled","risk","isFastlaneConfigValid","isFastlaneComponentConfigValid","billingAddressModeValue","onAddressLookup","showKCPType","koreanAuthenticationRequired","toLowerCase","length","toString","substring","hasBrandsConfiguration","notFalsy","hasData","hasDisclaimerMessage","hasInstallmentOptions","hasPlaceholders","hasStylesConfigured","socialSecurityNumberMode","hasOnAllValid","hasOnBinValue","hasOnBlur","hasOnBrand","hasOnConfigSuccess","hasOnFieldValid","hasOnFocus","hasOnLoad","hasOnBinLookup","hasOnEnterKeyPressed","hasFastlaneConfigured","isFastlaneConsentDefaultOn","defaultToggleState","mapDualBrandButtons","dualBrandSelectElements","map","id","useImage","imageName","imageURL","icon","brandObject","localeBrand","altName","mustHandleDualBrandingAccordingToEURegulations","EU_BrandArray","returnedDualBrandingObjects"],"mappings":"i1BA2BO,MAAMA,EAAkB,CAACC,EAAeC,IAMpCA,EALc,CACjBC,KAAgB,SAAVF,EAAmB,SAAWA,GAAS,SAC7CG,UAAW,OAGRF,CAAuBD,GAOrBI,EAA8BC,GACT,cAAvBA,GAAcC,MAAwBD,GAAcE,MAAQ,EAG1DC,EAAY,EACrBC,QACAC,UACAC,mBACAC,yBAAyB,KACzBC,+BAA+B,SAE/B,IAAIC,EAASC,EACb,MAAMC,EAAwBP,EAAMQ,eAAiBR,EAAMS,mBAqB3D,GAnBIF,IACAF,EAASL,EAAMU,wBAA0BC,EAAuBC,GAGhEX,IACAI,EAASQ,EACLN,IACAF,EAASL,EAAMU,wBAA0BI,EAAoBC,IAIjEb,IACAG,EAASW,EACLT,IACAF,EAASL,EAAMU,wBAA0BO,EAAoBC,IAKjEf,EAAwB,CAExB,MAAMgB,EAAuChB,EAAuB,KAAQ,GAAGiB,OAAOC,GAAwB,iBAATA,GAErG,IAAIC,EAA4BH,EAE5Bf,IAEAkB,EAA4BH,EAA2BC,OAAOG,GAAKnB,EAA6BoB,SAASD,KAG7GlB,EAASC,EAAYmB,OAAOH,GACxBf,IACAF,EAASL,EAAMU,wBACTC,EAAqBc,OAAOH,GAC5BV,EAAwBa,OAAOH,GAG7C,CACA,OAAOjB,GAMEqB,EAAc,CAACC,EAAaC,EAAgBC,KAErD,OAAQF,GACJ,IAAK,uBACD,OAAOC,EAAKE,IAAI,UAAUH,KAE9B,IAAK,SACL,IAAK,oBACL,IAAK,aACL,IAAK,kBACL,IAAK,OACL,IAAK,UACD,OAAOE,IAAwBF,GAAOC,EAAKE,IAA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,EAAKqI,GACblK,EAAWmK,IACXC,EAAsB,SAAVrK,EAAmB,SAAWA,EAC1CsK,EAAW1H,EAAoB5C,IAAQuK,MAAQxK,EAAgBsK,EAAWpK,GAIhF,MAAO,CACHkK,GAAIrI,EAAKqI,GACTvD,KAAM9E,EAAK0I,YAAYC,aAAe3I,EAAK0I,YAAYxK,MACvDsK,WACAI,QAAS7E,EAAiB7F,MAYzB2K,EAAiD,CAC1DC,EACAC,EACAzI,MACGyI,EAA4BhJ,OAAOC,GAAQ8I,EAAc3I,SAASH,EAAKM,KAAOoG"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createElement as t}from"../../external/preact/dist/preact.js";import{UIElement as e}from"../internal/UIElement/UIElement.js";import o from"./defaultProps.js";import{DropinComponent as i}from"./components/DropinComponent.js";import{CoreProvider as n}from"../../core/Context/CoreProvider.js";import{getCommonProps as s}from"./components/utils.js";import r from"./elements/createElements.js";import a from"./elements/createStoredElements.js";import h from"./elements/createInstantPaymentElements.js";import{hasOwnProperty as d}from"../../utils/hasOwnProperty.js";import m from"../../core/Errors/SRPanelProvider.js";import p from"./elements/splitPaymentMethods.js";import{TxVariants as l}from"../tx-variants.js";function c(t,e,o){return e in t?Object.defineProperty(t,e,{value:o,enumerable:!0,configurable:!0,writable:!0}):t[e]=o,t}const y=["paywithgoogle","googlepay","applepay"];class f extends e{storeElementRefOnCore(){this.core.storeElementReference(this)}formatProps(t){return{type:"dropin",...super.formatProps(t),instantPaymentTypes:Array.from(new Set(t.instantPaymentTypes)).filter(t=>y.includes(t))}}get isValid(){return!!this.dropinRef&&!!this.dropinRef.state.activePaymentMethod&&!!this.dropinRef.state.activePaymentMethod.isValid}showValidation(){return this.dropinRef.state.activePaymentMethod&&this.dropinRef.state.activePaymentMethod.showValidation(),this}setStatus(t,e={}){return this.dropinRef?.setStatus(t,e),this}get activePaymentMethod(){return this.dropinRef?.state||this.dropinRef?.state.activePaymentMethod?this.dropinRef.state.activePaymentMethod:null}get data(){return this.activePaymentMethod?this.dropinRef.state.activePaymentMethod.data:null}displayFinalAnimation(t){this.props.disableFinalAnimation||this.dropinRef
|
|
1
|
+
import{createElement as t}from"../../external/preact/dist/preact.js";import{UIElement as e}from"../internal/UIElement/UIElement.js";import o from"./defaultProps.js";import{DropinComponent as i}from"./components/DropinComponent.js";import{CoreProvider as n}from"../../core/Context/CoreProvider.js";import{getCommonProps as s}from"./components/utils.js";import r from"./elements/createElements.js";import a from"./elements/createStoredElements.js";import h from"./elements/createInstantPaymentElements.js";import{hasOwnProperty as d}from"../../utils/hasOwnProperty.js";import m from"../../core/Errors/SRPanelProvider.js";import p from"./elements/splitPaymentMethods.js";import{TxVariants as l}from"../tx-variants.js";function c(t,e,o){return e in t?Object.defineProperty(t,e,{value:o,enumerable:!0,configurable:!0,writable:!0}):t[e]=o,t}const y=["paywithgoogle","googlepay","applepay"];class f extends e{storeElementRefOnCore(){this.core.storeElementReference(this)}formatProps(t){return{type:"dropin",...super.formatProps(t),instantPaymentTypes:Array.from(new Set(t.instantPaymentTypes)).filter(t=>y.includes(t))}}get isValid(){return!!this.dropinRef&&!!this.dropinRef.state.activePaymentMethod&&!!this.dropinRef.state.activePaymentMethod.isValid}showValidation(){return this.dropinRef.state.activePaymentMethod&&this.dropinRef.state.activePaymentMethod.showValidation(),this}setStatus(t,e={}){return this.dropinRef?.setStatus(t,e),this}get activePaymentMethod(){return this.dropinRef?.state||this.dropinRef?.state.activePaymentMethod?this.dropinRef.state.activePaymentMethod:null}get data(){return this.activePaymentMethod?this.dropinRef.state.activePaymentMethod.data:null}displayFinalAnimation(t){this.props.disableFinalAnimation||this.dropinRef?.setStatus(t)}submit(){if(!this.activePaymentMethod)throw new Error("No active payment method.");this.activePaymentMethod.isValid||this.activePaymentMethod.showValidation(),this.activePaymentMethod.isInstantPayment&&this.closeActivePaymentMethod(),this.activePaymentMethod.submit()}handleAction(t,e={}){if(!t||!t.type){if(d(t,"action")&&d(t,"resultCode"))throw new Error('handleAction::Invalid Action - the passed action object itself has an "action" property and a "resultCode": have you passed in the whole response object by mistake?');throw new Error('handleAction::Invalid Action - the passed action object does not have a "type" property')}if("redirect"!==t.type&&this.activePaymentMethod?.updateWithAction)return this.activePaymentMethod.updateWithAction(t);this.elementRef instanceof f&&(e={...this.elementRef.activePaymentMethod?.props,...e});const o=this.core.createFromAction(t,{...e,elementRef:this.elementRef,onAdditionalDetails:this.handleAdditionalDetails,isDropin:!0});return o?(this.setStatus(o.props.statusType,{component:o}),this.componentFromAction=o,this):null}closeActivePaymentMethod(){this.dropinRef.closeActivePaymentMethod()}handleKeyPress(t){if("Enter"===t.key||"Enter"===t.code){if("radio"===document?.activeElement?.getAttribute("role"))return;super.handleKeyPress(t)}}onEnterKeyPressed(t,e){const o=this.activePaymentMethod??e;this.activePaymentMethod?.onEnterKeyPressed(t,o)}render(){return t(n,{i18n:this.props.i18n,loadingContext:this.props.loadingContext,resources:this.resources},t(m,{srPanel:this.props.modules.srPanel},t(i,{...this.props,core:this.core,elementRef:this.elementRef,onCreateElements:this.handleCreate,ref:t=>{this.dropinRef=t}})))}constructor(t,e){super(t,e),c(this,"dropinRef",null),c(this,"paymentMethodsConfiguration",void 0),c(this,"componentFromAction",void 0),c(this,"handleCreate",()=>{const{paymentMethodsConfiguration:t,showStoredPaymentMethods:e,showPaymentMethods:o,instantPaymentTypes:i}=this.props,{paymentMethods:n,storedPaymentMethods:d,instantPaymentMethods:m,fastlanePaymentMethod:l}=p(this.core.paymentMethodsResponse,i),c=s({...this.props,elementRef:this.elementRef}),y=o?r(n,t,c,this.core):[],f=h(m,t,c,this.core);return[e?a(this.props.filterStoredPaymentMethods?.(d)??d,t,c,this.core):[],y,f,l?r([l],t,c,this.core):[]]}),c(this,"handleOrder",({order:t})=>{this.updateParent({order:t})}),this.submit=this.submit.bind(this),this.handleAction=this.handleAction.bind(this),this.props.paymentMethodComponents.forEach(t=>this.core.register(t)),this.paymentMethodsConfiguration=this.props.paymentMethodsConfiguration||{}}}c(f,"type",l.dropin),c(f,"defaultProps",o);export{f as default};
|
|
2
2
|
//# sourceMappingURL=Dropin.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Dropin.js","sources":["../../../../src/components/Dropin/Dropin.tsx"],"sourcesContent":["import { h } from 'preact';\nimport UIElement from '../internal/UIElement/UIElement';\nimport defaultProps from './defaultProps';\nimport DropinComponent from '../../components/Dropin/components/DropinComponent';\nimport { CoreProvider } from '../../core/Context/CoreProvider';\nimport { getCommonProps } from './components/utils';\nimport { createElements, createStoredElements } from './elements';\nimport createInstantPaymentElements from './elements/createInstantPaymentElements';\nimport { hasOwnProperty } from '../../utils/hasOwnProperty';\nimport SRPanelProvider from '../../core/Errors/SRPanelProvider';\nimport splitPaymentMethods from './elements/splitPaymentMethods';\nimport { TxVariants } from '../tx-variants';\n\nimport type { DropinConfiguration, InstantPaymentTypes, PaymentMethodsConfiguration } from './types';\nimport type { PaymentAction, PaymentResponseData } from '../../types/global-types';\nimport type { ICore } from '../../core/types';\nimport type { IDropin } from './types';\n\nconst SUPPORTED_INSTANT_PAYMENTS = ['paywithgoogle', 'googlepay', 'applepay'];\n\nclass DropinElement extends UIElement<DropinConfiguration> implements IDropin {\n public static type = TxVariants.dropin;\n\n protected static defaultProps = defaultProps;\n\n public dropinRef = null;\n\n private paymentMethodsConfiguration: PaymentMethodsConfiguration;\n /**\n * Reference to the component created from `handleAction` (Ex.: ThreeDS2Challenge)\n */\n public componentFromAction?: UIElement;\n\n constructor(checkout: ICore, props?: DropinConfiguration) {\n super(checkout, props);\n this.submit = this.submit.bind(this);\n this.handleAction = this.handleAction.bind(this);\n\n this.props.paymentMethodComponents.forEach(PaymentMethod => this.core.register(PaymentMethod));\n this.paymentMethodsConfiguration = this.props.paymentMethodsConfiguration || {};\n }\n\n protected override storeElementRefOnCore() {\n this.core.storeElementReference(this);\n }\n\n formatProps(props) {\n return {\n type: 'dropin', // for analytics\n ...super.formatProps(props),\n instantPaymentTypes: Array.from<InstantPaymentTypes>(new Set(props.instantPaymentTypes)).filter(value =>\n SUPPORTED_INSTANT_PAYMENTS.includes(value)\n )\n };\n }\n\n get isValid() {\n return !!this.dropinRef && !!this.dropinRef.state.activePaymentMethod && !!this.dropinRef.state.activePaymentMethod.isValid;\n }\n\n showValidation() {\n if (this.dropinRef.state.activePaymentMethod) {\n this.dropinRef.state.activePaymentMethod.showValidation();\n }\n\n return this;\n }\n\n public setStatus(status, props = {}): this {\n this.dropinRef?.setStatus(status, props);\n return this;\n }\n\n get activePaymentMethod() {\n if (!this.dropinRef?.state && !this.dropinRef?.state.activePaymentMethod) {\n return null;\n }\n\n return this.dropinRef.state.activePaymentMethod;\n }\n\n get data() {\n if (!this.activePaymentMethod) {\n return null;\n }\n\n return this.dropinRef.state.activePaymentMethod.data;\n }\n\n public displayFinalAnimation(type: 'success' | 'error') {\n if (this.props.disableFinalAnimation) return;\n\n this.dropinRef.setStatus(type);\n }\n\n /**\n * Calls the onSubmit event with the state of the activePaymentMethod\n */\n public override submit(): void {\n if (!this.activePaymentMethod) {\n throw new Error('No active payment method.');\n }\n\n if (!this.activePaymentMethod.isValid) {\n this.activePaymentMethod.showValidation();\n }\n\n if (this.activePaymentMethod.isInstantPayment) {\n this.closeActivePaymentMethod();\n }\n\n this.activePaymentMethod.submit();\n }\n\n /**\n * Creates the Drop-in elements\n */\n private handleCreate = () => {\n const { paymentMethodsConfiguration, showStoredPaymentMethods, showPaymentMethods, instantPaymentTypes } = this.props;\n\n const { paymentMethods, storedPaymentMethods, instantPaymentMethods, fastlanePaymentMethod } = splitPaymentMethods(\n this.core.paymentMethodsResponse,\n instantPaymentTypes\n );\n\n const commonProps = getCommonProps({ ...this.props, elementRef: this.elementRef });\n\n const elements = showPaymentMethods ? createElements(paymentMethods, paymentMethodsConfiguration, commonProps, this.core) : [];\n const instantPaymentElements = createInstantPaymentElements(instantPaymentMethods, paymentMethodsConfiguration, commonProps, this.core);\n const storedElements = showStoredPaymentMethods\n ? createStoredElements(\n this.props.filterStoredPaymentMethods?.(storedPaymentMethods) ?? storedPaymentMethods,\n paymentMethodsConfiguration,\n commonProps,\n this.core\n )\n : [];\n const fastlanePaymentElement = fastlanePaymentMethod\n ? createElements([fastlanePaymentMethod], paymentMethodsConfiguration, commonProps, this.core)\n : [];\n\n return [storedElements, elements, instantPaymentElements, fastlanePaymentElement];\n };\n\n public handleAction(action: PaymentAction, props = {}): this | null {\n if (!action || !action.type) {\n if (hasOwnProperty(action, 'action') && hasOwnProperty(action, 'resultCode')) {\n throw new Error(\n 'handleAction::Invalid Action - the passed action object itself has an \"action\" property and ' +\n 'a \"resultCode\": have you passed in the whole response object by mistake?'\n );\n }\n throw new Error('handleAction::Invalid Action - the passed action object does not have a \"type\" property');\n }\n\n if (action.type !== 'redirect' && this.activePaymentMethod?.updateWithAction) {\n return this.activePaymentMethod.updateWithAction(action);\n }\n\n if (this.elementRef instanceof DropinElement) {\n props = {\n ...this.elementRef.activePaymentMethod?.props,\n ...props\n };\n }\n\n const paymentAction: UIElement = this.core.createFromAction(action, {\n ...props,\n elementRef: this.elementRef, // maintain elementRef for 3DS2 flow\n onAdditionalDetails: this.handleAdditionalDetails,\n isDropin: true\n });\n\n if (paymentAction) {\n this.setStatus(paymentAction.props.statusType, { component: paymentAction });\n this.componentFromAction = paymentAction;\n return this;\n }\n\n return null;\n }\n\n /**\n * handleOrder is implemented so we don't trigger a callback like in the components\n * @param response - PaymentResponse\n */\n protected handleOrder = ({ order }: PaymentResponseData): void => {\n void this.updateParent({ order });\n };\n\n closeActivePaymentMethod() {\n this.dropinRef.closeActivePaymentMethod();\n }\n\n protected handleKeyPress(e: h.JSX.TargetedKeyboardEvent<HTMLInputElement> | KeyboardEvent) {\n if (e.key === 'Enter' || e.code === 'Enter') {\n // If the active element has role=\"radio\", we're on a header in the PMList, in which case we don't want to validate the form, or, prevent the default behaviour\n const isPMHeader = document?.activeElement?.getAttribute('role') === 'radio';\n if (isPMHeader) {\n return;\n }\n super.handleKeyPress(e);\n }\n }\n\n protected onEnterKeyPressed(activeElement: Element, component: UIElement) {\n // We want to have a ref to the activePM, if we can; not a ref to the Dropin\n const pmComponent = this.activePaymentMethod ?? component;\n this.activePaymentMethod?.onEnterKeyPressed(activeElement, pmComponent);\n }\n\n render() {\n return (\n <CoreProvider i18n={this.props.i18n} loadingContext={this.props.loadingContext} resources={this.resources}>\n <SRPanelProvider srPanel={this.props.modules.srPanel}>\n <DropinComponent\n {...this.props}\n core={this.core}\n elementRef={this.elementRef}\n onCreateElements={this.handleCreate}\n ref={dropinRef => {\n this.dropinRef = dropinRef;\n }}\n />\n </SRPanelProvider>\n </CoreProvider>\n );\n }\n}\n\nexport default DropinElement;\n"],"names":["SUPPORTED_INSTANT_PAYMENTS","DropinElement","UIElement","storeElementRefOnCore","this","core","storeElementReference","formatProps","props","type","super","instantPaymentTypes","Array","from","Set","filter","value","includes","isValid","dropinRef","state","activePaymentMethod","showValidation","setStatus","status","data","displayFinalAnimation","disableFinalAnimation","submit","Error","isInstantPayment","closeActivePaymentMethod","handleAction","action","hasOwnProperty","updateWithAction","elementRef","paymentAction","createFromAction","onAdditionalDetails","handleAdditionalDetails","isDropin","statusType","component","componentFromAction","handleKeyPress","e","key","code","document","activeElement","getAttribute","onEnterKeyPressed","pmComponent","render","h","CoreProvider","i18n","loadingContext","resources","SRPanelProvider","srPanel","modules","DropinComponent","onCreateElements","handleCreate","ref","constructor","checkout","_define_property","paymentMethodsConfiguration","showStoredPaymentMethods","showPaymentMethods","paymentMethods","storedPaymentMethods","instantPaymentMethods","fastlanePaymentMethod","splitPaymentMethods","paymentMethodsResponse","commonProps","getCommonProps","elements","createElements","instantPaymentElements","createInstantPaymentElements","createStoredElements","filterStoredPaymentMethods","handleOrder","order","updateParent","bind","paymentMethodComponents","forEach","PaymentMethod","register","TxVariants","dropin","defaultProps"],"mappings":"m0BAkBA,MAAMA,EAA6B,CAAC,gBAAiB,YAAa,YAElE,MAAMC,UAAsBC,EAsBLC,qBAAAA,GACfC,KAAKC,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,eAAe,KACnB,MAAMK,4BAAEA,EAA2BC,yBAAEA,EAAwBC,mBAAEA,EAAkB7D,oBAAEA,GAAwBP,KAAKI,OAE1GiE,eAAEA,EAAcC,qBAAEA,EAAoBC,sBAAEA,EAAqBC,sBAAEA,GAA0BC,EAC3FzE,KAAKC,KAAKyE,uBACVnE,GAGEoE,EAAcC,EAAe,IAAK5E,KAAKI,MAAO4B,WAAYhC,KAAKgC,aAE/D6C,EAAWT,EAAqBU,EAAeT,EAAgBH,EAA6BS,EAAa3E,KAAKC,MAAQ,GACtH8E,EAAyBC,EAA6BT,EAAuBL,EAA6BS,EAAa3E,KAAKC,MAalI,MAAO,CAZgBkE,EACjBc,EACIjF,KAAKI,MAAM8E,6BAA6BZ,IAAyBA,EACjEJ,EACAS,EACA3E,KAAKC,MAET,GAKkB4E,EAAUE,EAJHP,EACzBM,EAAe,CAACN,GAAwBN,EAA6BS,EAAa3E,KAAKC,MACvF,MA+CVgE,EAAAjE,KAAUmF,cAAc,EAAGC,YAClBpF,KAAKqF,aAAa,CAAED,YAxJzBpF,KAAKwB,OAASxB,KAAKwB,OAAO8D,KAAKtF,MAC/BA,KAAK4B,aAAe5B,KAAK4B,aAAa0D,KAAKtF,MAE3CA,KAAKI,MAAMmF,wBAAwBC,QAAQC,GAAiBzF,KAAKC,KAAKyF,SAASD,IAC/EzF,KAAKkE,4BAA8BlE,KAAKI,MAAM8D,6BAA+B,CAAA,CACjF,EAnBAD,EADEpE,EACYQ,OAAOsF,EAAWC,QAEhC3B,EAHEpE,EAGegG,eAAeA"}
|
|
1
|
+
{"version":3,"file":"Dropin.js","sources":["../../../../src/components/Dropin/Dropin.tsx"],"sourcesContent":["import { h } from 'preact';\nimport UIElement from '../internal/UIElement/UIElement';\nimport defaultProps from './defaultProps';\nimport DropinComponent from '../../components/Dropin/components/DropinComponent';\nimport { CoreProvider } from '../../core/Context/CoreProvider';\nimport { getCommonProps } from './components/utils';\nimport { createElements, createStoredElements } from './elements';\nimport createInstantPaymentElements from './elements/createInstantPaymentElements';\nimport { hasOwnProperty } from '../../utils/hasOwnProperty';\nimport SRPanelProvider from '../../core/Errors/SRPanelProvider';\nimport splitPaymentMethods from './elements/splitPaymentMethods';\nimport { TxVariants } from '../tx-variants';\n\nimport type { DropinConfiguration, InstantPaymentTypes, PaymentMethodsConfiguration } from './types';\nimport type { PaymentAction, PaymentResponseData } from '../../types/global-types';\nimport type { ICore } from '../../core/types';\nimport type { IDropin } from './types';\n\nconst SUPPORTED_INSTANT_PAYMENTS = ['paywithgoogle', 'googlepay', 'applepay'];\n\nclass DropinElement extends UIElement<DropinConfiguration> implements IDropin {\n public static type = TxVariants.dropin;\n\n protected static defaultProps = defaultProps;\n\n public dropinRef = null;\n\n private paymentMethodsConfiguration: PaymentMethodsConfiguration;\n /**\n * Reference to the component created from `handleAction` (Ex.: ThreeDS2Challenge)\n */\n public componentFromAction?: UIElement;\n\n constructor(checkout: ICore, props?: DropinConfiguration) {\n super(checkout, props);\n this.submit = this.submit.bind(this);\n this.handleAction = this.handleAction.bind(this);\n\n this.props.paymentMethodComponents.forEach(PaymentMethod => this.core.register(PaymentMethod));\n this.paymentMethodsConfiguration = this.props.paymentMethodsConfiguration || {};\n }\n\n protected override storeElementRefOnCore() {\n this.core.storeElementReference(this);\n }\n\n formatProps(props) {\n return {\n type: 'dropin', // for analytics\n ...super.formatProps(props),\n instantPaymentTypes: Array.from<InstantPaymentTypes>(new Set(props.instantPaymentTypes)).filter(value =>\n SUPPORTED_INSTANT_PAYMENTS.includes(value)\n )\n };\n }\n\n get isValid() {\n return !!this.dropinRef && !!this.dropinRef.state.activePaymentMethod && !!this.dropinRef.state.activePaymentMethod.isValid;\n }\n\n showValidation() {\n if (this.dropinRef.state.activePaymentMethod) {\n this.dropinRef.state.activePaymentMethod.showValidation();\n }\n\n return this;\n }\n\n public setStatus(status, props = {}): this {\n this.dropinRef?.setStatus(status, props);\n return this;\n }\n\n get activePaymentMethod() {\n if (!this.dropinRef?.state && !this.dropinRef?.state.activePaymentMethod) {\n return null;\n }\n\n return this.dropinRef.state.activePaymentMethod;\n }\n\n get data() {\n if (!this.activePaymentMethod) {\n return null;\n }\n\n return this.dropinRef.state.activePaymentMethod.data;\n }\n\n public displayFinalAnimation(type: 'success' | 'error') {\n if (this.props.disableFinalAnimation) return;\n\n this.dropinRef?.setStatus(type);\n }\n\n /**\n * Calls the onSubmit event with the state of the activePaymentMethod\n */\n public override submit(): void {\n if (!this.activePaymentMethod) {\n throw new Error('No active payment method.');\n }\n\n if (!this.activePaymentMethod.isValid) {\n this.activePaymentMethod.showValidation();\n }\n\n if (this.activePaymentMethod.isInstantPayment) {\n this.closeActivePaymentMethod();\n }\n\n this.activePaymentMethod.submit();\n }\n\n /**\n * Creates the Drop-in elements\n */\n private handleCreate = () => {\n const { paymentMethodsConfiguration, showStoredPaymentMethods, showPaymentMethods, instantPaymentTypes } = this.props;\n\n const { paymentMethods, storedPaymentMethods, instantPaymentMethods, fastlanePaymentMethod } = splitPaymentMethods(\n this.core.paymentMethodsResponse,\n instantPaymentTypes\n );\n\n const commonProps = getCommonProps({ ...this.props, elementRef: this.elementRef });\n\n const elements = showPaymentMethods ? createElements(paymentMethods, paymentMethodsConfiguration, commonProps, this.core) : [];\n const instantPaymentElements = createInstantPaymentElements(instantPaymentMethods, paymentMethodsConfiguration, commonProps, this.core);\n const storedElements = showStoredPaymentMethods\n ? createStoredElements(\n this.props.filterStoredPaymentMethods?.(storedPaymentMethods) ?? storedPaymentMethods,\n paymentMethodsConfiguration,\n commonProps,\n this.core\n )\n : [];\n const fastlanePaymentElement = fastlanePaymentMethod\n ? createElements([fastlanePaymentMethod], paymentMethodsConfiguration, commonProps, this.core)\n : [];\n\n return [storedElements, elements, instantPaymentElements, fastlanePaymentElement];\n };\n\n public handleAction(action: PaymentAction, props = {}): this | null {\n if (!action || !action.type) {\n if (hasOwnProperty(action, 'action') && hasOwnProperty(action, 'resultCode')) {\n throw new Error(\n 'handleAction::Invalid Action - the passed action object itself has an \"action\" property and ' +\n 'a \"resultCode\": have you passed in the whole response object by mistake?'\n );\n }\n throw new Error('handleAction::Invalid Action - the passed action object does not have a \"type\" property');\n }\n\n if (action.type !== 'redirect' && this.activePaymentMethod?.updateWithAction) {\n return this.activePaymentMethod.updateWithAction(action);\n }\n\n if (this.elementRef instanceof DropinElement) {\n props = {\n ...this.elementRef.activePaymentMethod?.props,\n ...props\n };\n }\n\n const paymentAction: UIElement = this.core.createFromAction(action, {\n ...props,\n elementRef: this.elementRef, // maintain elementRef for 3DS2 flow\n onAdditionalDetails: this.handleAdditionalDetails,\n isDropin: true\n });\n\n if (paymentAction) {\n this.setStatus(paymentAction.props.statusType, { component: paymentAction });\n this.componentFromAction = paymentAction;\n return this;\n }\n\n return null;\n }\n\n /**\n * handleOrder is implemented so we don't trigger a callback like in the components\n * @param response - PaymentResponse\n */\n protected handleOrder = ({ order }: PaymentResponseData): void => {\n void this.updateParent({ order });\n };\n\n closeActivePaymentMethod() {\n this.dropinRef.closeActivePaymentMethod();\n }\n\n protected handleKeyPress(e: h.JSX.TargetedKeyboardEvent<HTMLInputElement> | KeyboardEvent) {\n if (e.key === 'Enter' || e.code === 'Enter') {\n // If the active element has role=\"radio\", we're on a header in the PMList, in which case we don't want to validate the form, or, prevent the default behaviour\n const isPMHeader = document?.activeElement?.getAttribute('role') === 'radio';\n if (isPMHeader) {\n return;\n }\n super.handleKeyPress(e);\n }\n }\n\n protected onEnterKeyPressed(activeElement: Element, component: UIElement) {\n // We want to have a ref to the activePM, if we can; not a ref to the Dropin\n const pmComponent = this.activePaymentMethod ?? component;\n this.activePaymentMethod?.onEnterKeyPressed(activeElement, pmComponent);\n }\n\n render() {\n return (\n <CoreProvider i18n={this.props.i18n} loadingContext={this.props.loadingContext} resources={this.resources}>\n <SRPanelProvider srPanel={this.props.modules.srPanel}>\n <DropinComponent\n {...this.props}\n core={this.core}\n elementRef={this.elementRef}\n onCreateElements={this.handleCreate}\n ref={dropinRef => {\n this.dropinRef = dropinRef;\n }}\n />\n </SRPanelProvider>\n </CoreProvider>\n );\n }\n}\n\nexport default DropinElement;\n"],"names":["SUPPORTED_INSTANT_PAYMENTS","DropinElement","UIElement","storeElementRefOnCore","this","core","storeElementReference","formatProps","props","type","super","instantPaymentTypes","Array","from","Set","filter","value","includes","isValid","dropinRef","state","activePaymentMethod","showValidation","setStatus","status","data","displayFinalAnimation","disableFinalAnimation","submit","Error","isInstantPayment","closeActivePaymentMethod","handleAction","action","hasOwnProperty","updateWithAction","elementRef","paymentAction","createFromAction","onAdditionalDetails","handleAdditionalDetails","isDropin","statusType","component","componentFromAction","handleKeyPress","e","key","code","document","activeElement","getAttribute","onEnterKeyPressed","pmComponent","render","h","CoreProvider","i18n","loadingContext","resources","SRPanelProvider","srPanel","modules","DropinComponent","onCreateElements","handleCreate","ref","constructor","checkout","_define_property","paymentMethodsConfiguration","showStoredPaymentMethods","showPaymentMethods","paymentMethods","storedPaymentMethods","instantPaymentMethods","fastlanePaymentMethod","splitPaymentMethods","paymentMethodsResponse","commonProps","getCommonProps","elements","createElements","instantPaymentElements","createInstantPaymentElements","createStoredElements","filterStoredPaymentMethods","handleOrder","order","updateParent","bind","paymentMethodComponents","forEach","PaymentMethod","register","TxVariants","dropin","defaultProps"],"mappings":"m0BAkBA,MAAMA,EAA6B,CAAC,gBAAiB,YAAa,YAElE,MAAMC,UAAsBC,EAsBLC,qBAAAA,GACfC,KAAKC,KAAKC,sBAAsBF,KACpC,CAEAG,WAAAA,CAAYC,GACR,MAAO,CACHC,KAAM,YACHC,MAAMH,YAAYC,GACrBG,oBAAqBC,MAAMC,KAA0B,IAAIC,IAAIN,EAAMG,sBAAsBI,OAAOC,GAC5FhB,EAA2BiB,SAASD,IAGhD,CAEA,WAAIE,GACA,QAASd,KAAKe,aAAef,KAAKe,UAAUC,MAAMC,uBAAyBjB,KAAKe,UAAUC,MAAMC,oBAAoBH,OACxH,CAEAI,cAAAA,GAKI,OAJIlB,KAAKe,UAAUC,MAAMC,qBACrB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C,EAA6BT,EAAuBL,EAA6BS,EAAa3E,KAAKC,MAalI,MAAO,CAZgBkE,EACjBc,EACIjF,KAAKI,MAAM8E,6BAA6BZ,IAAyBA,EACjEJ,EACAS,EACA3E,KAAKC,MAET,GAKkB4E,EAAUE,EAJHP,EACzBM,EAAe,CAACN,GAAwBN,EAA6BS,EAAa3E,KAAKC,MACvF,MA+CVgE,EAAAjE,KAAUmF,cAAc,EAAGC,YAClBpF,KAAKqF,aAAa,CAAED,YAxJzBpF,KAAKwB,OAASxB,KAAKwB,OAAO8D,KAAKtF,MAC/BA,KAAK4B,aAAe5B,KAAK4B,aAAa0D,KAAKtF,MAE3CA,KAAKI,MAAMmF,wBAAwBC,QAAQC,GAAiBzF,KAAKC,KAAKyF,SAASD,IAC/EzF,KAAKkE,4BAA8BlE,KAAKI,MAAM8D,6BAA+B,CAAA,CACjF,EAnBAD,EADEpE,EACYQ,OAAOsF,EAAWC,QAEhC3B,EAHEpE,EAGegG,eAAeA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useSRPanelForGiftcardErrors.js","sources":["../../../../../src/components/Giftcard/components/useSRPanelForGiftcardErrors.ts"],"sourcesContent":["import { useEffect, useState } from 'preact/hooks';\nimport { SetSRMessagesReturnObject } from '../../../core/Errors/types';\nimport useSRPanelContext from '../../../core/Errors/useSRPanelContext';\nimport { usePrevious } from '../../../utils/hookUtils';\nimport { ERROR_ACTION_BLUR_SCENARIO, ERROR_ACTION_FOCUS_FIELD } from '../../../core/Errors/constants';\nimport { getArrayDifferences } from '../../../utils/arrayUtils';\nimport { SetSRMessagesReturnFn } from '../../../core/Errors/SRPanelProvider';\nimport SecuredFieldsProvider from '../../internal/SecuredFields/SFP/SecuredFieldsProvider';\n\n/**\n * Interface for transformed error objects returned from mapErrorsToValidationRuleResult\n */\ninterface TransformedError {\n isValid: boolean;\n errorMessage: string;\n errorI18n: string;\n error: string;\n rootNode: HTMLElement;\n}\n\n/**\n * Interface for errors object with transformed error entries\n */\ninterface TransformedErrorsObj {\n [key: string]: TransformedError | null;\n}\n\n/**\n * Props interface for the error handling hook\n */\ninterface UseSRPanelForGiftcardErrorsProps {\n errors: TransformedErrorsObj;\n isValidating: boolean;\n sfp: SecuredFieldsProvider;\n}\n\n/**\n * Interface for sorted error objects used for comparison\n */\ninterface SortedErrorObject {\n field: string;\n errorMessage: string;\n}\n\n/**\n * Custom hook for handling gift card component errors and screen reader announcements\n *\n * This hook manages both visual and screen reader error announcements for the gift card component,\n * handling both blur-based validation errors and form-wide validation errors.\n */\nconst useSRPanelForGiftcardErrors = ({ errors, isValidating, sfp }: UseSRPanelForGiftcardErrorsProps) => {\n // Track sorted list of errors for comparison with previous state\n const [sortedErrorList, setSortedErrorList] = useState<SortedErrorObject[]>(null);\n // Track previous error list for detecting changes\n const previousSortedErrors = usePrevious(sortedErrorList);\n\n // Get SRPanel context for managing screen reader messages\n const { setSRMessagesFromObjects, setSRMessagesFromStrings, clearSRPanel, shouldMoveFocusSR } = useSRPanelContext();\n\n // Fixed layout array defining the order of fields for error sorting\n // Assume fields in this order, and adds encryptedExpiryDate for MealVoucher, this is ignored in giftcard\n const layout = ['encryptedCardNumber', 'encryptedExpiryDate', 'encryptedSecurityCode'];\n\n useEffect(() => {\n try {\n // Create a partial function for setting SR messages with fixed configuration\n const setMessages: SetSRMessagesReturnFn = setSRMessagesFromObjects?.({});\n // Set messages with current errors and layout\n\n // Unlike Card SR Panel, isValidating is a boolean\n const srPanelResp: SetSRMessagesReturnObject = setMessages?.({\n errors,\n isValidating,\n layout\n });\n\n // Store the sorted list of errors for comparison\n const currentErrorsSortedByLayout = srPanelResp?.currentErrorsSortedByLayout;\n setSortedErrorList(currentErrorsSortedByLayout);\n\n // Handle different error scenarios based on the action type\n switch (srPanelResp?.action) {\n case ERROR_ACTION_FOCUS_FIELD:\n // When a field needs to be focused due to validation error\n if (shouldMoveFocusSR) {\n sfp?.setFocusOn(srPanelResp?.fieldToFocus);\n }\n // Remove 'showValidation' mode - allowing time for collation of all the fields in error whilst it is 'showValidation' mode (some errors come in a second render pass)\n setTimeout(() => {\n if (typeof isValidating === 'boolean') {\n isValidating = false;\n }\n }, 300);\n break;\n\n case ERROR_ACTION_BLUR_SCENARIO: {\n // Handle blur-based validation errors\n const difference = getArrayDifferences(currentErrorsSortedByLayout, previousSortedErrors, 'field');\n const latestErrorMsg = difference?.[0];\n\n if (latestErrorMsg) {\n // Only announce blur-based errors to screen reader\n const isBlurBasedError = true;\n const latestSRError = isBlurBasedError ? latestErrorMsg.errorMessage : null;\n setSRMessagesFromStrings(latestSRError);\n } else {\n // Clear SR panel if there are no more errors\n clearSRPanel();\n }\n break;\n }\n }\n } catch (_) {\n // Fail silently - we don't want to break the component if SRPanel fails\n }\n }, [errors]);\n};\n\n// Export all interfaces and the hook\nexport type { TransformedError, TransformedErrorsObj };\n\nexport { useSRPanelForGiftcardErrors };\n"],"names":["useSRPanelForGiftcardErrors","errors","isValidating","sfp","sortedErrorList","setSortedErrorList","useState","previousSortedErrors","usePrevious","setSRMessagesFromObjects","setSRMessagesFromStrings","clearSRPanel","shouldMoveFocusSR","useSRPanelContext","layout","useEffect","setMessages","srPanelResp","currentErrorsSortedByLayout","action","ERROR_ACTION_FOCUS_FIELD","setFocusOn","fieldToFocus","setTimeout","ERROR_ACTION_BLUR_SCENARIO","difference","getArrayDifferences","latestErrorMsg","latestSRError","errorMessage","_"],"mappings":"0XAkDA,MAAMA,EAA8B,EAAGC,SAAQC,eAAcC,UAEzD,MAAOC,EAAiBC,GAAsBC,EAA8B,MAEtEC,EAAuBC,EAAYJ,IAGnCK,yBAAEA,EAAwBC,yBAAEA,EAAwBC,aAAEA,EAAYC,kBAAEA,GAAsBC,IAI1FC,EAAS,CAAC,sBAAuB,sBAAuB,yBAE9DC,EAAU,KACN,IAEI,MAAMC,EAAqCP,IAA2B,IAIhEQ,EAAyCD,IAAc,CACzDf,SACAC,eACAY,WAIEI,EAA8BD,GAAaC,4BAIjD,OAHAb,EAAmBa,GAGXD,GAAaE,QACjB,KAAKC,EAEGR,GACAT,GAAKkB,WAAWJ,GAAaK,cAGjCC,WAAW,KACqB,kBAAjBrB,IACPA,GAAe,IAEpB,KACH,MAEJ,KAAKsB,EAA4B,CAE7B,MAAMC,EAAaC,EAAoBR,EAA6BX,EAAsB,SACpFoB,EAAiBF,IAAa,GAEpC,GAAIE,EAAgB,CAEhB,MACMC,GADmB,EACgBD,EAAeE,aAAe,KACvEnB,EAAyBkB,
|
|
1
|
+
{"version":3,"file":"useSRPanelForGiftcardErrors.js","sources":["../../../../../src/components/Giftcard/components/useSRPanelForGiftcardErrors.ts"],"sourcesContent":["import { useEffect, useState } from 'preact/hooks';\nimport { SetSRMessagesReturnObject } from '../../../core/Errors/types';\nimport useSRPanelContext from '../../../core/Errors/useSRPanelContext';\nimport { usePrevious } from '../../../utils/hookUtils';\nimport { ERROR_ACTION_BLUR_SCENARIO, ERROR_ACTION_FOCUS_FIELD } from '../../../core/Errors/constants';\nimport { getArrayDifferences } from '../../../utils/arrayUtils';\nimport { SetSRMessagesReturnFn } from '../../../core/Errors/SRPanelProvider';\nimport SecuredFieldsProvider from '../../internal/SecuredFields/SFP/SecuredFieldsProvider';\n\n/**\n * Interface for transformed error objects returned from mapErrorsToValidationRuleResult\n */\ninterface TransformedError {\n isValid: boolean;\n errorMessage: string;\n errorI18n: string;\n error: string;\n rootNode: HTMLElement;\n}\n\n/**\n * Interface for errors object with transformed error entries\n */\ninterface TransformedErrorsObj {\n [key: string]: TransformedError | null;\n}\n\n/**\n * Props interface for the error handling hook\n */\ninterface UseSRPanelForGiftcardErrorsProps {\n errors: TransformedErrorsObj;\n isValidating: boolean;\n sfp: SecuredFieldsProvider;\n}\n\n/**\n * Interface for sorted error objects used for comparison\n */\ninterface SortedErrorObject {\n field: string;\n errorMessage: string;\n}\n\n/**\n * Custom hook for handling gift card component errors and screen reader announcements\n *\n * This hook manages both visual and screen reader error announcements for the gift card component,\n * handling both blur-based validation errors and form-wide validation errors.\n */\nconst useSRPanelForGiftcardErrors = ({ errors, isValidating, sfp }: UseSRPanelForGiftcardErrorsProps) => {\n // Track sorted list of errors for comparison with previous state\n const [sortedErrorList, setSortedErrorList] = useState<SortedErrorObject[]>(null);\n // Track previous error list for detecting changes\n const previousSortedErrors = usePrevious(sortedErrorList);\n\n // Get SRPanel context for managing screen reader messages\n const { setSRMessagesFromObjects, setSRMessagesFromStrings, clearSRPanel, shouldMoveFocusSR } = useSRPanelContext();\n\n // Fixed layout array defining the order of fields for error sorting\n // Assume fields in this order, and adds encryptedExpiryDate for MealVoucher, this is ignored in giftcard\n const layout = ['encryptedCardNumber', 'encryptedExpiryDate', 'encryptedSecurityCode'];\n\n useEffect(() => {\n try {\n // Create a partial function for setting SR messages with fixed configuration\n const setMessages: SetSRMessagesReturnFn = setSRMessagesFromObjects?.({});\n // Set messages with current errors and layout\n\n // Unlike Card SR Panel, isValidating is a boolean\n const srPanelResp: SetSRMessagesReturnObject = setMessages?.({\n errors,\n isValidating,\n layout\n });\n\n // Store the sorted list of errors for comparison\n const currentErrorsSortedByLayout = srPanelResp?.currentErrorsSortedByLayout;\n setSortedErrorList(currentErrorsSortedByLayout);\n\n // Handle different error scenarios based on the action type\n switch (srPanelResp?.action) {\n case ERROR_ACTION_FOCUS_FIELD:\n // When a field needs to be focused due to validation error\n if (shouldMoveFocusSR) {\n sfp?.setFocusOn(srPanelResp?.fieldToFocus);\n }\n // Remove 'showValidation' mode - allowing time for collation of all the fields in error whilst it is 'showValidation' mode (some errors come in a second render pass)\n setTimeout(() => {\n if (typeof isValidating === 'boolean') {\n isValidating = false;\n }\n }, 300);\n break;\n\n case ERROR_ACTION_BLUR_SCENARIO: {\n // Handle blur-based validation errors\n const difference = getArrayDifferences(currentErrorsSortedByLayout, previousSortedErrors, 'field');\n const latestErrorMsg = difference?.[0];\n\n if (latestErrorMsg) {\n // Only announce blur-based errors to screen reader\n const isBlurBasedError = true;\n const latestSRError = isBlurBasedError ? latestErrorMsg.errorMessage : null;\n setSRMessagesFromStrings(latestSRError);\n } else {\n // Clear SR panel if there are no more errors\n clearSRPanel();\n }\n break;\n }\n }\n } catch (_) {\n // Fail silently - we don't want to break the component if SRPanel fails\n }\n }, [errors]);\n};\n\n// Export all interfaces and the hook\nexport type { TransformedError, TransformedErrorsObj };\n\nexport { useSRPanelForGiftcardErrors };\n"],"names":["useSRPanelForGiftcardErrors","errors","isValidating","sfp","sortedErrorList","setSortedErrorList","useState","previousSortedErrors","usePrevious","setSRMessagesFromObjects","setSRMessagesFromStrings","clearSRPanel","shouldMoveFocusSR","useSRPanelContext","layout","useEffect","setMessages","srPanelResp","currentErrorsSortedByLayout","action","ERROR_ACTION_FOCUS_FIELD","setFocusOn","fieldToFocus","setTimeout","ERROR_ACTION_BLUR_SCENARIO","difference","getArrayDifferences","latestErrorMsg","latestSRError","errorMessage","_"],"mappings":"0XAkDA,MAAMA,EAA8B,EAAGC,SAAQC,eAAcC,UAEzD,MAAOC,EAAiBC,GAAsBC,EAA8B,MAEtEC,EAAuBC,EAAYJ,IAGnCK,yBAAEA,EAAwBC,yBAAEA,EAAwBC,aAAEA,EAAYC,kBAAEA,GAAsBC,IAI1FC,EAAS,CAAC,sBAAuB,sBAAuB,yBAE9DC,EAAU,KACN,IAEI,MAAMC,EAAqCP,IAA2B,IAIhEQ,EAAyCD,IAAc,CACzDf,SACAC,eACAY,WAIEI,EAA8BD,GAAaC,4BAIjD,OAHAb,EAAmBa,GAGXD,GAAaE,QACjB,KAAKC,EAEGR,GACAT,GAAKkB,WAAWJ,GAAaK,cAGjCC,WAAW,KACqB,kBAAjBrB,IACPA,GAAe,IAEpB,KACH,MAEJ,KAAKsB,EAA4B,CAE7B,MAAMC,EAAaC,EAAoBR,EAA6BX,EAAsB,SACpFoB,EAAiBF,IAAa,GAEpC,GAAIE,EAAgB,CAEhB,MACMC,GADmB,EACgBD,EAAeE,aAAe,KACvEnB,EAAyBkB,EAC7B,MAEIjB,IAEJ,KACJ,EAER,CAAE,MAAOmB,GAET,GACD,CAAC7B"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createElement as t}from"../../external/preact/dist/preact.js";import{CoreProvider as e}from"../../core/Context/CoreProvider.js";import{TxVariants as s}from"../tx-variants.js";import{UIElement as
|
|
1
|
+
import{createElement as t}from"../../external/preact/dist/preact.js";import{CoreProvider as e}from"../../core/Context/CoreProvider.js";import{TxVariants as s}from"../tx-variants.js";import{UIElement as n}from"../internal/UIElement/UIElement.js";import i from"../../core/Errors/SRPanelProvider.js";import r from"../internal/RedirectButton/RedirectButton.js";import o,{ERROR as a}from"../../core/Errors/AdyenCheckoutError.js";import{PasskeyService as p}from"./services/PasskeyService.js";import{authorizeEnrollment as d}from"./services/authorizeEnrollment.js";import{authorizePayment as h}from"./services/authorizePayment.js";import l from"./components/StoredPayment/StoredPayment.js";import c from"./components/Enrollment/Enrollment.js";function m(t,e,s){return e in t?Object.defineProperty(t,e,{value:s,enumerable:!0,configurable:!0,writable:!0}):t[e]=s,t}class y extends n{get isValid(){return!(this.props._isAdyenHosted&&!this.props.storedPaymentMethodId)||!!this.state?.isValid}get additionalInfo(){return this.props.storedPaymentMethodId?this.props.i18n.get("paybybankpix.storedPayment.additionalLabel",{values:{receiver:this.props?.payByBankPixDetails?.receiver}}):""}get icon(){return this.props.storedPaymentMethodId?this.resources.getImage({parentFolder:`${y.type}/`})(this.props?.payByBankPixDetails?.ispb):super.icon}async isAvailable(){const t=await this.passkeyService.getWebAuthnUnsupportedReason();if(t)return Promise.reject(new o(a,t));if(!this.props._isAdyenHosted)return Promise.resolve();try{if(await this.passkeyService.initialize(),this.props.storedPaymentMethodId){return await this.passkeyService.canUseStoredCredential()?Promise.resolve():Promise.reject(new o("ERROR","The stored payment method is not available on this device"))}return Promise.resolve()}catch(t){return Promise.reject(t instanceof Error?t?.message:"Unknown error")}}handleAction(t,e={}){const s=this.core.createFromAction(t,{...this.elementRef.props,...e,onAdditionalDetails:this.handleAdditionalDetails});return s?(this.unmount(),s.isAvailable().then(()=>{s.mount(this._node)}),s):null}formatData(){if(!this.props._isAdyenHosted)return{paymentMethod:{type:s.paybybank_pix}};const t=null==this.props.storedPaymentMethodId;return{paymentMethod:{type:s.paybybank_pix,...this.state.data},...t?{storePaymentMethod:!0}:{}}}render(){return this.props._isAdyenHosted?t(e,{i18n:this.props.i18n,loadingContext:this.props.loadingContext,resources:this.resources},t(i,{srPanel:this.props.modules.srPanel},null!=this.props.storedPaymentMethodId?t(l,{txVariant:y.type,type:this.props.type,clientKey:this.props.clientKey,amount:this.props.amount,enrollmentId:this.props.paymentMethodData?.enrollmentId,initiationId:this.props.paymentMethodData?.initiationId,setComponentRef:this.setComponentRef,onPay:this.payWithStoredPayment,onAuthorize:this.authorizePayment}):t(c,{onError:this.handleError,txVariant:y.type,type:this.props.type,clientKey:this.props.clientKey,enrollmentId:this.props.paymentMethodData?.enrollmentId,countdownTime:this.props.countdownTime,onEnroll:this.authorizeEnrollment,issuers:this.props.issuers,payButton:this.payButton,onChange:this.onIssuerSelected,onSubmitAnalytics:this.submitAnalytics,setComponentRef:this.setComponentRef}))):t(e,{i18n:this.props.i18n,loadingContext:this.props.loadingContext,resources:this.resources},t(i,{srPanel:this.props.modules.srPanel},t(r,{showPayButton:this.props.showPayButton,name:this.displayName,label:this.props.i18n.get("paybybankpix.redirectBtn.label"),amount:this.props.amount,payButton:this.payButton,onSubmit:this.submit,ref:t=>{this.componentRef=t}})))}constructor(t,e){super(t,e),m(this,"passkeyService",void 0),m(this,"onIssuerSelected",async t=>{try{const{data:e={}}=t;if(!e.issuer)return;const{deviceId:s,...n}=await this.passkeyService.captureRiskSignalsEnrollment();this.setState({...t,data:{...e,riskSignals:n,deviceId:s}})}catch(t){const e=t instanceof Error?t.message:"Unknown error in the onIssuerSelected";this.handleError(t instanceof o?t:new o(a,e))}}),m(this,"authorizeEnrollment",async t=>{try{const e=await this.passkeyService.createCredentialForEnrollment(t),s={enrollmentId:this.props.paymentMethodData?.enrollmentId,fidoAssertion:e},{redirectResult:n}=await d({enrollment:s,clientKey:this.props.clientKey,loadingContext:this.props.loadingContext});this.handleAdditionalDetails({data:{details:{redirectResult:n}}})}catch(t){const e=t instanceof Error?t.message:"Unknown error in the authorizeEnrollment";this.handleError(t instanceof o?t:new o(a,e))}}),m(this,"payWithStoredPayment",async()=>{try{const{deviceId:t,...e}=await this.passkeyService.captureRiskSignalsAuthentication();this.state={...this.state,data:{storedPaymentMethodId:this.props.storedPaymentMethodId,riskSignals:e,deviceId:t}},super.submit()}catch(t){const e=t instanceof Error?t.message:"Unknown error in the payWithStoredPayment";this.handleError(t instanceof o?t:new o(a,e))}}),m(this,"authorizePayment",async t=>{try{const e=await this.passkeyService.authenticateWithCredential(t),s={enrollmentId:this.props.paymentMethodData?.enrollmentId,initiationId:this.props.paymentMethodData?.initiationId,fidoAssertion:e},{redirectResult:n}=await h({payment:s,clientKey:this.props.clientKey,loadingContext:this.props.loadingContext});this.handleAdditionalDetails({data:{details:{redirectResult:n}}})}catch(t){const e=t instanceof Error?t.message:"Unknown error in the authorizePayment";this.handleError(t instanceof o?t:new o(a,e))}});const s=this.props.storedPaymentMethodId?this.props?.payByBankPixDetails?.deviceId:this.props.deviceId;this.passkeyService=new p({environment:this.props.environment,deviceId:s}),this.props._isAdyenHosted&&this.passkeyService.initialize()}}m(y,"type",s.paybybank_pix),m(y,"TIMEOUT_MINUTES",1),m(y,"defaultProps",{showPayButton:!0,_isAdyenHosted:(()=>{try{return new URL(window.location.href).hostname.endsWith(".adyen.com")}catch(t){return!1}})(),countdownTime:y.TIMEOUT_MINUTES});export{y as default};
|
|
2
2
|
//# sourceMappingURL=PayByBankPix.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PayByBankPix.js","sources":["../../../../src/components/PayByBankPix/PayByBankPix.tsx"],"sourcesContent":["import { h } from 'preact';\nimport { CoreProvider } from '../../core/Context/CoreProvider';\nimport { PayByBankPixData, PayByBankPixConfiguration } from './types';\nimport { TxVariants } from '../tx-variants';\nimport UIElement from '../internal/UIElement';\nimport SRPanelProvider from '../../core/Errors/SRPanelProvider';\nimport RedirectButton from '../internal/RedirectButton';\nimport AdyenCheckoutError, { ERROR } from '../../core/Errors/AdyenCheckoutError';\nimport { PasskeyService } from './services/PasskeyService';\nimport { authorizeEnrollment } from './services/authorizeEnrollment';\nimport { authorizePayment } from './services/authorizePayment';\nimport StoredPayment from './components/StoredPayment';\nimport Enrollment from './components/Enrollment';\nimport { PaymentAction } from '../../types/global-types';\nimport type { ICore } from '../../core/types';\n\nconst isAdyenHosted = () => {\n try {\n const currentUrl = new URL(window.location.href);\n return currentUrl.hostname.endsWith('.adyen.com');\n } catch (e) {\n // SSR, or it fails to parse the full url\n return false;\n }\n};\nclass PayByBankPixElement extends UIElement<PayByBankPixConfiguration> {\n public static readonly type = TxVariants.paybybank_pix;\n private static readonly TIMEOUT_MINUTES = 1;\n private readonly passkeyService: PasskeyService;\n\n public static readonly defaultProps: PayByBankPixConfiguration = {\n showPayButton: true,\n _isAdyenHosted: isAdyenHosted(),\n countdownTime: PayByBankPixElement.TIMEOUT_MINUTES\n };\n\n constructor(checkout: ICore, props?: PayByBankPixConfiguration) {\n super(checkout, props);\n const deviceId = this.props.storedPaymentMethodId ? this.props?.payByBankPixDetails?.deviceId : this.props.deviceId;\n this.passkeyService = new PasskeyService({ environment: this.props.environment, deviceId });\n if (this.props._isAdyenHosted) {\n void this.passkeyService.initialize();\n }\n }\n\n get isValid(): boolean {\n // Always true for non-hosted page or stored payment\n if (!this.props._isAdyenHosted || this.props.storedPaymentMethodId) {\n return true;\n }\n return !!this.state?.isValid;\n }\n\n /**\n * Display in the drop-in\n */\n get additionalInfo() {\n return this.props.storedPaymentMethodId\n ? this.props.i18n.get('paybybankpix.storedPayment.additionalLabel', { values: { receiver: this.props?.payByBankPixDetails?.receiver } })\n : '';\n }\n\n /**\n * Display in the drop-in\n */\n public override get icon() {\n return this.props.storedPaymentMethodId\n ? this.resources.getImage({ parentFolder: `${PayByBankPixElement.type}/` })(this.props?.payByBankPixDetails?.ispb)\n : super.icon;\n }\n\n /**\n * Method used to let the merchant know if the shopper's device supports WebAuthn APIs: https://featuredetect.passkeys.dev/\n */\n public override async isAvailable(): Promise<void> {\n const unsupportedReason = await this.passkeyService.getWebAuthnUnsupportedReason();\n if (unsupportedReason) {\n return Promise.reject(new AdyenCheckoutError(ERROR, unsupportedReason));\n }\n if (!this.props._isAdyenHosted) {\n return Promise.resolve();\n }\n\n // Load passkey sdk on the hosted page\n try {\n await this.passkeyService.initialize();\n\n if (this.props.storedPaymentMethodId) {\n // If the provided deviceId from the server does not match the localstorage deviceId, do not render the stored payment component.\n const shouldShowStoredPaymentMethod = await this.passkeyService.canUseStoredCredential();\n return shouldShowStoredPaymentMethod\n ? Promise.resolve()\n : Promise.reject(new AdyenCheckoutError('ERROR', 'The stored payment method is not available on this device'));\n }\n\n return Promise.resolve();\n } catch (error) {\n return Promise.reject(error instanceof Error ? error?.message : 'Unknown error');\n }\n }\n\n /**\n * Make sure the await action UIElement is available before mounting\n */\n public override handleAction(action: PaymentAction, props: {} = {}): UIElement | null {\n const paymentAction = this.core.createFromAction(action, {\n ...this.elementRef.props,\n ...props,\n onAdditionalDetails: this.handleAdditionalDetails\n });\n if (paymentAction) {\n this.unmount();\n void paymentAction.isAvailable().then(() => {\n paymentAction.mount(this._node);\n });\n return paymentAction;\n }\n\n return null;\n }\n\n formatData(): PayByBankPixData {\n if (!this.props._isAdyenHosted) {\n return {\n paymentMethod: { type: TxVariants.paybybank_pix }\n };\n }\n\n const isEnrollment = this.props.storedPaymentMethodId == null;\n return {\n paymentMethod: { type: TxVariants.paybybank_pix, ...this.state.data },\n // Always store the payment method for the enrollment flow.\n ...(isEnrollment ? { storePaymentMethod: true } : {})\n };\n }\n\n /**\n * There are 3 endpoints (stages) we need to call for the enrollment flow.\n * The first one is the regular payments call on issuer selection - we indicate to store the payment token for the selected issuer.\n * The second one is to poll the enrollment eligibility - we poll the server to get the enrollment challenge in the `getEnrollmentStatus` function.\n * The third one is in the `authorizeEnrollment` function - we create passkeys and authorize the enrollment with shopper's passkey.\n */\n private readonly onIssuerSelected = async payload => {\n try {\n const { data = {} } = payload;\n if (!data.issuer) {\n return;\n }\n\n const { deviceId, ...riskSignals } = await this.passkeyService.captureRiskSignalsEnrollment();\n this.setState({ ...payload, data: { ...data, riskSignals, deviceId } });\n } catch (error) {\n const errorMsg = error instanceof Error ? error.message : 'Unknown error in the onIssuerSelected';\n this.handleError(error instanceof AdyenCheckoutError ? error : new AdyenCheckoutError(ERROR, errorMsg));\n }\n };\n\n private readonly authorizeEnrollment = async (registrationOptions: string): Promise<void> => {\n try {\n const fidoAssertion = await this.passkeyService.createCredentialForEnrollment(registrationOptions); // Create passkey and trigger biometrics\n const enrollment = { enrollmentId: this.props.paymentMethodData?.enrollmentId, fidoAssertion };\n const { redirectResult } = await authorizeEnrollment({\n enrollment,\n clientKey: this.props.clientKey,\n loadingContext: this.props.loadingContext\n });\n // Make paymentDetails call to finalize the enrollment.\n this.handleAdditionalDetails({ data: { details: { redirectResult } } });\n } catch (error) {\n const errorMsg = error instanceof Error ? error.message : 'Unknown error in the authorizeEnrollment';\n this.handleError(error instanceof AdyenCheckoutError ? error : new AdyenCheckoutError(ERROR, errorMsg));\n }\n };\n\n /**\n * There are 3 endpoints (stages) we need to call for the payment flow.\n * The first one `payWithStoredPayment` is the regular payments call - we attempt to pay with the stored payment token.\n * The second one is to poll the authorization options - we poll the server to get the challenge in the `getAuthorizationStatus` function.\n * The third one is in the `authorizePayment` function - we authorize the payment with shopper's passkey.\n */\n private readonly payWithStoredPayment = async () => {\n try {\n const { deviceId, ...riskSignals } = await this.passkeyService.captureRiskSignalsAuthentication();\n this.state = { ...this.state, ...{ data: { storedPaymentMethodId: this.props.storedPaymentMethodId, riskSignals, deviceId } } };\n super.submit();\n } catch (error) {\n const errorMsg = error instanceof Error ? error.message : 'Unknown error in the payWithStoredPayment';\n this.handleError(error instanceof AdyenCheckoutError ? error : new AdyenCheckoutError(ERROR, errorMsg));\n }\n };\n\n private readonly authorizePayment = async (authenticationOptions: string): Promise<void> => {\n try {\n const fidoAssertion = await this.passkeyService.authenticateWithCredential(authenticationOptions);\n const payment = {\n enrollmentId: this.props.paymentMethodData?.enrollmentId,\n initiationId: this.props.paymentMethodData?.initiationId,\n fidoAssertion\n };\n const { redirectResult } = await authorizePayment({\n payment,\n clientKey: this.props.clientKey,\n loadingContext: this.props.loadingContext\n });\n this.handleAdditionalDetails({ data: { details: { redirectResult } } });\n } catch (error) {\n const errorMsg = error instanceof Error ? error.message : 'Unknown error in the authorizePayment';\n this.handleError(error instanceof AdyenCheckoutError ? error : new AdyenCheckoutError(ERROR, errorMsg));\n }\n };\n\n render() {\n // Always render the redirect button on the merchant's page\n if (!this.props._isAdyenHosted) {\n return (\n <CoreProvider i18n={this.props.i18n} loadingContext={this.props.loadingContext} resources={this.resources}>\n <SRPanelProvider srPanel={this.props.modules.srPanel}>\n <RedirectButton\n showPayButton={this.props.showPayButton}\n name={this.displayName}\n label={this.props.i18n.get('paybybankpix.redirectBtn.label')}\n amount={this.props.amount}\n payButton={this.payButton}\n onSubmit={this.submit}\n ref={ref => {\n this.componentRef = ref;\n }}\n />\n </SRPanelProvider>\n </CoreProvider>\n );\n }\n\n return (\n <CoreProvider i18n={this.props.i18n} loadingContext={this.props.loadingContext} resources={this.resources}>\n <SRPanelProvider srPanel={this.props.modules.srPanel}>\n {this.props.storedPaymentMethodId != null ? (\n <StoredPayment\n txVariant={PayByBankPixElement.type}\n type={this.props.type}\n clientKey={this.props.clientKey}\n amount={this.props.amount}\n issuer={this.props?.payByBankPixDetails?.ispb}\n receiver={this.props?.payByBankPixDetails?.receiver}\n enrollmentId={this.props.paymentMethodData?.enrollmentId}\n initiationId={this.props.paymentMethodData?.initiationId}\n setComponentRef={this.setComponentRef}\n onPay={this.payWithStoredPayment}\n onAuthorize={this.authorizePayment}\n />\n ) : (\n <Enrollment\n onError={this.handleError}\n txVariant={PayByBankPixElement.type}\n // Await\n type={this.props.type}\n clientKey={this.props.clientKey}\n enrollmentId={this.props.paymentMethodData?.enrollmentId}\n countdownTime={this.props.countdownTime}\n onEnroll={this.authorizeEnrollment}\n // Issuer List\n issuers={this.props.issuers}\n payButton={this.payButton}\n onChange={this.onIssuerSelected}\n onSubmitAnalytics={this.submitAnalytics}\n setComponentRef={this.setComponentRef}\n />\n )}\n </SRPanelProvider>\n </CoreProvider>\n );\n }\n}\n//\nexport default PayByBankPixElement;\n"],"names":["PayByBankPixElement","UIElement","isValid","this","props","_isAdyenHosted","storedPaymentMethodId","state","additionalInfo","i18n","get","values","receiver","payByBankPixDetails","icon","resources","getImage","parentFolder","type","ispb","super","isAvailable","unsupportedReason","passkeyService","getWebAuthnUnsupportedReason","Promise","reject","AdyenCheckoutError","ERROR","resolve","initialize","canUseStoredCredential","error","Error","message","handleAction","action","paymentAction","core","createFromAction","elementRef","onAdditionalDetails","handleAdditionalDetails","unmount","then","mount","_node","formatData","paymentMethod","TxVariants","paybybank_pix","isEnrollment","data","storePaymentMethod","render","h","CoreProvider","loadingContext","SRPanelProvider","srPanel","modules","StoredPayment","txVariant","clientKey","amount","issuer","enrollmentId","paymentMethodData","initiationId","setComponentRef","onPay","payWithStoredPayment","onAuthorize","authorizePayment","Enrollment","onError","handleError","countdownTime","onEnroll","authorizeEnrollment","issuers","payButton","onChange","onIssuerSelected","onSubmitAnalytics","submitAnalytics","RedirectButton","showPayButton","name","displayName","label","onSubmit","submit","ref","componentRef","constructor","checkout","_define_property","async","payload","deviceId","riskSignals","captureRiskSignalsEnrollment","setState","errorMsg","registrationOptions","fidoAssertion","createCredentialForEnrollment","enrollment","redirectResult","details","captureRiskSignalsAuthentication","authenticationOptions","authenticateWithCredential","payment","PasskeyService","environment","TIMEOUT_MINUTES","defaultProps","URL","window","location","href","hostname","endsWith","e","isAdyenHosted"],"mappings":"w1BAyBA,MAAMA,UAA4BC,EAoB9B,WAAIC,GAEA,QAAKC,KAAKC,MAAM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eAA0C,CAC7D/B,eAAe,EACflF,eAhBc,MAClB,IAEI,OADmB,IAAIkH,IAAIC,OAAOC,SAASC,MACzBC,SAASC,SAAS,aACxC,CAAE,MAAOC,GAEL,OAAO,CACX,GASoBC,GAChBjD,cAAe7E,EAAoBqH"}
|
|
1
|
+
{"version":3,"file":"PayByBankPix.js","sources":["../../../../src/components/PayByBankPix/PayByBankPix.tsx"],"sourcesContent":["import { h } from 'preact';\nimport { CoreProvider } from '../../core/Context/CoreProvider';\nimport { PayByBankPixData, PayByBankPixConfiguration } from './types';\nimport { TxVariants } from '../tx-variants';\nimport UIElement from '../internal/UIElement';\nimport SRPanelProvider from '../../core/Errors/SRPanelProvider';\nimport RedirectButton from '../internal/RedirectButton';\nimport AdyenCheckoutError, { ERROR } from '../../core/Errors/AdyenCheckoutError';\nimport { PasskeyService } from './services/PasskeyService';\nimport { authorizeEnrollment } from './services/authorizeEnrollment';\nimport { authorizePayment } from './services/authorizePayment';\nimport StoredPayment from './components/StoredPayment';\nimport Enrollment from './components/Enrollment';\nimport { PaymentAction } from '../../types/global-types';\nimport type { ICore } from '../../core/types';\n\nconst isAdyenHosted = () => {\n try {\n const currentUrl = new URL(window.location.href);\n return currentUrl.hostname.endsWith('.adyen.com');\n } catch (e) {\n // SSR, or it fails to parse the full url\n return false;\n }\n};\nclass PayByBankPixElement extends UIElement<PayByBankPixConfiguration> {\n public static readonly type = TxVariants.paybybank_pix;\n private static readonly TIMEOUT_MINUTES = 1;\n private readonly passkeyService: PasskeyService;\n\n public static readonly defaultProps: PayByBankPixConfiguration = {\n showPayButton: true,\n _isAdyenHosted: isAdyenHosted(),\n countdownTime: PayByBankPixElement.TIMEOUT_MINUTES\n };\n\n constructor(checkout: ICore, props?: PayByBankPixConfiguration) {\n super(checkout, props);\n const deviceId = this.props.storedPaymentMethodId ? this.props?.payByBankPixDetails?.deviceId : this.props.deviceId;\n this.passkeyService = new PasskeyService({ environment: this.props.environment, deviceId });\n if (this.props._isAdyenHosted) {\n void this.passkeyService.initialize();\n }\n }\n\n get isValid(): boolean {\n // Always true for non-hosted page or stored payment\n if (!this.props._isAdyenHosted || this.props.storedPaymentMethodId) {\n return true;\n }\n return !!this.state?.isValid;\n }\n\n /**\n * Display in the drop-in\n */\n get additionalInfo() {\n return this.props.storedPaymentMethodId\n ? this.props.i18n.get('paybybankpix.storedPayment.additionalLabel', { values: { receiver: this.props?.payByBankPixDetails?.receiver } })\n : '';\n }\n\n /**\n * Display in the drop-in\n */\n public override get icon() {\n return this.props.storedPaymentMethodId\n ? this.resources.getImage({ parentFolder: `${PayByBankPixElement.type}/` })(this.props?.payByBankPixDetails?.ispb)\n : super.icon;\n }\n\n /**\n * Method used to let the merchant know if the shopper's device supports WebAuthn APIs: https://featuredetect.passkeys.dev/\n */\n public override async isAvailable(): Promise<void> {\n const unsupportedReason = await this.passkeyService.getWebAuthnUnsupportedReason();\n if (unsupportedReason) {\n return Promise.reject(new AdyenCheckoutError(ERROR, unsupportedReason));\n }\n if (!this.props._isAdyenHosted) {\n return Promise.resolve();\n }\n\n // Load passkey sdk on the hosted page\n try {\n await this.passkeyService.initialize();\n\n if (this.props.storedPaymentMethodId) {\n // If the provided deviceId from the server does not match the localstorage deviceId, do not render the stored payment component.\n const shouldShowStoredPaymentMethod = await this.passkeyService.canUseStoredCredential();\n return shouldShowStoredPaymentMethod\n ? Promise.resolve()\n : Promise.reject(new AdyenCheckoutError('ERROR', 'The stored payment method is not available on this device'));\n }\n\n return Promise.resolve();\n } catch (error) {\n return Promise.reject(error instanceof Error ? error?.message : 'Unknown error');\n }\n }\n\n /**\n * Make sure the await action UIElement is available before mounting\n */\n public override handleAction(action: PaymentAction, props: {} = {}): UIElement | null {\n const paymentAction = this.core.createFromAction(action, {\n ...this.elementRef.props,\n ...props,\n onAdditionalDetails: this.handleAdditionalDetails\n });\n if (paymentAction) {\n this.unmount();\n void paymentAction.isAvailable().then(() => {\n paymentAction.mount(this._node);\n });\n return paymentAction;\n }\n\n return null;\n }\n\n formatData(): PayByBankPixData {\n if (!this.props._isAdyenHosted) {\n return {\n paymentMethod: { type: TxVariants.paybybank_pix }\n };\n }\n\n const isEnrollment = this.props.storedPaymentMethodId == null;\n return {\n paymentMethod: { type: TxVariants.paybybank_pix, ...this.state.data },\n // Always store the payment method for the enrollment flow.\n ...(isEnrollment ? { storePaymentMethod: true } : {})\n };\n }\n\n /**\n * There are 3 endpoints (stages) we need to call for the enrollment flow.\n * The first one is the regular payments call on issuer selection - we indicate to store the payment token for the selected issuer.\n * The second one is to poll the enrollment eligibility - we poll the server to get the enrollment challenge in the `getEnrollmentStatus` function.\n * The third one is in the `authorizeEnrollment` function - we create passkeys and authorize the enrollment with shopper's passkey.\n */\n private readonly onIssuerSelected = async payload => {\n try {\n const { data = {} } = payload;\n if (!data.issuer) {\n return;\n }\n\n const { deviceId, ...riskSignals } = await this.passkeyService.captureRiskSignalsEnrollment();\n this.setState({ ...payload, data: { ...data, riskSignals, deviceId } });\n } catch (error) {\n const errorMsg = error instanceof Error ? error.message : 'Unknown error in the onIssuerSelected';\n this.handleError(error instanceof AdyenCheckoutError ? error : new AdyenCheckoutError(ERROR, errorMsg));\n }\n };\n\n private readonly authorizeEnrollment = async (registrationOptions: string): Promise<void> => {\n try {\n const fidoAssertion = await this.passkeyService.createCredentialForEnrollment(registrationOptions); // Create passkey and trigger biometrics\n const enrollment = { enrollmentId: this.props.paymentMethodData?.enrollmentId, fidoAssertion };\n const { redirectResult } = await authorizeEnrollment({\n enrollment,\n clientKey: this.props.clientKey,\n loadingContext: this.props.loadingContext\n });\n // Make paymentDetails call to finalize the enrollment.\n this.handleAdditionalDetails({ data: { details: { redirectResult } } });\n } catch (error) {\n const errorMsg = error instanceof Error ? error.message : 'Unknown error in the authorizeEnrollment';\n this.handleError(error instanceof AdyenCheckoutError ? error : new AdyenCheckoutError(ERROR, errorMsg));\n }\n };\n\n /**\n * There are 3 endpoints (stages) we need to call for the payment flow.\n * The first one `payWithStoredPayment` is the regular payments call - we attempt to pay with the stored payment token.\n * The second one is to poll the authorization options - we poll the server to get the challenge in the `getAuthorizationStatus` function.\n * The third one is in the `authorizePayment` function - we authorize the payment with shopper's passkey.\n */\n private readonly payWithStoredPayment = async () => {\n try {\n const { deviceId, ...riskSignals } = await this.passkeyService.captureRiskSignalsAuthentication();\n this.state = { ...this.state, ...{ data: { storedPaymentMethodId: this.props.storedPaymentMethodId, riskSignals, deviceId } } };\n super.submit();\n } catch (error) {\n const errorMsg = error instanceof Error ? error.message : 'Unknown error in the payWithStoredPayment';\n this.handleError(error instanceof AdyenCheckoutError ? error : new AdyenCheckoutError(ERROR, errorMsg));\n }\n };\n\n private readonly authorizePayment = async (authenticationOptions: string): Promise<void> => {\n try {\n const fidoAssertion = await this.passkeyService.authenticateWithCredential(authenticationOptions);\n const payment = {\n enrollmentId: this.props.paymentMethodData?.enrollmentId,\n initiationId: this.props.paymentMethodData?.initiationId,\n fidoAssertion\n };\n const { redirectResult } = await authorizePayment({\n payment,\n clientKey: this.props.clientKey,\n loadingContext: this.props.loadingContext\n });\n this.handleAdditionalDetails({ data: { details: { redirectResult } } });\n } catch (error) {\n const errorMsg = error instanceof Error ? error.message : 'Unknown error in the authorizePayment';\n this.handleError(error instanceof AdyenCheckoutError ? error : new AdyenCheckoutError(ERROR, errorMsg));\n }\n };\n\n render() {\n // Always render the redirect button on the merchant's page\n if (!this.props._isAdyenHosted) {\n return (\n <CoreProvider i18n={this.props.i18n} loadingContext={this.props.loadingContext} resources={this.resources}>\n <SRPanelProvider srPanel={this.props.modules.srPanel}>\n <RedirectButton\n showPayButton={this.props.showPayButton}\n name={this.displayName}\n label={this.props.i18n.get('paybybankpix.redirectBtn.label')}\n amount={this.props.amount}\n payButton={this.payButton}\n onSubmit={this.submit}\n ref={ref => {\n this.componentRef = ref;\n }}\n />\n </SRPanelProvider>\n </CoreProvider>\n );\n }\n\n return (\n <CoreProvider i18n={this.props.i18n} loadingContext={this.props.loadingContext} resources={this.resources}>\n <SRPanelProvider srPanel={this.props.modules.srPanel}>\n {this.props.storedPaymentMethodId != null ? (\n <StoredPayment\n txVariant={PayByBankPixElement.type}\n type={this.props.type}\n clientKey={this.props.clientKey}\n amount={this.props.amount}\n enrollmentId={this.props.paymentMethodData?.enrollmentId}\n initiationId={this.props.paymentMethodData?.initiationId}\n setComponentRef={this.setComponentRef}\n onPay={this.payWithStoredPayment}\n onAuthorize={this.authorizePayment}\n />\n ) : (\n <Enrollment\n onError={this.handleError}\n txVariant={PayByBankPixElement.type}\n // Await\n type={this.props.type}\n clientKey={this.props.clientKey}\n enrollmentId={this.props.paymentMethodData?.enrollmentId}\n countdownTime={this.props.countdownTime}\n onEnroll={this.authorizeEnrollment}\n // Issuer List\n issuers={this.props.issuers}\n payButton={this.payButton}\n onChange={this.onIssuerSelected}\n onSubmitAnalytics={this.submitAnalytics}\n setComponentRef={this.setComponentRef}\n />\n )}\n </SRPanelProvider>\n </CoreProvider>\n );\n }\n}\n//\nexport default PayByBankPixElement;\n"],"names":["PayByBankPixElement","UIElement","isValid","this","props","_isAdyenHosted","storedPaymentMethodId","state","additionalInfo","i18n","get","values","receiver","payByBankPixDetails","icon","resources","getImage","parentFolder","type","ispb","super","isAvailable","unsupportedReason","passkeyService","getWebAuthnUnsupportedReason","Promise","reject","AdyenCheckoutError","ERROR","resolve","initialize","canUseStoredCredential","error","Error","message","handleAction","action","paymentAction","core","createFromAction","elementRef","onAdditionalDetails","handleAdditionalDetails","unmount","then","mount","_node","formatData","paymentMethod","TxVariants","paybybank_pix","isEnrollment","data","storePaymentMethod","render","h","CoreProvider","loadingContext","SRPanelProvider","srPanel","modules","StoredPayment","txVariant","clientKey","amount","enrollmentId","paymentMethodData","initiationId","setComponentRef","onPay","payWithStoredPayment","onAuthorize","authorizePayment","Enrollment","onError","handleError","countdownTime","onEnroll","authorizeEnrollment","issuers","payButton","onChange","onIssuerSelected","onSubmitAnalytics","submitAnalytics","RedirectButton","showPayButton","name","displayName","label","onSubmit","submit","ref","componentRef","constructor","checkout","_define_property","async","payload","issuer","deviceId","riskSignals","captureRiskSignalsEnrollment","setState","errorMsg","registrationOptions","fidoAssertion","createCredentialForEnrollment","enrollment","redirectResult","details","captureRiskSignalsAuthentication","authenticationOptions","authenticateWithCredential","payment","PasskeyService","environment","TIMEOUT_MINUTES","defaultProps","URL","window","location","href","hostname","endsWith","e","isAdyenHosted"],"mappings":"w1BAyBA,MAAMA,UAA4BC,EAoB9B,WAAIC,GAEA,QAAKC,KAAKC,MAAMC,iBAAkBF,KAAKC,MAAME,0BAGpCH,KAAKI,OAAOL,OACzB,CAKA,kBAAIM,GACA,OAAOL,KAAKC,MAAME,sBACZH,KAAKC,MAAMK,KAAKC,IAAI,6CAA8C,CAAEC,OAAQ,CAAEC,SAAUT,KAAKC,OAAOS,qBAAqBD,YACzH,EACV,CAKA,QAAoBE,GAChB,OAAOX,KAAKC,MAAME,sBACZH,KAAKY,UAAUC,SAAS,CAAEC,aAAc,GAAGjB,EAAoBkB,SAA/Df,CAA0EA,KAAKC,OAAOS,qBAAqBM,MAC3GC,MAAMN,IAChB,CAKA,iBAAsBO,GAClB,MAAMC,QAA0BnB,KAAKoB,eAAeC,+BACpD,GAAIF,EACA,OAAOG,QAAQC,OAAO,IAAIC,EAAmBC,EAAON,IAExD,IAAKnB,KAAKC,MAAMC,eACZ,OAAOoB,QAAQI,UAInB,IAGI,SAFM1B,KAAKoB,eAAeO,aAEtB3B,KAAKC,MAAME,sBAAuB,CAGlC,aAD4CH,KAAKoB,eAAeQ,yBAE1DN,QAAQI,UACRJ,QAAQC,OAAO,IAAIC,EAAmB,QAAS,6DACzD,CAEA,OAAOF,QAAQI,SACnB,CAAE,MAAOG,GACL,OAAOP,QAAQC,OAAOM,aAAiBC,MAAQD,GAAOE,QAAU,gBACpE,CACJ,CAKA,YAAAC,CAA6BC,EAAuBhC,EAAY,IAC5D,MAAMiC,EAAgBlC,KAAKmC,KAAKC,iBAAiBH,EAAQ,IAClDjC,KAAKqC,WAAWpC,SAChBA,EACH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AiB,IAAI4F,EAAe,CAAEC,YAAajH,KAAKC,MAAMgH,YAAahB,aAC5EjG,KAAKC,MAAMC,gBACNF,KAAKoB,eAAeO,YAEjC,EAjBAkE,EADEhG,EACqBkB,OAAO+B,EAAWC,eACzC8C,EAFEhG,EAEsBqH,kBAAkB,GAG1CrB,EALEhG,EAKqBsH,eAA0C,CAC7DhC,eAAe,EACfjF,eAhBc,MAClB,IAEI,OADmB,IAAIkH,IAAIC,OAAOC,SAASC,MACzBC,SAASC,SAAS,aACxC,CAAE,MAAOC,GAEL,OAAO,CACX,GASoBC,GAChBlD,cAAe5E,EAAoBqH"}
|
|
@@ -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
|
|
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";function u(u){const{i18n:y,loadingContext:d}=o(),g=p(),w=e(null),[b,x]=n(null),f=[{name:"open-finance",alt:y.get("paybybankpix.await.logoAlt.openFinance"),src:`${g({parentFolder:`${u.txVariant}/`})("open-finance")}`},{name:"arrow-down",alt:y.get("paybybankpix.await.logoAlt.arrowDown"),src:`${g({imageFolder:"components/"})("arrow_down")}`},{name:"bank",alt:y.get("paybybankpix.await.logoAlt.bank"),src:`${g({imageFolder:"components/"})("bank")}`}],k=e({showValidation:()=>{w?.current?.showValidation()},setStatus:t=>{w?.current?.setStatus(t)}});return a(()=>{u.setComponentRef(k.current)},[u.setComponentRef]),a(()=>{b&&u.onEnroll(b)},[b]),t("div",{className:"adyen-checkout-pix-enrollment"},(t=>"await"===t.type)(u)?t(m,{logos:f,type:u.txVariant,countdownTime:u.countdownTime,clientKey:u.clientKey,onError:u.onError,awaitText:y.get("paybybankpix.await.waitForConfirmation"),instructions:y.get("paybybankpix.await.timeToPay",{values:{numberOfMin:u.countdownTime}}),pollStatus:async()=>{if(b)return;const{enrollmentId:t,clientKey:e}=u,n=await r({enrollmentId:t,clientKey:e,loadingContext:d});return n.registrationOptions&&x(n.registrationOptions),n},endSlot:()=>t("span",null,y.get("paybybankpix.await.withOpenFinance"))}):t("div",{className:"adyen-checkout-pix-enrollment-issuer-list"},t(l,{txVariant:u.txVariant}),t(i,{items:s({issuers:u.issuers,txVariant:u.txVariant}),selectFieldLabel:y.get("paybybankpix.issuerList.selectField.label"),onSubmitAnalytics:u.onSubmitAnalytics,onChange:u.onChange,payButton:u.payButton,showPayButton:!0,ref:w}),t("span",{className:"adyen-checkout-disclaimer__label"},t(c,{message:y.get("paybybankpix.issuerList.disclaimer"),urls:["https://www.adyen.com/pt_BR/legal/termo-de-consentimento-br"]}))))}export{u 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';\n\
|
|
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';\n\nconst TERMS_CONDITIONS_URL = 'https://www.adyen.com/pt_BR/legal/termo-de-consentimento-br';\n\nfunction Enrollment(props: 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: `${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 ref={issuerListRef}\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","LabelOnlyDisclaimerMessage","message","urls"],"mappings":"ypBAgBA,SAASA,EAAWC,GAChB,MAAMC,KAAEA,EAAIC,eAAEA,GAAmBC,IAC3BC,EAAWC,IACXC,EAAgBC,EAA4B,OAC3CC,EAAqBC,GAA0BC,EAAiB,MACjEC,EAAQ,CACV,CACIC,KAAM,eACNC,IAAKZ,EAAKa,IAAI,0CACdC,IAAK,GAAGX,EAAS,CAAEY,aAAc,GAAGhB,EAAMiB,cAAlCb,CAAkD,mBAE9D,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,OAVAC,EAAU,KACNxB,EAAMyB,gBAAgBN,EAAKE,UAC5B,CAACrB,EAAMyB,kBAEVD,EAAU,KACFhB,GACAR,EAAM0B,SAASlB,IAEpB,CAACA,IAGAmB,EAACC,MAAAA,CAAIC,UAAW,iCAdJ,CAAC7B,GAA+D,UAAfA,EAAM8B,KAe9DC,CAAQ/B,GACL2B,EAACK,EAAAA,CACGrB,MAAOA,EACPmB,KAAM9B,EAAMiB,UACZgB,cAAejC,EAAMiC,cACrBC,UAAWlC,EAAMkC,UACjBC,QAASnC,EAAMmC,QACfC,UAAWnC,EAAKa,IAAI,0CACpBuB,aAAcpC,EAAKa,IAAI,+BAAgC,CACnDwB,OAAQ,CAAEC,YAAavC,EAAMiC,iBAEjCO,WArCGC,UACf,GAAIjC,EAAqB,OAEzB,MAAMkC,aAAEA,EAAYR,UAAEA,GAAclC,EAC9B2C,QAAiBC,EAAoB,CAAEF,eAAcR,YAAWhC,mBAItE,OAHIyC,EAASnC,qBACTC,EAAuBkC,EAASnC,qBAE7BmC,GA8BKE,QA1BK,IAAMlB,EAACmB,OAAAA,KAAM7C,EAAKa,IAAI,yCA6B/Ba,EAACC,MAAAA,CAAIC,UAAU,6CACXF,EAACoB,EAAAA,CAAuB9B,UAAWjB,EAAMiB,YACzCU,EAACqB,EAAAA,CACGC,MAAOC,EAAkB,CAAEC,QAASnD,EAAMmD,QAASlC,UAAWjB,EAAMiB,YACpEmC,iBAAkBnD,EAAKa,IAAI,6CAC3BuC,kBAAmBrD,EAAMqD,kBACzBC,SAAUtD,EAAMsD,SAChBC,UAAWvD,EAAMuD,UACjBC,eAAe,EACfC,IAAKnD,IAETqB,EAACmB,OAAAA,CAAKjB,UAAU,oCACZF,EAAC+B,EAAAA,CAA2BC,QAAS1D,EAAKa,IAAI,sCAAuC8C,KAAM,CAlFtF,mEAwF7B"}
|
package/dist/es/components/PayByBankPix/components/Enrollment/components/IssuerListIntroduction.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createElement as t}from"../../../../../external/preact/dist/preact.js";import{useCoreContext as e}from"../../../../../core/Context/CoreProvider.js";import
|
|
1
|
+
import{createElement as t}from"../../../../../external/preact/dist/preact.js";import{useCoreContext as e}from"../../../../../core/Context/CoreProvider.js";import o from"../../../../../core/Context/useImage.js";const n="open-finance",i="paybybankpix.await.logoAlt.openFinance";function a({txVariant:a}){const{i18n:r}=e(),s=o();return t("div",{className:"adyen-checkout-issuer-list-introduction"},t("div",{className:"adyen-checkout-issuer-list-introduction-logo-container"},t("img",{src:s({parentFolder:`${a}/`})(n),alt:r.get(i),className:"adyen-checkout-issuer-list-introduction-logo-container__logo"}),t("p",{className:"adyen-checkout-issuer-list-introduction-logo-container__title"},r.get("paybybankpix.issuerList.introduction.logo.content"))))}export{a as default};
|
|
2
2
|
//# sourceMappingURL=IssuerListIntroduction.js.map
|