@adyen/adyen-web 6.34.1 → 6.35.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/adyen.css +2 -3
- 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 +39 -26
- package/dist/es/adyen.css +2 -3
- package/dist/es/adyen.css.map +1 -1
- package/dist/es/components/Card/components/CardInput/CardInput.js +1 -1
- package/dist/es/components/Card/components/CardInput/CardInput.js.map +1 -1
- package/dist/es/components/Card/components/CardInput/components/BrandIcon.js +1 -1
- package/dist/es/components/Card/components/CardInput/components/BrandIcon.js.map +1 -1
- package/dist/es/components/Card/components/CardInput/components/CardFields.js +1 -1
- package/dist/es/components/Card/components/CardInput/components/CardFields.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/CardNumber.js +1 -1
- package/dist/es/components/Card/components/CardInput/components/CardNumber.js.map +1 -1
- package/dist/es/components/Card/components/CardInput/components/DualBrandSelector.js +2 -0
- package/dist/es/components/Card/components/CardInput/components/DualBrandSelector.js.map +1 -0
- package/dist/es/components/Card/components/CardInput/components/DualBrandSelector.module.scss.js +2 -0
- package/dist/es/components/Card/components/CardInput/components/DualBrandSelector.module.scss.js.map +1 -0
- package/dist/es/components/Card/components/CardInput/types.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/Card/constants.js.map +1 -1
- package/dist/es/components/CustomCard/CustomCard.js +1 -1
- package/dist/es/components/CustomCard/CustomCard.js.map +1 -1
- package/dist/es/components/CustomCard/CustomCardInput/CustomCardInput.js +1 -1
- package/dist/es/components/CustomCard/CustomCardInput/CustomCardInput.js.map +1 -1
- package/dist/es/components/Giftcard/components/GiftcardComponent.js +1 -1
- package/dist/es/components/Giftcard/components/GiftcardComponent.js.map +1 -1
- package/dist/es/components/internal/BaseElement/BaseElement.js +1 -1
- package/dist/es/components/internal/BaseElement/BaseElement.js.map +1 -1
- package/dist/es/components/internal/FormFields/Field/Field.js +1 -1
- package/dist/es/components/internal/FormFields/Field/Field.js.map +1 -1
- package/dist/es/components/internal/SecuredFields/SFP/SFPUtils.js +1 -1
- package/dist/es/components/internal/SecuredFields/SFP/SFPUtils.js.map +1 -1
- package/dist/es/components/internal/SecuredFields/SFP/SecuredFieldsProvider.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/lib/CSF/extensions/handleBrandFromBinLookup.js +1 -1
- package/dist/es/components/internal/SecuredFields/lib/CSF/extensions/handleBrandFromBinLookup.js.map +1 -1
- package/dist/es/components/internal/SecuredFields/lib/CSF/partials/processBrand.js +1 -1
- package/dist/es/components/internal/SecuredFields/lib/CSF/partials/processBrand.js.map +1 -1
- package/dist/es/components/internal/SecuredFields/lib/CSF/utils/cardType.js +1 -1
- package/dist/es/components/internal/SecuredFields/lib/CSF/utils/cardType.js.map +1 -1
- package/dist/es/components/internal/SecuredFields/lib/constants.js +1 -1
- package/dist/es/components/internal/SecuredFields/lib/constants.js.map +1 -1
- package/dist/es/core/Analytics/Analytics.js +1 -1
- package/dist/es/core/Analytics/Analytics.js.map +1 -1
- package/dist/es/core/Analytics/AnalyticsService.js.map +1 -1
- package/dist/es/core/Analytics/events/AnalyticsInfoEvent.js +1 -1
- package/dist/es/core/Analytics/events/AnalyticsInfoEvent.js.map +1 -1
- package/dist/es/core/config.js +1 -1
- package/dist/es/core/config.js.map +1 -1
- package/dist/es/index.d.ts +39 -26
- package/dist/es/utils/createSdkData.js +1 -1
- package/dist/es/utils/createSdkData.js.map +1 -1
- package/dist/es-legacy/adyen.css +2 -3
- package/dist/es-legacy/adyen.css.map +1 -1
- package/dist/es-legacy/components/Card/components/CardInput/CardInput.js +1 -1
- package/dist/es-legacy/components/Card/components/CardInput/CardInput.js.map +1 -1
- package/dist/es-legacy/components/Card/components/CardInput/components/BrandIcon.js +1 -1
- package/dist/es-legacy/components/Card/components/CardInput/components/BrandIcon.js.map +1 -1
- package/dist/es-legacy/components/Card/components/CardInput/components/CardFields.js +1 -1
- package/dist/es-legacy/components/Card/components/CardInput/components/CardFields.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/CardNumber.js +1 -1
- package/dist/es-legacy/components/Card/components/CardInput/components/CardNumber.js.map +1 -1
- package/dist/es-legacy/components/Card/components/CardInput/components/DualBrandSelector.js +2 -0
- package/dist/es-legacy/components/Card/components/CardInput/components/DualBrandSelector.js.map +1 -0
- package/dist/es-legacy/components/Card/components/CardInput/components/DualBrandSelector.module.scss.js +2 -0
- package/dist/es-legacy/components/Card/components/CardInput/components/DualBrandSelector.module.scss.js.map +1 -0
- package/dist/es-legacy/components/Card/components/CardInput/types.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/Card/constants.js.map +1 -1
- package/dist/es-legacy/components/CustomCard/CustomCard.js +1 -1
- package/dist/es-legacy/components/CustomCard/CustomCard.js.map +1 -1
- package/dist/es-legacy/components/CustomCard/CustomCardInput/CustomCardInput.js +1 -1
- package/dist/es-legacy/components/CustomCard/CustomCardInput/CustomCardInput.js.map +1 -1
- package/dist/es-legacy/components/Giftcard/components/GiftcardComponent.js +1 -1
- package/dist/es-legacy/components/Giftcard/components/GiftcardComponent.js.map +1 -1
- package/dist/es-legacy/components/internal/BaseElement/BaseElement.js +1 -1
- package/dist/es-legacy/components/internal/BaseElement/BaseElement.js.map +1 -1
- package/dist/es-legacy/components/internal/FormFields/Field/Field.js +1 -1
- package/dist/es-legacy/components/internal/FormFields/Field/Field.js.map +1 -1
- package/dist/es-legacy/components/internal/SecuredFields/SFP/SFPUtils.js +1 -1
- package/dist/es-legacy/components/internal/SecuredFields/SFP/SFPUtils.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/extensions.js +1 -1
- package/dist/es-legacy/components/internal/SecuredFields/binLookup/extensions.js.map +1 -1
- package/dist/es-legacy/components/internal/SecuredFields/lib/CSF/extensions/handleBrandFromBinLookup.js +1 -1
- package/dist/es-legacy/components/internal/SecuredFields/lib/CSF/extensions/handleBrandFromBinLookup.js.map +1 -1
- package/dist/es-legacy/components/internal/SecuredFields/lib/CSF/partials/processBrand.js +1 -1
- package/dist/es-legacy/components/internal/SecuredFields/lib/CSF/partials/processBrand.js.map +1 -1
- package/dist/es-legacy/components/internal/SecuredFields/lib/CSF/utils/cardType.js +1 -1
- package/dist/es-legacy/components/internal/SecuredFields/lib/CSF/utils/cardType.js.map +1 -1
- package/dist/es-legacy/components/internal/SecuredFields/lib/constants.js +1 -1
- package/dist/es-legacy/components/internal/SecuredFields/lib/constants.js.map +1 -1
- package/dist/es-legacy/core/Analytics/Analytics.js +1 -1
- package/dist/es-legacy/core/Analytics/Analytics.js.map +1 -1
- package/dist/es-legacy/core/Analytics/AnalyticsService.js.map +1 -1
- package/dist/es-legacy/core/Analytics/events/AnalyticsInfoEvent.js +1 -1
- package/dist/es-legacy/core/Analytics/events/AnalyticsInfoEvent.js.map +1 -1
- package/dist/es-legacy/core/config.js +1 -1
- package/dist/es-legacy/core/config.js.map +1 -1
- package/dist/es-legacy/utils/createSdkData.js +1 -1
- package/dist/es-legacy/utils/createSdkData.js.map +1 -1
- package/package.json +3 -3
- package/styles/adyen.css +2 -3
- package/dist/es/components/internal/FormFields/RadioGroupExtended/RadioButtonIcon.js +0 -2
- package/dist/es/components/internal/FormFields/RadioGroupExtended/RadioButtonIcon.js.map +0 -1
- package/dist/es/components/internal/FormFields/RadioGroupExtended/RadioGroupExtended.js +0 -2
- package/dist/es/components/internal/FormFields/RadioGroupExtended/RadioGroupExtended.js.map +0 -1
- package/dist/es-legacy/components/internal/FormFields/RadioGroupExtended/RadioButtonIcon.js +0 -2
- package/dist/es-legacy/components/internal/FormFields/RadioGroupExtended/RadioButtonIcon.js.map +0 -1
- package/dist/es-legacy/components/internal/FormFields/RadioGroupExtended/RadioGroupExtended.js +0 -2
- package/dist/es-legacy/components/internal/FormFields/RadioGroupExtended/RadioGroupExtended.js.map +0 -1
|
@@ -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 r,KCP_CARD_NAME_BOTTOM as i,SSN_CARD_NAME_TOP as t,SSN_CARD_NAME_BOTTOM as a,CREDIT_CARD as s,KCP_CARD as l,SSN_CARD as d}from"./layouts.js";import{PARTIAL_ADDRESS_SCHEMA as c}from"../../../internal/Address/constants.js";import{BRAND_READABLE_NAME_MAP as u}from"../../../internal/SecuredFields/lib/constants.js";import m from"../../../../core/Context/useImage.js";import{SF_ErrorCodes as p}from"../../../../core/Errors/constants.js";const C=(e,o)=>o({type:"card"===e?"nocard":e||"nocard",extension:"svg"})(e),g=e=>["revolving","bonus"].includes(e?.plan)||e?.value>1,h=({props:e,showKCP:c,showBrazilianSSN:u,countrySpecificSchemas:m=null,billingAddressRequiredFields:p=null})=>{let C=s;const g=e.hasHolderName&&e.holderNameRequired;if(g&&(C=e.positionHolderNameOnTop?o:n),c&&(C=l,g&&(C=e.positionHolderNameOnTop?r:i)),u&&(C=d,g&&(C=e.positionHolderNameOnTop?t:a)),m){const r=m.flat(2).filter(e=>"number"!=typeof e);let i=r;p&&(i=r.filter(e=>p.includes(e))),C=s.concat(i),g&&(C=e.positionHolderNameOnTop?o.concat(i):n.concat(i))}return C},R=(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}},y=e=>({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}),O=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}),b=o=>o==e.partial?c:null;function f(e){return![p.ERROR_MSG_UNSUPPORTED_CARD_ENTERED,p.ERROR_MSG_CARD_TOO_OLD,p.ERROR_MSG_CARD_TOO_FAR_IN_FUTURE,p.ERROR_MSG_CARD_EXPIRES_TOO_SOON].includes(e)}function S(e){return u[e]??e}const x=(e,o)=>e.map(e=>{const n=e.id,r=m(),i="card"===n?"nocard":n,t=o[n]?.icon??C(i,r);return{id:e.id,name:e.brandObject.localeBrand||e.brandObject.brand,imageURL:t,altName:S(n)}}),A=(e,o,n)=>o.some(o=>e.includes(o[n])),E=({installmentOptions:e,fundingSource:o,amount:n})=>!(!e||0===Object.keys(e).length)&&(!(!n||0===n.value)&&(!o||"credit"===o));export{y as extractPropsForCardFields,O as extractPropsForSFP,C as getCardImageUrl,S as getFullBrandName,h as getLayout,b as handlePartialAddressMode,f as lookupBlurBasedErrors,x as mapDualBrandButtons,R as mapFieldKey,A as
|
|
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 r,KCP_CARD_NAME_BOTTOM as i,SSN_CARD_NAME_TOP as t,SSN_CARD_NAME_BOTTOM as a,CREDIT_CARD as s,KCP_CARD as l,SSN_CARD as d}from"./layouts.js";import{PARTIAL_ADDRESS_SCHEMA as c}from"../../../internal/Address/constants.js";import{BRAND_READABLE_NAME_MAP as u}from"../../../internal/SecuredFields/lib/constants.js";import m from"../../../../core/Context/useImage.js";import{SF_ErrorCodes as p}from"../../../../core/Errors/constants.js";const C=(e,o)=>o({type:"card"===e?"nocard":e||"nocard",extension:"svg"})(e),g=e=>["revolving","bonus"].includes(e?.plan)||e?.value>1,h=({props:e,showKCP:c,showBrazilianSSN:u,countrySpecificSchemas:m=null,billingAddressRequiredFields:p=null})=>{let C=s;const g=e.hasHolderName&&e.holderNameRequired;if(g&&(C=e.positionHolderNameOnTop?o:n),c&&(C=l,g&&(C=e.positionHolderNameOnTop?r:i)),u&&(C=d,g&&(C=e.positionHolderNameOnTop?t:a)),m){const r=m.flat(2).filter(e=>"number"!=typeof e);let i=r;p&&(i=r.filter(e=>p.includes(e))),C=s.concat(i),g&&(C=e.positionHolderNameOnTop?o.concat(i):n.concat(i))}return C},R=(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}},y=e=>({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}),O=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}),b=o=>o==e.partial?c:null;function f(e){return![p.ERROR_MSG_UNSUPPORTED_CARD_ENTERED,p.ERROR_MSG_CARD_TOO_OLD,p.ERROR_MSG_CARD_TOO_FAR_IN_FUTURE,p.ERROR_MSG_CARD_EXPIRES_TOO_SOON].includes(e)}function S(e){return u[e]??e}const x=(e,o)=>e.map(e=>{const n=e.id,r=m(),i="card"===n?"nocard":n,t=o?.[n]?.icon??C(i,r);return{id:e.id,name:e.brandObject.localeBrand||e.brandObject.brand,imageURL:t,altName:S(n)}}),A=(e,o,n)=>o.some(o=>e.includes(o[n])),E=({installmentOptions:e,fundingSource:o,amount:n})=>!(!e||0===Object.keys(e).length)&&(!(!n||0===n.value)&&(!o||"credit"===o));export{y as extractPropsForCardFields,O as extractPropsForSFP,C as getCardImageUrl,S as getFullBrandName,h as getLayout,b as handlePartialAddressMode,f as lookupBlurBasedErrors,x as mapDualBrandButtons,R as mapFieldKey,A as requiresDualBrandSelection,g as shouldIncludeInstallmentsInPaymentData,E as shouldShowInstallmentsComponent};
|
|
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 type { InstallmentOptions, InstallmentsState } from './components/Installments/Installments';\nimport { SFPProps } from '../../../internal/SecuredFields/SFP/types';\nimport { BRAND_READABLE_NAME_MAP } from '../../../internal/SecuredFields/lib/constants';\nimport useImage, { UseImageHookType } from '../../../../core/Context/useImage';\nimport { SF_ErrorCodes } from '../../../../core/Errors/constants';\nimport { BrandObject, CardBrandsConfiguration, DualBrandSelectElement, DualBrandButtons } from '../../types';\nimport { PaymentAmount } from '../../../../types';\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 * 'installments' should be added to the payload if it has plan as revolving or bonus\n * or value greater than 1.\n *\n * More about it here: COWEB-1070\n */\nexport const shouldIncludeInstallmentsInPaymentData = (installment?: InstallmentsState): boolean => {\n return ['revolving', 'bonus'].includes(installment?.plan) || installment?.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 hasCVC, installmentOptions)\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 mapDualBrandButtons = (\n dualBrandSelectElements: DualBrandSelectElement[],\n brandsConfiguration: CardBrandsConfiguration\n): DualBrandButtons[] => {\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.some is true - 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: readonly string[],\n returnedDualBrandingObjects: DualBrandSelectElement[] | BrandObject[],\n key: string\n) => returnedDualBrandingObjects.some(item => EU_BrandArray.includes(item[key]));\n\n/**\n * Determines whether the Installments component should be rendered.\n *\n * Installments Component is displayed when:\n * - installmentOptions is provided and not empty\n * - amount is provided and not zero\n * - fundingSource is not provided or is 'credit'\n *\n * @param params.installmentOptions - The installment configuration options\n * @param params.fundingSource - The card funding source (e.g. 'credit', 'debit')\n * @param params.amount - The payment amount\n * @returns Whether the Installments component should be rendered\n */\nexport const shouldShowInstallmentsComponent = ({\n installmentOptions,\n fundingSource,\n amount\n}: {\n installmentOptions?: InstallmentOptions;\n fundingSource?: string;\n amount?: PaymentAmount;\n}): boolean => {\n if (!installmentOptions || Object.keys(installmentOptions).length === 0) return false;\n if (!amount || amount.value === 0) return false;\n if (fundingSource && fundingSource !== 'credit') return false;\n\n return true;\n};\n"],"names":["getCardImageUrl","brand","getImage","type","extension","shouldIncludeInstallmentsInPaymentData","installment","includes","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","concat","mapFieldKey","key","i18n","countrySpecificLabels","get","extractPropsForCardFields","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","mapDualBrandButtons","dualBrandSelectElements","map","id","useImage","imageName","imageURL","icon","name","brandObject","localeBrand","altName","mustHandleDualBrandingAccordingToEURegulations","EU_BrandArray","returnedDualBrandingObjects","some","shouldShowInstallmentsComponent","fundingSource","amount","Object","keys","length"],"mappings":"ojBAuBO,MAAMA,EAAkB,CAACC,EAAeC,IAMpCA,EALc,CACjBC,KAAgB,SAAVF,EAAmB,SAAWA,GAAS,SAC7CG,UAAW,OAGRF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oD,EAAwBC,IAAIjE,IAC/B,MAAM/B,EAAQ+B,EAAKkE,GACbhG,EAAWiG,IACXC,EAAsB,SAAVnG,EAAmB,SAAWA,EAC1CoG,EAAWzD,EAAoB3C,IAAQqG,MAAQtG,EAAgBoG,EAAWlG,GAIhF,MAAO,CACHgG,GAAIlE,EAAKkE,GACTK,KAAMvE,EAAKwE,YAAYC,aAAezE,EAAKwE,YAAYvG,MACvDoG,WACAK,QAASb,EAAiB5F,MAYzB0G,EAAiD,CAC1DC,EACAC,EACAxE,IACCwE,EAA4BC,KAAK9E,GAAQ4E,EAAcrG,SAASyB,EAAKK,KAe7D0E,EAAkC,EAC3ChE,qBACAiE,gBACAC,eAMKlE,GAAiE,IAA3CmE,OAAOC,KAAKpE,GAAoBqE,aACtDH,GAA2B,IAAjBA,EAAOxG,UAClBuG,GAAmC,WAAlBA"}
|
|
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 type { InstallmentOptions, InstallmentsState } from './components/Installments/Installments';\nimport { SFPProps } from '../../../internal/SecuredFields/SFP/types';\nimport { BRAND_READABLE_NAME_MAP } from '../../../internal/SecuredFields/lib/constants';\nimport useImage, { UseImageHookType } from '../../../../core/Context/useImage';\nimport { SF_ErrorCodes } from '../../../../core/Errors/constants';\nimport { BrandObject, CardBrandsConfiguration, DualBrandSelectElement, DualBrandButtons } from '../../types';\nimport { PaymentAmount } from '../../../../types';\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 * 'installments' should be added to the payload if it has plan as revolving or bonus\n * or value greater than 1.\n *\n * More about it here: COWEB-1070\n */\nexport const shouldIncludeInstallmentsInPaymentData = (installment?: InstallmentsState): boolean => {\n return ['revolving', 'bonus'].includes(installment?.plan) || installment?.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 hasCVC, installmentOptions)\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): Pick<SFPProps, 'clientKey' | 'loadingContext'> & Partial<SFPProps> => {\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 };\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: string): string {\n return BRAND_READABLE_NAME_MAP[brand] ?? brand;\n}\n\nexport const mapDualBrandButtons = (\n dualBrandSelectElements: DualBrandSelectElement[],\n brandsConfiguration?: CardBrandsConfiguration\n): DualBrandButtons[] => {\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 * Checks if any of the brands requiring a selection mechanism are present in the binLookup response.\n *\n * If the result from Array.some is true - then we are in a dual branding scenario that requires selection, i.e.\n * - Show the dualBranding selector UI\n * - Preselect a card brand\n */\nexport const requiresDualBrandSelection = (\n brandsRequiringSelection: readonly string[],\n returnedDualBrandingObjects: DualBrandSelectElement[] | BrandObject[],\n key: string\n) => returnedDualBrandingObjects.some(item => brandsRequiringSelection.includes(item[key]));\n\n/**\n * Determines whether the Installments component should be rendered.\n *\n * Installments Component is displayed when:\n * - installmentOptions is provided and not empty\n * - amount is provided and not zero\n * - fundingSource is not provided or is 'credit'\n *\n * @param params.installmentOptions - The installment configuration options\n * @param params.fundingSource - The card funding source (e.g. 'credit', 'debit')\n * @param params.amount - The payment amount\n * @returns Whether the Installments component should be rendered\n */\nexport const shouldShowInstallmentsComponent = ({\n installmentOptions,\n fundingSource,\n amount\n}: {\n installmentOptions?: InstallmentOptions;\n fundingSource?: string;\n amount?: PaymentAmount;\n}): boolean => {\n if (!installmentOptions || Object.keys(installmentOptions).length === 0) return false;\n if (!amount || amount.value === 0) return false;\n if (fundingSource && fundingSource !== 'credit') return false;\n\n return true;\n};\n"],"names":["getCardImageUrl","brand","getImage","type","extension","shouldIncludeInstallmentsInPaymentData","installment","includes","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","concat","mapFieldKey","key","i18n","countrySpecificLabels","get","extractPropsForCardFields","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","mapDualBrandButtons","dualBrandSelectElements","map","id","useImage","imageName","imageURL","icon","name","brandObject","localeBrand","altName","requiresDualBrandSelection","brandsRequiringSelection","returnedDualBrandingObjects","some","shouldShowInstallmentsComponent","fundingSource","amount","Object","keys","length"],"mappings":"ojBAuBO,MAAMA,EAAkB,CAACC,EAAeC,IAMpCA,EALc,CACjBC,KAAgB,SAAVF,EAAmB,SAAWA,GAAS,SAC7CG,UAAW,OAGRF,CAAuBD,GASrBI,EAA0CC,GAC5C,CAAC,YAAa,SAASC,SAASD,GAAaE,OAASF,GAAaG,MAAQ,EAGzEC,EAAY,EACrBC,QACAC,UACAC,mBACAC,yBAAyB,KACzBC,+BAA+B,SAE/B,IAAIC,E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lG,GAIlF,MAAO,CACHgG,GAAIlE,EAAKkE,GACTK,KAAMvE,EAAKwE,YAAYC,aAAezE,EAAKwE,YAAYvG,MACvDoG,WACAK,QAASb,EAAiB5F,MAYzB0G,EAA6B,CACtCC,EACAC,EACAxE,IACCwE,EAA4BC,KAAK9E,GAAQ4E,EAAyBrG,SAASyB,EAAKK,KAexE0E,EAAkC,EAC3ChE,qBACAiE,gBACAC,eAMKlE,GAAiE,IAA3CmE,OAAOC,KAAKpE,GAAoBqE,aACtDH,GAA2B,IAAjBA,EAAOxG,UAClBuG,GAAmC,WAAlBA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"constants.js","sources":["../../../../src/components/Card/constants.ts"],"sourcesContent":["export const DUAL_BRANDS_THAT_NEED_SELECTION_MECHANISM = ['cartebancaire', 'bcmc', 'dankort'] as const;\n"],"names":["DUAL_BRANDS_THAT_NEED_SELECTION_MECHANISM"],"mappings":"MAAaA,EAA4C,CAAC,gBAAiB,OAAQ"}
|
|
1
|
+
{"version":3,"file":"constants.js","sources":["../../../../src/components/Card/constants.ts"],"sourcesContent":["export const DUAL_BRANDS_THAT_NEED_SELECTION_MECHANISM = ['cartebancaire', 'bcmc', 'dankort'] as const;\n\nexport const DUAL_BRAND_SELECTION_MECHANISM_MAP: Record<string, string> = {\n fr: 'cartebancaire',\n be: 'bcmc',\n dk: 'dankort'\n};\n"],"names":["DUAL_BRANDS_THAT_NEED_SELECTION_MECHANISM"],"mappings":"MAAaA,EAA4C,CAAC,gBAAiB,OAAQ"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createElement as e}from"../../external/preact/dist/preact.js";import{UIElement as t}from"../internal/UIElement/UIElement.js";import n from"./CustomCardInput/CustomCardInput.js";import s from"../../utils/browserInfo.js";import o from"../internal/SecuredFields/binLookup/triggerBinLookUp.js";import{getCardImageUrl as r,fieldTypeToSnakeCase as i}from"../internal/SecuredFields/utils.js";import{TxVariants as a}from"../tx-variants.js";import{AnalyticsInfoEvent as
|
|
1
|
+
import{createElement as e}from"../../external/preact/dist/preact.js";import{UIElement as t}from"../internal/UIElement/UIElement.js";import n from"./CustomCardInput/CustomCardInput.js";import s from"../../utils/browserInfo.js";import o from"../internal/SecuredFields/binLookup/triggerBinLookUp.js";import{getCardImageUrl as r,fieldTypeToSnakeCase as i}from"../internal/SecuredFields/utils.js";import{TxVariants as a}from"../tx-variants.js";import{AnalyticsInfoEvent as d,InfoEventType as p}from"../../core/Analytics/events/AnalyticsInfoEvent.js";import{DUAL_BRANDS_THAT_NEED_SELECTION_MECHANISM as u}from"../Card/constants.js";function c(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class l extends t{formatProps(e){return{...e,type:a.customCard}}formatData(){const e=this.state.selectedBrandValue;return{paymentMethod:{type:"scheme",...this.state.data,...e&&{brand:e}},browserInfo:this.browserInfo,origin:!!window&&window.location.origin}}updateStyles(e){return this.componentRef?.updateStyles&&this.componentRef.updateStyles(e),this}setFocusOn(e){return this.componentRef?.setFocusOn&&this.componentRef.setFocusOn(e),this}processBinLookupResponse(e){return this.componentRef?.processBinLookupResponse&&this.componentRef.processBinLookupResponse(e),this}dualBrandingChangeHandler(e){return this.componentRef?.dualBrandingChangeHandler&&this.componentRef.dualBrandingChangeHandler(e),this}handleUnsupportedCard(e){return this.componentRef?.handleUnsupportedCard&&this.componentRef.handleUnsupportedCard(e),this}onBinLookup(e){const t={...e};if(t.rootNode=this._node,!t.isReset){t.supportedBrandsRaw=e.supportedBrandsRaw?.map(e=>(e.brandImageUrl=this.props.brandsConfiguration[e.brand]?.icon??r(e.brand,this.resources),e));let n=!1,s=!1;e.supportedBrandsRaw?.length>1&&(n=!0,s=e.detectedBrands.some(e=>u.includes(e))),t.dualBrandingType=null,n&&(t.dualBrandingType=s?"Dual Branded (Selectable): Regulation mandates that you must provide a brand selection mechanism":"Dual Branded (Display-only): No selection mechanism required")}this.props.onBinLookup(t)}get isValid(){return!!this.state.isValid}get browserInfo(){return s()}componentToRender(){return e(n,{ref:e=>{this.componentRef=e},...this.props,...this.state,handleKeyPress:this.handleKeyPress,rootNode:this._node,onChange:this.setState,onBinValue:this.onBinValue,implementationType:"custom",resources:this.resources,brand:this.brand,onFocus:this.onFocus,onSubmitAnalytics:this.submitAnalytics})}constructor(...e){super(...e),c(this,"brand",a.card),c(this,"onBinValue",o(this)),c(this,"onFocus",e=>{const t=new d({component:this.type,type:!0===e.focus?p.focus:p.unfocus,target:i(e.fieldType)});this.submitAnalytics(t),this.props.onFocus?.(e)}),c(this,"onEnterKeyPressed",(e,t)=>{this.props.onEnterKeyPressed?.(e,t)})}}c(l,"type",a.customCard),c(l,"defaultProps",{onBinLookup:()=>{},brandsConfiguration:{}});export{l as CustomCard,l as default};
|
|
2
2
|
//# sourceMappingURL=CustomCard.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CustomCard.js","sources":["../../../../src/components/CustomCard/CustomCard.tsx"],"sourcesContent":["import { h } from 'preact';\nimport UIElement from '../internal/UIElement';\nimport CustomCardInput from './CustomCardInput';\nimport collectBrowserInfo from '../../utils/browserInfo';\nimport triggerBinLookUp from '../internal/SecuredFields/binLookup/triggerBinLookUp';\nimport { CardBinLookupData, CardFocusData } from '../internal/SecuredFields/lib/types';\nimport { BrandObject } from '../Card/types';\nimport { getCardImageUrl, fieldTypeToSnakeCase } from '../internal/SecuredFields/utils';\nimport { TxVariants } from '../tx-variants';\nimport { CustomCardConfiguration } from './types';\nimport { AnalyticsInfoEvent, InfoEventType, UiTarget } from '../../core/Analytics/events/AnalyticsInfoEvent';\n\nexport class CustomCard extends UIElement<CustomCardConfiguration> {\n public static readonly type = TxVariants.customCard;\n\n protected static readonly defaultProps = {\n onBinLookup: () => {},\n brandsConfiguration: {}\n };\n\n private brand = TxVariants.card;\n\n formatProps(props: CustomCardConfiguration) {\n return {\n ...props,\n type: TxVariants.customCard\n };\n }\n\n /**\n * Formats the component data output\n */\n formatData() {\n const sfBrand = this.state.selectedBrandValue;\n return {\n paymentMethod: {\n type: 'scheme',\n ...this.state.data,\n ...(sfBrand && { brand: sfBrand })\n },\n browserInfo: this.browserInfo,\n origin: !!window && window.location.origin\n };\n }\n\n updateStyles(stylesObj) {\n if (this.componentRef?.updateStyles) this.componentRef.updateStyles(stylesObj);\n return this;\n }\n\n setFocusOn(frame) {\n if (this.componentRef?.setFocusOn) this.componentRef.setFocusOn(frame);\n return this;\n }\n\n processBinLookupResponse(binLookupResponse) {\n if (this.componentRef?.processBinLookupResponse) this.componentRef.processBinLookupResponse(binLookupResponse);\n return this;\n }\n\n dualBrandingChangeHandler(e: Event | string) {\n if (this.componentRef?.dualBrandingChangeHandler) this.componentRef.dualBrandingChangeHandler(e);\n return this;\n }\n\n handleUnsupportedCard(errObj) {\n if (this.componentRef?.handleUnsupportedCard) this.componentRef.handleUnsupportedCard(errObj);\n return this;\n }\n\n onBinLookup(obj: CardBinLookupData) {\n const nuObj = { ...obj };\n nuObj.rootNode = this._node;\n\n if (!nuObj.isReset) {\n // Add brandImage urls, first checking if the merchant has configured their own one for the brand\n nuObj.supportedBrandsRaw = obj.supportedBrandsRaw?.map((item: BrandObject) => {\n item.brandImageUrl = this.props.brandsConfiguration[item.brand]?.icon ?? getCardImageUrl(item.brand, this.resources);\n return item;\n });\n }\n\n this.props.onBinLookup(nuObj);\n }\n\n public onBinValue = triggerBinLookUp(this);\n\n get isValid() {\n return !!this.state.isValid;\n }\n\n get browserInfo() {\n return collectBrowserInfo();\n }\n\n private onFocus = (obj: CardFocusData) => {\n const event = new AnalyticsInfoEvent({\n component: this.type,\n type: obj.focus === true ? InfoEventType.focus : InfoEventType.unfocus,\n target: fieldTypeToSnakeCase(obj.fieldType) as UiTarget\n });\n\n this.submitAnalytics(event);\n\n // Call merchant defined callback\n this.props.onFocus?.(obj);\n };\n\n protected onEnterKeyPressed = (activeElement: Element, component: UIElement) => {\n this.props.onEnterKeyPressed?.(activeElement, component);\n };\n\n protected override componentToRender(): h.JSX.Element {\n return (\n <CustomCardInput\n ref={ref => {\n this.componentRef = ref;\n }}\n {...this.props}\n {...this.state}\n handleKeyPress={this.handleKeyPress}\n rootNode={this._node}\n onChange={this.setState}\n onBinValue={this.onBinValue}\n implementationType={'custom'}\n resources={this.resources}\n brand={this.brand}\n onFocus={this.onFocus}\n onSubmitAnalytics={this.submitAnalytics}\n />\n );\n }\n}\n\nexport default CustomCard;\n"],"names":["CustomCard","UIElement","formatProps","props","type","TxVariants","customCard","formatData","sfBrand","this","state","selectedBrandValue","paymentMethod","data","brand","browserInfo","origin","window","location","updateStyles","stylesObj","componentRef","setFocusOn","frame","processBinLookupResponse","binLookupResponse","dualBrandingChangeHandler","e","handleUnsupportedCard","errObj","onBinLookup","obj","nuObj","rootNode","_node","isReset","supportedBrandsRaw","map","item","brandImageUrl","brandsConfiguration","icon","getCardImageUrl","resources","isValid","collectBrowserInfo","componentToRender","h","CustomCardInput","ref","handleKeyPress","onChange","setState","onBinValue","implementationType","onFocus","onSubmitAnalytics","submitAnalytics","super","args","_define_property","card","triggerBinLookUp","event","AnalyticsInfoEvent","component","focus","InfoEventType","unfocus","target","fieldTypeToSnakeCase","fieldType","onEnterKeyPressed","activeElement","defaultProps"],"mappings":"
|
|
1
|
+
{"version":3,"file":"CustomCard.js","sources":["../../../../src/components/CustomCard/CustomCard.tsx"],"sourcesContent":["import { h } from 'preact';\nimport UIElement from '../internal/UIElement';\nimport CustomCardInput from './CustomCardInput';\nimport collectBrowserInfo from '../../utils/browserInfo';\nimport triggerBinLookUp from '../internal/SecuredFields/binLookup/triggerBinLookUp';\nimport { CardBinLookupData, CardFocusData } from '../internal/SecuredFields/lib/types';\nimport { BrandObject } from '../Card/types';\nimport { getCardImageUrl, fieldTypeToSnakeCase } from '../internal/SecuredFields/utils';\nimport { TxVariants } from '../tx-variants';\nimport { CustomCardConfiguration } from './types';\nimport { AnalyticsInfoEvent, InfoEventType, UiTarget } from '../../core/Analytics/events/AnalyticsInfoEvent';\nimport { DUAL_BRANDS_THAT_NEED_SELECTION_MECHANISM } from '../Card/constants';\n\nconst SELECTABLE_DUAL_BRANDED_SCENARIO = 'Dual Branded (Selectable): Regulation mandates that you must provide a brand selection mechanism';\nconst DISPLAY_ONLY_DUAL_BRANDED_SCENARIO = 'Dual Branded (Display-only): No selection mechanism required';\n\nexport class CustomCard extends UIElement<CustomCardConfiguration> {\n public static readonly type = TxVariants.customCard;\n\n protected static readonly defaultProps = {\n onBinLookup: () => {},\n brandsConfiguration: {}\n };\n\n private brand = TxVariants.card;\n\n formatProps(props: CustomCardConfiguration) {\n return {\n ...props,\n type: TxVariants.customCard\n };\n }\n\n /**\n * Formats the component data output\n */\n formatData() {\n const sfBrand = this.state.selectedBrandValue;\n return {\n paymentMethod: {\n type: 'scheme',\n ...this.state.data,\n ...(sfBrand && { brand: sfBrand })\n },\n browserInfo: this.browserInfo,\n origin: !!window && window.location.origin\n };\n }\n\n updateStyles(stylesObj) {\n if (this.componentRef?.updateStyles) this.componentRef.updateStyles(stylesObj);\n return this;\n }\n\n setFocusOn(frame) {\n if (this.componentRef?.setFocusOn) this.componentRef.setFocusOn(frame);\n return this;\n }\n\n processBinLookupResponse(binLookupResponse) {\n if (this.componentRef?.processBinLookupResponse) this.componentRef.processBinLookupResponse(binLookupResponse);\n return this;\n }\n\n dualBrandingChangeHandler(e: Event | string) {\n if (this.componentRef?.dualBrandingChangeHandler) this.componentRef.dualBrandingChangeHandler(e);\n return this;\n }\n\n handleUnsupportedCard(errObj) {\n if (this.componentRef?.handleUnsupportedCard) this.componentRef.handleUnsupportedCard(errObj);\n return this;\n }\n\n onBinLookup(obj: CardBinLookupData) {\n const nuObj = { ...obj };\n nuObj.rootNode = this._node;\n\n if (!nuObj.isReset) {\n // Add brandImage urls, first checking if the merchant has configured their own one for the brand\n nuObj.supportedBrandsRaw = obj.supportedBrandsRaw?.map((item: BrandObject) => {\n item.brandImageUrl = this.props.brandsConfiguration[item.brand]?.icon ?? getCardImageUrl(item.brand, this.resources);\n return item;\n });\n\n // Check for dual branded scenario and, if so, discern which type\n let isDualBrandedScenario = false;\n let isSelectableDualBrandedScenario = false;\n\n if (obj.supportedBrandsRaw?.length > 1) {\n isDualBrandedScenario = true;\n isSelectableDualBrandedScenario = obj.detectedBrands.some(item =>\n (DUAL_BRANDS_THAT_NEED_SELECTION_MECHANISM as readonly string[]).includes(item)\n );\n }\n\n // Set the dual branding type\n nuObj.dualBrandingType = null;\n\n if (isDualBrandedScenario) {\n nuObj.dualBrandingType = isSelectableDualBrandedScenario ? SELECTABLE_DUAL_BRANDED_SCENARIO : DISPLAY_ONLY_DUAL_BRANDED_SCENARIO;\n }\n }\n\n this.props.onBinLookup(nuObj);\n }\n\n public onBinValue = triggerBinLookUp(this);\n\n get isValid() {\n return !!this.state.isValid;\n }\n\n get browserInfo() {\n return collectBrowserInfo();\n }\n\n private onFocus = (obj: CardFocusData) => {\n const event = new AnalyticsInfoEvent({\n component: this.type,\n type: obj.focus === true ? InfoEventType.focus : InfoEventType.unfocus,\n target: fieldTypeToSnakeCase(obj.fieldType) as UiTarget\n });\n\n this.submitAnalytics(event);\n\n // Call merchant defined callback\n this.props.onFocus?.(obj);\n };\n\n protected onEnterKeyPressed = (activeElement: Element, component: UIElement) => {\n this.props.onEnterKeyPressed?.(activeElement, component);\n };\n\n protected override componentToRender(): h.JSX.Element {\n return (\n <CustomCardInput\n ref={ref => {\n this.componentRef = ref;\n }}\n {...this.props}\n {...this.state}\n handleKeyPress={this.handleKeyPress}\n rootNode={this._node}\n onChange={this.setState}\n onBinValue={this.onBinValue}\n implementationType={'custom'}\n resources={this.resources}\n brand={this.brand}\n onFocus={this.onFocus}\n onSubmitAnalytics={this.submitAnalytics}\n />\n );\n }\n}\n\nexport default CustomCard;\n"],"names":["CustomCard","UIElement","formatProps","props","type","TxVariants","customCard","formatData","sfBrand","this","state","selectedBrandValue","paymentMethod","data","brand","browserInfo","origin","window","location","updateStyles","stylesObj","componentRef","setFocusOn","frame","processBinLookupResponse","binLookupResponse","dualBrandingChangeHandler","e","handleUnsupportedCard","errObj","onBinLookup","obj","nuObj","rootNode","_node","isReset","supportedBrandsRaw","map","item","brandImageUrl","brandsConfiguration","icon","getCardImageUrl","resources","isDualBrandedScenario","isSelectableDualBrandedScenario","length","detectedBrands","some","DUAL_BRANDS_THAT_NEED_SELECTION_MECHANISM","includes","dualBrandingType","isValid","collectBrowserInfo","componentToRender","h","CustomCardInput","ref","handleKeyPress","onChange","setState","onBinValue","implementationType","onFocus","onSubmitAnalytics","submitAnalytics","super","args","_define_property","card","triggerBinLookUp","event","AnalyticsInfoEvent","component","focus","InfoEventType","unfocus","target","fieldTypeToSnakeCase","fieldType","onEnterKeyPressed","activeElement","defaultProps"],"mappings":"0uBAgBO,MAAMA,UAAmBC,EAU5BC,WAAAA,CAAYC,GACR,MAAO,IACAA,EACHC,KAAMC,EAAWC,WAEzB,CAKAC,UAAAA,GACI,MAAMC,EAAUC,KAAKC,MAAMC,mBAC3B,MAAO,CACHC,cAAe,CACXR,KAAM,YACHK,KAAKC,MAAMG,QACVL,GAAW,CAAEM,MAAON,IAE5BO,YAAaN,KAAKM,YAClBC,SAAUC,QAAUA,OAAOC,SAASF,OAE5C,CAEAG,YAAAA,CAAaC,GAET,OADIX,KAAKY,cAAcF,cAAcV,KAAKY,aAAaF,aAAaC,GAC7DX,IACX,CAEAa,UAAAA,CAAWC,GAEP,OADId,KAAKY,cAAcC,YAAYb,KAAKY,aAAaC,WAAWC,GACzDd,IACX,CAEAe,wBAAAA,CAAyBC,GAErB,OADIhB,KAAKY,cAAcG,0BAA0Bf,KAAKY,aAAaG,yBAAyBC,GACrFhB,IACX,CAEAiB,yBAAAA,CAA0BC,GAEtB,OADIlB,KAAKY,cAAcK,2BAA2BjB,KAAKY,aAAaK,0BAA0BC,GACvFlB,IACX,CAEAmB,qBAAAA,CAAsBC,GAElB,OADIpB,KAAKY,cAAcO,uBAAuBnB,KAAKY,aAAaO,sBAAsB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/C,EAAIgD,aAGrCtE,KAAKwD,gBAAgBM,GAGrB9D,KAAKN,MAAM4D,UAAUhC,KAGzBqC,EAAA3D,KAAUuE,oBAAoB,CAACC,EAAwBR,KACnDhE,KAAKN,MAAM6E,oBAAoBC,EAAeR,MAlHlDL,EADSpE,EACcI,OAAOC,EAAWC,YAEzC8D,EAHSpE,EAGiBkF,eAAe,CACrCpD,YAAa,OACbU,oBAAqB,CAAA"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createElement as e}from"../../../external/preact/dist/preact.js";import{useRef as o,useState as n,useMemo as r,useEffect as t}from"../../../external/preact/hooks/dist/hooks.js";import a from"../../internal/SecuredFields/SFP/SecuredFieldsProvider.js";import s from"../../internal/SecuredFields/binLookup/extensions.js";function i(i){const l=o(null),[u,
|
|
1
|
+
import{createElement as e}from"../../../external/preact/dist/preact.js";import{useRef as o,useState as n,useMemo as r,useEffect as t}from"../../../external/preact/hooks/dist/hooks.js";import a from"../../internal/SecuredFields/SFP/SecuredFieldsProvider.js";import s from"../../internal/SecuredFields/binLookup/extensions.js";function i(i){const l=o(null),[u,p]=n({}),[c,m]=n({}),[y,h]=n({}),[S,C]=n(!1),[f,g]=n(null),[F,V]=n([]),[E,x]=n(""),B=r(()=>s(i,{sfp:l},{dualBrandSelectElements:F,setDualBrandSelectElements:V,setSelectedBrandValue:x,issuingCountryCode:f,setIssuingCountryCode:g}),[F,f]);return this.processBinLookupResponse=(e,o)=>{B.processBinLookup(e,o)},this.dualBrandingChangeHandler=B.handleDualBrandSelection,t(()=>(this.setFocusOn=l.current.setFocusOn,this.updateStyles=l.current.updateStyles,this.showValidation=l.current.showValidation,this.handleUnsupportedCard=l.current.handleUnsupportedCard,()=>{l.current.destroy()}),[]),t(()=>{const e=l.current.mapErrorsToValidationRuleResult(),o={...u,...e};if(i.onChange({data:y,valid:c,errors:o,isValid:S,selectedBrandValue:E}),Object.keys(o).length){const e=Object.entries(o).map(([e,o])=>({fieldType:e,...o||{error:"",rootNode:this.props.rootNode}}));this.props.onValidationError?.(e)}},[y,c,u,E]),e(a,{ref:l,...d(i),type:i.brand,componentType:i.type,onChange:e=>{h({...y,...e.data}),p({...u,...e.errors}),m({...c,...e.valid}),C(e.isSfpValid)},onSubmitAnalytics:i.onSubmitAnalytics,exposeExpiryDate:!1,disableIOSArrowKeys:null,render:()=>null})}i.defaultProps={onChange:()=>{},onError:()=>{},onValidationError:()=>{}};const d=e=>({autoFocus:e.autoFocus,brands:e.brands,brandsConfiguration:e.brandsConfiguration,clientKey:e.clientKey,forceCompat:e.forceCompat,i18n:e.i18n,implementationType:e.implementationType,keypadFix:e.keypadFix,legacyInputMode:e.legacyInputMode,loadingContext:e.loadingContext,minimumExpiryDate:e.minimumExpiryDate,onAdditionalSFConfig:e.onAdditionalSFConfig,onAdditionalSFRemoved:e.onAdditionalSFRemoved,onAllValid:e.onAllValid,onAutoComplete:e.onAutoComplete,onBinValue:e.onBinValue,onBrand:e.onBrand,onConfigSuccess:e.onConfigSuccess,handleKeyPress:e.handleKeyPress,onError:e.onError,onFieldValid:e.onFieldValid,onFocus:e.onFocus,onLoad:e.onLoad,rootNode:e.rootNode,showWarnings:e.showWarnings,styles:e.styles,trimTrailingSeparator:e.trimTrailingSeparator,resources:e.resources,maskSecurityCode:e.maskSecurityCode,placeholders:e.placeholders});export{i as default};
|
|
2
2
|
//# sourceMappingURL=CustomCardInput.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CustomCardInput.js","sources":["../../../../../src/components/CustomCard/CustomCardInput/CustomCardInput.tsx"],"sourcesContent":["import { h } from 'preact';\nimport { useState, useEffect, useRef, useMemo } from 'preact/hooks';\nimport Language from '../../../language/Language';\nimport SecuredFieldsProvider from '../../internal/SecuredFields/SFP/SecuredFieldsProvider';\nimport { SFPState } from '../../internal/SecuredFields/SFP/types';\nimport { BinLookupResponse, CardBrandsConfiguration, CardPlaceholders } from '../../Card/types';\nimport SFExtensions from '../../internal/SecuredFields/binLookup/extensions';\nimport { StylesObject } from '../../internal/SecuredFields/lib/types';\nimport { Resources } from '../../../core/Context/Resources';\nimport { SFError } from '../../Card/components/CardInput/types';\nimport { ValidationError } from '../types';\nimport type { AbstractAnalyticsEvent } from '../../../core/Analytics/events/AbstractAnalyticsEvent';\n\ninterface SecuredFieldsProps {\n autoFocus?: boolean;\n brand?: string;\n brands?: string[];\n brandsConfiguration?: CardBrandsConfiguration;\n clientKey?: string;\n countryCode?: string;\n forceCompat?: boolean;\n i18n: Language;\n implementationType?: string;\n keypadFix?: boolean;\n loadingContext?: string;\n legacyInputMode?: boolean;\n minimumExpiryDate?: string;\n onAdditionalSFConfig?: () => {};\n onAdditionalSFRemoved?: () => {};\n onAllValid?: () => {};\n onAutoComplete?: () => {};\n onBinValue?: () => {};\n onBrand?: () => {};\n onConfigSuccess?: () => {};\n onChange: (data) => void;\n onSubmitAnalytics?: (event: AbstractAnalyticsEvent) => void;\n handleKeyPress?: (obj: KeyboardEvent) => void;\n onError?: () => {};\n onFieldValid?: () => {};\n onFocus?: (e) => {};\n onLoad?: () => {};\n placeholders?: CardPlaceholders;\n rootNode: HTMLElement;\n resources: Resources;\n showWarnings?: boolean;\n styles?: StylesObject;\n trimTrailingSeparator?: boolean;\n type: string;\n maskSecurityCode?: boolean;\n}\n\nconst defaultProps = {\n onChange: () => {},\n onError: () => {},\n onValidationError: () => {}\n};\n\nfunction CustomCardInput(props: Readonly<SecuredFieldsProps>) {\n const sfp = useRef(null);\n\n const [errors, setErrors] = useState({});\n const [valid, setValid] = useState({});\n const [data, setData] = useState({});\n\n const [isSfpValid, setIsSfpValid] = useState(false);\n\n const [issuingCountryCode, setIssuingCountryCode] = useState(null);\n\n const [dualBrandSelectElements, setDualBrandSelectElements] = useState([]);\n const [selectedBrandValue, setSelectedBrandValue] = useState('');\n\n const handleSecuredFieldsChange = (sfState: SFPState): void => {\n setData({ ...data, ...sfState.data });\n setErrors({ ...errors, ...sfState.errors });\n setValid({ ...valid, ...sfState.valid });\n\n setIsSfpValid(sfState.isSfpValid);\n };\n\n // Farm the handlers for binLookup related functionality out to another 'extensions' file\n const extensions = useMemo(\n () =>\n SFExtensions(\n props,\n { sfp },\n { dualBrandSelectElements, setDualBrandSelectElements, setSelectedBrandValue, issuingCountryCode, setIssuingCountryCode }\n ),\n [dualBrandSelectElements, issuingCountryCode]\n );\n\n /**\n * EXPECTED METHODS ON SecuredFields.this\n */\n this.processBinLookupResponse = (binLookupResponse: BinLookupResponse, isReset: boolean) => {\n extensions.processBinLookup(binLookupResponse, isReset);\n };\n\n this.dualBrandingChangeHandler = extensions.handleDualBrandSelection;\n\n /**\n * EFFECT HOOKS\n */\n useEffect(() => {\n // componentDidMount\n this.setFocusOn = sfp.current.setFocusOn;\n this.updateStyles = sfp.current.updateStyles;\n this.showValidation = sfp.current.showValidation;\n this.handleUnsupportedCard = sfp.current.handleUnsupportedCard;\n\n // componentWillUnmount\n return () => {\n sfp.current.destroy();\n };\n }, []);\n\n /**\n * Main 'componentDidUpdate' handler\n */\n useEffect(() => {\n const sfStateErrorsObj = sfp.current.mapErrorsToValidationRuleResult();\n\n const mappedErrors = { ...errors, ...sfStateErrorsObj }; // maps sfErrors\n\n props.onChange({\n data,\n valid,\n errors: mappedErrors,\n isValid: isSfpValid,\n selectedBrandValue\n });\n\n // Create an array of Validation error objects and send to callback\n if (Object.keys(mappedErrors).length) {\n const validationErrors: ValidationError[] = Object.entries(mappedErrors).map(([fieldType, error]) => {\n const valErr: ValidationError = {\n fieldType,\n ...(error ? (error as SFError) : { error: '', rootNode: this.props.rootNode })\n };\n return valErr;\n });\n this.props.onValidationError?.(validationErrors);\n }\n }, [data, valid, errors, selectedBrandValue]);\n\n /**\n * RENDER\n */\n // prettier-ignore\n return (\n <SecuredFieldsProvider\n ref={sfp}\n {...extractPropsForSFP(props)}\n type={props.brand}\n componentType={props.type}\n onChange={handleSecuredFieldsChange}\n onSubmitAnalytics={props.onSubmitAnalytics}\n render={() => null}\n />\n );\n}\n\nCustomCardInput.defaultProps = defaultProps;\n\nexport default CustomCardInput;\n\nconst extractPropsForSFP = (props: SecuredFieldsProps) => {\n return {\n autoFocus: props.autoFocus,\n brands: props.brands,\n brandsConfiguration: props.brandsConfiguration,\n clientKey: props.clientKey,\n forceCompat: props.forceCompat,\n // countryCode: props.countryCode, // only used for korean cards when koreanAuthenticationRequired is true\n i18n: props.i18n,\n implementationType: props.implementationType,\n keypadFix: props.keypadFix,\n legacyInputMode: props.legacyInputMode,\n loadingContext: props.loadingContext,\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 onBrand: props.onBrand,\n // onChange // set directly\n onConfigSuccess: props.onConfigSuccess,\n handleKeyPress: props.handleKeyPress,\n onError: props.onError,\n onFieldValid: props.onFieldValid,\n onFocus: props.onFocus,\n onLoad: props.onLoad,\n // render // set directly\n rootNode: props.rootNode,\n showWarnings: props.showWarnings,\n styles: props.styles,\n trimTrailingSeparator: props.trimTrailingSeparator,\n resources: props.resources,\n maskSecurityCode: props.maskSecurityCode,\n placeholders: props.placeholders\n };\n};\n"],"names":["CustomCardInput","props","sfp","useRef","errors","setErrors","useState","valid","setValid","data","setData","isSfpValid","setIsSfpValid","issuingCountryCode","setIssuingCountryCode","dualBrandSelectElements","setDualBrandSelectElements","selectedBrandValue","setSelectedBrandValue","extensions","useMemo","SFExtensions","this","processBinLookupResponse","binLookupResponse","isReset","processBinLookup","dualBrandingChangeHandler","handleDualBrandSelection","useEffect","setFocusOn","current","updateStyles","showValidation","handleUnsupportedCard","destroy","sfStateErrorsObj","mapErrorsToValidationRuleResult","mappedErrors","onChange","isValid","Object","keys","length","validationErrors","entries","map","fieldType","error","rootNode","onValidationError","h","SecuredFieldsProvider","ref","extractPropsForSFP","type","brand","componentType","sfState","onSubmitAnalytics","render","defaultProps","onError","autoFocus","brands","brandsConfiguration","clientKey","forceCompat","i18n","implementationType","keypadFix","legacyInputMode","loadingContext","minimumExpiryDate","onAdditionalSFConfig","onAdditionalSFRemoved","onAllValid","onAutoComplete","onBinValue","onBrand","onConfigSuccess","handleKeyPress","onFieldValid","onFocus","onLoad","showWarnings","styles","trimTrailingSeparator","resources","maskSecurityCode","placeholders"],"mappings":"qUAyDA,SAASA,EAAgBC,GACrB,MAAMC,EAAMC,EAAO,OAEZC,EAAQC,GAAaC,EAAS,CAAA,IAC9BC,EAAOC,GAAYF,EAAS,CAAA,IAC5BG,EAAMC,GAAWJ,EAAS,CAAA,IAE1BK,EAAYC,GAAiBN,GAAS,IAEtCO,EAAoBC,GAAyBR,EAAS,OAEtDS,EAAyBC,GAA8BV,EAAS,KAChEW,EAAoBC,GAAyBZ,EAAS,IAWvDa,EAAaC,EACf,IACIC,EACIpB,EACA,CAAEC,OACF,CAAEa,0BAAyBC,6BAA4BE,wBAAuBL,qBAAoBC,0BAE1G,CAACC,EAAyBF,IA6D9B,OAvDAS,KAAKC,yBAA2B,CAACC,EAAsCC,KACnEN,EAAWO,iBAAiBF,EAAmBC,IAGnDH,KAAKK,0BAA4BR,EAAWS,yBAK5CC,EAAU,KAENP,KAAKQ,WAAa5B,EAAI6B,QAAQD,WAC9BR,KAAKU,aAAe9B,EAAI6B,QAAQC,aAChCV,KAAKW,eAAiB/B,EAAI6B,QAAQE,eAClCX,KAAKY,sBAAwBhC,EAAI6B,QAAQG,sBAGlC,KACHhC,EAAI6B,QAAQI,YAEjB,IAKHN,EAAU,KACN,MAAMO,EAAmBlC,EAAI6B,QAAQM,kCAE/BC,EAAe,IAAKlC,KAAWgC,GAWrC,GATAnC,EAAMsC,SAAS,CACX9B,OACAF,QACAH,OAAQkC,EACRE,QAAS7B,EACTM,uBAIAwB,OAAOC,KAAKJ,GAAcK,OAAQ,CAClC,MAAMC,EAAsCH,OAAOI,QAAQP,GAAcQ,IAAI,EAAEC,EAAWC,MACtD,CAC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uBtF,EAAMsF,sBAC7BC,UAAWvF,EAAMuF,UACjBC,iBAAkBxF,EAAMwF,iBACxBC,aAAczF,EAAMyF"}
|
|
1
|
+
{"version":3,"file":"CustomCardInput.js","sources":["../../../../../src/components/CustomCard/CustomCardInput/CustomCardInput.tsx"],"sourcesContent":["import { h } from 'preact';\nimport { useState, useEffect, useRef, useMemo } from 'preact/hooks';\nimport Language from '../../../language/Language';\nimport SecuredFieldsProvider from '../../internal/SecuredFields/SFP/SecuredFieldsProvider';\nimport { SFPState } from '../../internal/SecuredFields/SFP/types';\nimport { BinLookupResponse, CardBrandsConfiguration, CardPlaceholders } from '../../Card/types';\nimport SFExtensions from '../../internal/SecuredFields/binLookup/extensions';\nimport { StylesObject } from '../../internal/SecuredFields/lib/types';\nimport { Resources } from '../../../core/Context/Resources';\nimport { SFError } from '../../Card/components/CardInput/types';\nimport { ValidationError } from '../types';\nimport type { AbstractAnalyticsEvent } from '../../../core/Analytics/events/AbstractAnalyticsEvent';\n\ninterface SecuredFieldsProps {\n autoFocus?: boolean;\n brand?: string;\n brands?: string[];\n brandsConfiguration?: CardBrandsConfiguration;\n clientKey: string;\n countryCode?: string;\n forceCompat?: boolean;\n i18n: Language;\n implementationType?: 'components' | 'custom';\n keypadFix?: boolean;\n loadingContext?: string;\n legacyInputMode?: boolean;\n minimumExpiryDate?: string;\n onAdditionalSFConfig?: () => {};\n onAdditionalSFRemoved?: () => {};\n onAllValid?: () => {};\n onAutoComplete?: () => {};\n onBinValue?: () => {};\n onBrand?: () => {};\n onConfigSuccess?: () => {};\n onChange: (data) => void;\n onSubmitAnalytics?: (event: AbstractAnalyticsEvent) => void;\n handleKeyPress?: (obj: KeyboardEvent) => void;\n onError?: () => {};\n onFieldValid?: () => {};\n onFocus?: (e) => {};\n onLoad?: () => {};\n placeholders?: CardPlaceholders;\n rootNode: HTMLElement;\n resources: Resources;\n showWarnings?: boolean;\n styles?: StylesObject;\n trimTrailingSeparator?: boolean;\n type: string;\n maskSecurityCode?: boolean;\n}\n\nconst defaultProps = {\n onChange: () => {},\n onError: () => {},\n onValidationError: () => {}\n};\n\nfunction CustomCardInput(props: Readonly<SecuredFieldsProps>) {\n const sfp = useRef(null);\n\n const [errors, setErrors] = useState({});\n const [valid, setValid] = useState({});\n const [data, setData] = useState({});\n\n const [isSfpValid, setIsSfpValid] = useState(false);\n\n const [issuingCountryCode, setIssuingCountryCode] = useState(null);\n\n const [dualBrandSelectElements, setDualBrandSelectElements] = useState([]);\n const [selectedBrandValue, setSelectedBrandValue] = useState('');\n\n const handleSecuredFieldsChange = (sfState: SFPState): void => {\n setData({ ...data, ...sfState.data });\n setErrors({ ...errors, ...sfState.errors });\n setValid({ ...valid, ...sfState.valid });\n\n setIsSfpValid(sfState.isSfpValid);\n };\n\n // Farm the handlers for binLookup related functionality out to another 'extensions' file\n const extensions = useMemo(\n () =>\n SFExtensions(\n props,\n { sfp },\n { dualBrandSelectElements, setDualBrandSelectElements, setSelectedBrandValue, issuingCountryCode, setIssuingCountryCode }\n ),\n [dualBrandSelectElements, issuingCountryCode]\n );\n\n /**\n * EXPECTED METHODS ON SecuredFields.this\n */\n this.processBinLookupResponse = (binLookupResponse: BinLookupResponse, isReset: boolean) => {\n extensions.processBinLookup(binLookupResponse, isReset);\n };\n\n this.dualBrandingChangeHandler = extensions.handleDualBrandSelection;\n\n /**\n * EFFECT HOOKS\n */\n useEffect(() => {\n // componentDidMount\n this.setFocusOn = sfp.current.setFocusOn;\n this.updateStyles = sfp.current.updateStyles;\n this.showValidation = sfp.current.showValidation;\n this.handleUnsupportedCard = sfp.current.handleUnsupportedCard;\n\n // componentWillUnmount\n return () => {\n sfp.current.destroy();\n };\n }, []);\n\n /**\n * Main 'componentDidUpdate' handler\n */\n useEffect(() => {\n const sfStateErrorsObj = sfp.current.mapErrorsToValidationRuleResult();\n\n const mappedErrors = { ...errors, ...sfStateErrorsObj }; // maps sfErrors\n\n props.onChange({\n data,\n valid,\n errors: mappedErrors,\n isValid: isSfpValid,\n selectedBrandValue\n });\n\n // Create an array of Validation error objects and send to callback\n if (Object.keys(mappedErrors).length) {\n const validationErrors: ValidationError[] = Object.entries(mappedErrors).map(([fieldType, error]) => {\n const valErr: ValidationError = {\n fieldType,\n ...(error ? (error as SFError) : { error: '', rootNode: this.props.rootNode })\n };\n return valErr;\n });\n this.props.onValidationError?.(validationErrors);\n }\n }, [data, valid, errors, selectedBrandValue]);\n\n /**\n * RENDER\n */\n // prettier-ignore\n return (\n <SecuredFieldsProvider\n ref={sfp}\n {...extractPropsForSFP(props)}\n type={props.brand}\n componentType={props.type}\n onChange={handleSecuredFieldsChange}\n onSubmitAnalytics={props.onSubmitAnalytics}\n exposeExpiryDate={false}\n disableIOSArrowKeys={null}\n render={() => null}\n />\n );\n}\n\nCustomCardInput.defaultProps = defaultProps;\n\nexport default CustomCardInput;\n\nconst extractPropsForSFP = (props: SecuredFieldsProps) => {\n return {\n autoFocus: props.autoFocus,\n brands: props.brands,\n brandsConfiguration: props.brandsConfiguration,\n clientKey: props.clientKey,\n forceCompat: props.forceCompat,\n // countryCode: props.countryCode, // only used for korean cards when koreanAuthenticationRequired is true\n i18n: props.i18n,\n implementationType: props.implementationType,\n keypadFix: props.keypadFix,\n legacyInputMode: props.legacyInputMode,\n loadingContext: props.loadingContext,\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 onBrand: props.onBrand,\n // onChange // set directly\n onConfigSuccess: props.onConfigSuccess,\n handleKeyPress: props.handleKeyPress,\n onError: props.onError,\n onFieldValid: props.onFieldValid,\n onFocus: props.onFocus,\n onLoad: props.onLoad,\n // render // set directly\n rootNode: props.rootNode,\n showWarnings: props.showWarnings,\n styles: props.styles,\n trimTrailingSeparator: props.trimTrailingSeparator,\n resources: props.resources,\n maskSecurityCode: props.maskSecurityCode,\n placeholders: props.placeholders\n };\n};\n"],"names":["CustomCardInput","props","sfp","useRef","errors","setErrors","useState","valid","setValid","data","setData","isSfpValid","setIsSfpValid","issuingCountryCode","setIssuingCountryCode","dualBrandSelectElements","setDualBrandSelectElements","selectedBrandValue","setSelectedBrandValue","extensions","useMemo","SFExtensions","this","processBinLookupResponse","binLookupResponse","isReset","processBinLookup","dualBrandingChangeHandler","handleDualBrandSelection","useEffect","setFocusOn","current","updateStyles","showValidation","handleUnsupportedCard","destroy","sfStateErrorsObj","mapErrorsToValidationRuleResult","mappedErrors","onChange","isValid","Object","keys","length","validationErrors","entries","map","fieldType","error","rootNode","onValidationError","h","SecuredFieldsProvider","ref","extractPropsForSFP","type","brand","componentType","sfState","onSubmitAnalytics","exposeExpiryDate","disableIOSArrowKeys","render","defaultProps","onError","autoFocus","brands","brandsConfiguration","clientKey","forceCompat","i18n","implementationType","keypadFix","legacyInputMode","loadingContext","minimumExpiryDate","onAdditionalSFConfig","onAdditionalSFRemoved","onAllValid","onAutoComplete","onBinValue","onBrand","onConfigSuccess","handleKeyPress","onFieldValid","onFocus","onLoad","showWarnings","styles","trimTrailingSeparator","resources","maskSecurityCode","placeholders"],"mappings":"qUAyDA,SAASA,EAAgBC,GACrB,MAAMC,EAAMC,EAAO,OAEZC,EAAQC,GAAaC,EAAS,CAAA,IAC9BC,EAAOC,GAAYF,EAAS,CAAA,IAC5BG,EAAMC,GAAWJ,EAAS,CAAA,IAE1BK,EAAYC,GAAiBN,GAAS,IAEtCO,EAAoBC,GAAyBR,EAAS,OAEtDS,EAAyBC,GAA8BV,EAAS,KAChEW,EAAoBC,GAAyBZ,EAAS,IAWvDa,EAAaC,EACf,IACIC,EACIpB,EACA,CAAEC,OACF,CAAEa,0BAAyBC,6BAA4BE,wBAAuBL,qBAAoBC,0BAE1G,CAACC,EAAyBF,IA6D9B,OAvDAS,KAAKC,yBAA2B,CAACC,EAAsCC,KACnEN,EAAWO,iBAAiBF,EAAmBC,IAGnDH,KAAKK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MrE,EAAMqE,KACZC,mBAAoBtE,EAAMsE,mBAC1BC,UAAWvE,EAAMuE,UACjBC,gBAAiBxE,EAAMwE,gBACvBC,eAAgBzE,EAAMyE,eACtBC,kBAAmB1E,EAAM0E,kBACzBC,qBAAsB3E,EAAM2E,qBAC5BC,sBAAuB5E,EAAM4E,sBAC7BC,WAAY7E,EAAM6E,WAClBC,eAAgB9E,EAAM8E,eACtBC,WAAY/E,EAAM+E,WAClBC,QAAShF,EAAMgF,QAEfC,gBAAiBjF,EAAMiF,gBACvBC,eAAgBlF,EAAMkF,eACtBnB,QAAS/D,EAAM+D,QACfoB,aAAcnF,EAAMmF,aACpBC,QAASpF,EAAMoF,QACfC,OAAQrF,EAAMqF,OAEdrC,SAAUhD,EAAMgD,SAChBsC,aAActF,EAAMsF,aACpBC,OAAQvF,EAAMuF,OACdC,sBAAuBxF,EAAMwF,sBAC7BC,UAAWzF,EAAMyF,UACjBC,iBAAkB1F,EAAM0F,iBACxBC,aAAc3F,EAAM2F"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{Component as t,createElement as e}from"../../../external/preact/dist/preact.js";import r from"../../internal/SecuredFields/SFP/SecuredFieldsProvider.js";import s from"../../internal/Alert/Alert.js";import a from"./GiftcardResult.js";import{useCoreContext as o}from"../../../core/Context/CoreProvider.js";import{GIFT_CARD as i}from"../../internal/SecuredFields/lib/constants.js";import{GiftCardFields as n}from"./GiftcardFields.js";import{useSRPanelForGiftcardErrors as c}from"./useSRPanelForGiftcardErrors.js";import{useAmount as l}from"../../../core/Context/AmountProvider.js";function d(t,e,r){return e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}class
|
|
1
|
+
import{Component as t,createElement as e}from"../../../external/preact/dist/preact.js";import r from"../../internal/SecuredFields/SFP/SecuredFieldsProvider.js";import s from"../../internal/Alert/Alert.js";import a from"./GiftcardResult.js";import{useCoreContext as o}from"../../../core/Context/CoreProvider.js";import{GIFT_CARD as i}from"../../internal/SecuredFields/lib/constants.js";import{GiftCardFields as n}from"./GiftcardFields.js";import{useSRPanelForGiftcardErrors as c}from"./useSRPanelForGiftcardErrors.js";import{useAmount as l}from"../../../core/Context/AmountProvider.js";function d(t,e,r){return e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}class p extends t{generateBalanceCheckErrors(t){const e={};return null===t||(e.encryptedCardNumber={isValid:!1,errorMessage:`error.giftcard.${t}`,error:t}),e}isBalanceCheckError(t){return["no-balance","card-error","currency-error"].includes(t)}render(t,{focusedElement:n,balance:d,transactionLimit:p,isValidating:u,transformedErrors:h}){const{i18n:m}=o(),{amount:f}=l();c({errors:h,isValidating:u,setIsValidating:this.setIsValidating,sfp:this.sfp});const g=p?.value<d?.value?p:d;if(g&&g?.value>=f?.value)return e(a,{balance:d,transactionLimit:p,makePayment:t.makePayment,status:this.state.status,makeBalanceCheck:t.makeBalanceCheck,showPayButton:this.props.showPayButton,payButton:this.props.payButton});const y=t=>t.errors.encryptedCardNumber?m.get(t.errors.encryptedCardNumber):h.encryptedCardNumber?m.get(h.encryptedCardNumber.errorMessage):null;return e("div",{className:"adyen-checkout__giftcard"},"error"===this.state.status&&e(s,{icon:"cross"},m.get("error.message.unknown")),e(r,{...this.props,clientKey:this.props.clientKey,loadingContext:this.props.loadingContext,ref:t=>{this.sfp=t},onChange:this.onChange,onFocus:this.handleFocus,onSubmitAnalytics:t.onSubmitAnalytics,type:i,componentType:t.type,render:({setRootNode:t,setFocusOn:e},r)=>this.props.fieldsLayoutComponent({i18n:m,pinRequired:this.props.pinRequired,focusedElement:n,getCardErrorMessage:y,setRootNode:t,setFocusOn:e,sfpState:r})}),this.props.showPayButton&&this.props.payButton({status:this.state.status,onClick:this.props.makeBalanceCheck,label:m.get("applyGiftcard")}))}constructor(...t){super(...t),d(this,"state",{status:"ready",data:{},balance:null,transactionLimit:null,focusedElement:!1,isValid:!1,sfpState:{},isValidating:!1,transformedErrors:{}}),d(this,"sfp",void 0),d(this,"mapErrorsToValidationObjects",()=>this.sfp?this.sfp.mapErrorsToValidationRuleResult():{}),d(this,"updateTransformedErrors",t=>{const e={...this.mapErrorsToValidationObjects(),...t};this.setState({transformedErrors:e})}),d(this,"onChange",t=>{this.setState({sfpState:t},()=>this.updateTransformedErrors()),this.props.onChange({data:t.data,isValid:t.isSfpValid})}),d(this,"handleFocus",t=>{this.setState({focusedElement:t.currentFocusObject});!0===t.focus?this.props.onFocus(t):this.props.onBlur(t)}),d(this,"setBalance",({balance:t,transactionLimit:e})=>{this.setState({balance:t,transactionLimit:e})}),d(this,"setBalanceCheckErrors",t=>{if(this.isBalanceCheckError(t)){const e=this.generateBalanceCheckErrors(t);this.updateTransformedErrors(e)}}),d(this,"showValidation",()=>{this.setState({isValidating:!0}),this.sfp?.showValidation()}),d(this,"setIsValidating",t=>{this.setState({isValidating:t})})}}d(p,"defaultProps",{pinRequired:!0,expiryDateRequired:!1,onChange:()=>{},onFocus:()=>{},onBlur:()=>{},fieldsLayoutComponent:n});export{p as default};
|
|
2
2
|
//# sourceMappingURL=GiftcardComponent.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"GiftcardComponent.js","sources":["../../../../../src/components/Giftcard/components/GiftcardComponent.tsx"],"sourcesContent":["import { Component, FunctionComponent, h } from 'preact';\nimport SecuredFieldsProvider from '../../internal/SecuredFields/SFP/SecuredFieldsProvider';\nimport Alert from '../../internal/Alert';\nimport GiftcardResult from './GiftcardResult';\nimport { useCoreContext } from '../../../core/Context/CoreProvider';\nimport { GIFT_CARD } from '../../internal/SecuredFields/lib/constants';\nimport { GiftCardFields } from './GiftcardFields';\nimport { GiftcardFieldsProps, Placeholders } from './types';\nimport { useSRPanelForGiftcardErrors } from './useSRPanelForGiftcardErrors';\nimport { GiftCardBalanceCheckErrorType } from '../types';\nimport { PayButtonProps } from '../../internal/PayButton/PayButton';\nimport { useAmount } from '../../../core/Context/AmountProvider';\nimport type { AbstractAnalyticsEvent } from '../../../core/Analytics/events/AbstractAnalyticsEvent';\n\ninterface GiftcardComponentProps {\n onChange: (state) => void;\n onFocus: (event) => void;\n onBlur: (event) => void;\n makeBalanceCheck: (event) => void;\n makePayment: (event) => void;\n showPayButton: boolean;\n payButton: (props: PayButtonProps) => h.JSX.Element;\n pinRequired: boolean;\n expiryDateRequired?: boolean;\n fieldsLayoutComponent: FunctionComponent<GiftcardFieldsProps>;\n placeholders?: Placeholders;\n handleKeyPress?: (o: KeyboardEvent) => void;\n onSubmitAnalytics?: (event: AbstractAnalyticsEvent) => void;\n}\n\nclass Giftcard extends Component<Readonly<GiftcardComponentProps>> {\n public state = {\n status: 'ready',\n data: {},\n balance: null,\n transactionLimit: null,\n focusedElement: false,\n isValid: false,\n sfpState: {},\n isValidating: false,\n transformedErrors: {}\n };\n\n public static readonly defaultProps = {\n pinRequired: true,\n expiryDateRequired: false,\n onChange: () => {},\n onFocus: () => {},\n onBlur: () => {},\n fieldsLayoutComponent: GiftCardFields\n };\n\n public sfp: SecuredFieldsProvider;\n\n /**\n * Maps string error codes from SecuredFields to validation rule objects\n */\n public mapErrorsToValidationObjects = () => {\n // Use the sfp reference to call mapErrorsToValidationRuleResult\n if (!this.sfp) return {};\n return this.sfp.mapErrorsToValidationRuleResult();\n };\n\n private updateTransformedErrors = (balanceCheckErrors?: Record<string, any>) => {\n const transformedErrors = this.mapErrorsToValidationObjects();\n\n const mergedErrors = { ...transformedErrors, ...balanceCheckErrors };\n\n this.setState({ transformedErrors: mergedErrors });\n };\n\n public onChange = sfpState => {\n this.setState({ sfpState }, () => this.updateTransformedErrors());\n\n this.props.onChange({\n data: sfpState.data,\n isValid: sfpState.isSfpValid\n });\n };\n\n public handleFocus = e => {\n this.setState({ focusedElement: e.currentFocusObject });\n\n const isFocused = e.focus === true;\n if (isFocused) {\n this.props.onFocus(e);\n } else {\n this.props.onBlur(e);\n }\n };\n\n public setBalance = ({ balance, transactionLimit }) => {\n this.setState({ balance, transactionLimit });\n };\n\n /**\n * Generates balance check errors in the same format as SFP errors\n * Compatible with the transformedErrors structure\n */\n private generateBalanceCheckErrors(errorType?: GiftCardBalanceCheckErrorType | null): Record<string, any> {\n const balanceCheckErrors: Record<string, any> = {};\n\n // This is the field that the error is associated with, only used for SR logic\n const fieldToAnnounce = 'encryptedCardNumber';\n\n // If errorType is null, clear errors\n if (errorType === null) {\n return balanceCheckErrors;\n }\n\n // Create error in the same format as SFP errors for consistency\n balanceCheckErrors[fieldToAnnounce] = {\n isValid: false,\n errorMessage: `error.giftcard.${errorType}`,\n error: errorType\n };\n\n return balanceCheckErrors;\n }\n\n /**\n * Checks if a status represents a balance check error\n */\n private isBalanceCheckError(status: string): boolean {\n return ['no-balance', 'card-error', 'currency-error'].includes(status);\n }\n\n /**\n * Method called by GiftcardElement to set balance check errors only\n */\n public setBalanceCheckErrors = (errorType: GiftCardBalanceCheckErrorType | null): void => {\n // Check if the errors should be displayed\n if (this.isBalanceCheckError(errorType)) {\n // Generate balance check errors in the style of useForm\n // This is usefull because then we can use the same logic for SF and balance check errors\n // Also we can use the same logic for SRPanel errors\n const balanceCheckErrors = this.generateBalanceCheckErrors(errorType);\n this.updateTransformedErrors(balanceCheckErrors);\n }\n };\n\n public showValidation = () => {\n this.setState({ isValidating: true });\n\n // Validate SecuredFields\n this.sfp?.showValidation();\n };\n\n public setIsValidating = (val: boolean) => {\n this.setState({ isValidating: val });\n };\n\n render(props, { focusedElement, balance, transactionLimit, isValidating, transformedErrors }) {\n const { i18n } = useCoreContext();\n const { amount } = useAmount();\n\n // Handle SRPanel errors in render with transformed error objects\n useSRPanelForGiftcardErrors({\n errors: transformedErrors,\n isValidating,\n setIsValidating: this.setIsValidating,\n sfp: this.sfp\n });\n\n const transactionAmount = transactionLimit?.value < balance?.value ? transactionLimit : balance;\n const hasEnoughBalance = transactionAmount?.value >= amount?.value;\n\n if (transactionAmount && hasEnoughBalance) {\n return (\n <GiftcardResult\n balance={balance}\n transactionLimit={transactionLimit}\n makePayment={props.makePayment}\n status={this.state.status}\n makeBalanceCheck={props.makeBalanceCheck}\n showPayButton={this.props.showPayButton}\n payButton={this.props.payButton}\n />\n );\n }\n\n const getCardErrorMessage = sfpState => {\n if (sfpState.errors.encryptedCardNumber) return i18n.get(sfpState.errors.encryptedCardNumber);\n\n // This logic is a bit of a hack, but it's the only way to get the error message for balance check errors\n // In the future we should move this logic to useForm\n if (transformedErrors.encryptedCardNumber) {\n return i18n.get(transformedErrors.encryptedCardNumber.errorMessage);\n }\n\n return null;\n };\n\n return (\n <div className=\"adyen-checkout__giftcard\">\n {this.state.status === 'error' && <Alert icon={'cross'}>{i18n.get('error.message.unknown')}</Alert>}\n\n <SecuredFieldsProvider\n {...this.props}\n ref={ref => {\n this.sfp = ref;\n }}\n onChange={this.onChange}\n onFocus={this.handleFocus}\n onSubmitAnalytics={props.onSubmitAnalytics}\n type={GIFT_CARD}\n componentType={props.type}\n render={({ setRootNode, setFocusOn }, sfpState) =>\n this.props.fieldsLayoutComponent({\n i18n: i18n,\n pinRequired: this.props.pinRequired,\n focusedElement: focusedElement,\n getCardErrorMessage: getCardErrorMessage,\n setRootNode: setRootNode,\n setFocusOn: setFocusOn,\n sfpState: sfpState\n })\n }\n />\n\n {this.props.showPayButton &&\n this.props.payButton({\n status: this.state.status,\n onClick: this.props.makeBalanceCheck,\n label: i18n.get('applyGiftcard')\n })}\n </div>\n );\n }\n}\n\nexport default Giftcard;\n"],"names":["Giftcard","Component","generateBalanceCheckErrors","errorType","balanceCheckErrors","isValid","errorMessage","error","isBalanceCheckError","status","includes","render","props","focusedElement","balance","transactionLimit","isValidating","transformedErrors","i18n","useCoreContext","amount","useAmount","useSRPanelForGiftcardErrors","errors","setIsValidating","this","sfp","transactionAmount","value","h","GiftcardResult","makePayment","state","makeBalanceCheck","showPayButton","payButton","getCardErrorMessage","sfpState","encryptedCardNumber","get","div","className","Alert","icon","SecuredFieldsProvider","ref","onChange","onFocus","handleFocus","onSubmitAnalytics","type","GIFT_CARD","componentType","setRootNode","setFocusOn","fieldsLayoutComponent","pinRequired","onClick","label","super","args","_define_property","data","mapErrorsToValidationObjects","mapErrorsToValidationRuleResult","updateTransformedErrors","mergedErrors","setState","isSfpValid","e","currentFocusObject","focus","onBlur","setBalance","setBalanceCheckErrors","showValidation","val","defaultProps","expiryDateRequired","GiftCardFields"],"mappings":"isBA8BA,MAAMA,UAAiBC,EAqEXC,0BAAAA,CAA2BC,GAC/B,MAAMC,EAA0C,CAAA,EAMhD,OAAkB,OAAdD,IAKJC,sBAAsC,CAClCC,SAAS,EACTC,aAAc,kBAAkBH,IAChCI,MAAOJ,IAPAC,CAWf,CAKQI,mBAAAA,CAAoBC,GACxB,MAAO,CAAC,aAAc,aAAc,kBAAkBC,SAASD,EACnE,CA2BAE,MAAAA,CAAOC,GAAOC,eAAEA,EAAcC,QAAEA,EAAOC,iBAAEA,EAAgBC,aAAEA,EAAYC,kBAAEA,IACrE,MAAMC,KAAEA,GAASC,KACXC,OAAEA,GAAWC,IAGnBC,EAA4B,CACxBC,OAAQN,EACRD,eACAQ,gBAAiBC,KAAKD,gBACtBE,IAAKD,KAAKC,MAGd,MAAMC,EAAoBZ,GAAkBa,MAAQd,GAASc,MAAQb,EAAmBD,EAGxF,GAAIa,GAFqBA,GAAmBC,OAASR,GAAQQ,MAGzD,OACIC,EAACC,EAAAA,CACGhB,QAASA,EACTC,iBAAkBA,EAClBgB,YAAanB,EAAMmB,YACnBtB,OAAQgB,KAAKO,MAAMvB,OACnBwB,iBAAkBrB,EAAMqB,iBACxBC,cAAeT,KAAKb,MAAMsB,cAC1BC,UAAWV,KAAKb,MAAMuB,YAKlC,MAAMC,EAAsBC,GACpBA,EAASd,OAAOe,oBAA4BpB,EAAKqB,IAAIF,EAASd,OAAOe,qBAIrErB,EAAkBqB,oBACXpB,EAAKqB,IAAItB,EAAkBqB,oBAAoBhC,cAGnD,KAGX,OACIuB,EAACW,MAAAA,CAAIC,UAAU,4BACY,UAAtBhB,KAAKO,MAA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,CAAEtD,eAAgBwD,EAAEC,sBAEJ,IAAZD,EAAEE,MAEhB9C,KAAKb,MAAMmC,QAAQsB,GAEnB5C,KAAKb,MAAM4D,OAAOH,KAI1BR,OAAOY,aAAa,EAAG3D,UAASC,uBAC5BU,KAAK0C,SAAS,CAAErD,UAASC,uBAsC7B8C,EAAApC,KAAOiD,wBAAyBvE,IAE5B,GAAIsB,KAAKjB,oBAAoBL,GAAY,CAIrC,MAAMC,EAAqBqB,KAAKvB,2BAA2BC,GAC3DsB,KAAKwC,wBAAwB7D,EACjC,IAGJyD,OAAOc,iBAAiB,KACpBlD,KAAK0C,SAAS,CAAEnD,cAAc,IAG9BS,KAAKC,KAAKiD,mBAGdd,EAAApC,KAAOD,kBAAmBoD,IACtBnD,KAAK0C,SAAS,CAAEnD,aAAc4D,OA1GlCf,EAbE7D,EAaqB6E,eAAe,CAClCrB,aAAa,EACbsB,oBAAoB,EACpBhC,SAAU,OACVC,QAAS,OACTyB,OAAQ,OACRjB,sBAAuBwB"}
|
|
1
|
+
{"version":3,"file":"GiftcardComponent.js","sources":["../../../../../src/components/Giftcard/components/GiftcardComponent.tsx"],"sourcesContent":["import { Component, FunctionComponent, h } from 'preact';\nimport SecuredFieldsProvider from '../../internal/SecuredFields/SFP/SecuredFieldsProvider';\nimport Alert from '../../internal/Alert';\nimport GiftcardResult from './GiftcardResult';\nimport { useCoreContext } from '../../../core/Context/CoreProvider';\nimport { GIFT_CARD } from '../../internal/SecuredFields/lib/constants';\nimport { GiftCardFields } from './GiftcardFields';\nimport { GiftcardFieldsProps, Placeholders } from './types';\nimport { useSRPanelForGiftcardErrors } from './useSRPanelForGiftcardErrors';\nimport { GiftCardBalanceCheckErrorType } from '../types';\nimport { PayButtonProps } from '../../internal/PayButton/PayButton';\nimport { useAmount } from '../../../core/Context/AmountProvider';\nimport type { AbstractAnalyticsEvent } from '../../../core/Analytics/events/AbstractAnalyticsEvent';\nimport type { SFPProps } from '../../internal/SecuredFields/SFP/types';\n\ninterface GiftcardComponentProps extends Partial<Pick<SFPProps, 'clientKey' | 'loadingContext'>> {\n onChange: (state) => void;\n onFocus: (event) => void;\n onBlur: (event) => void;\n makeBalanceCheck: (event) => void;\n makePayment: (event) => void;\n showPayButton: boolean;\n payButton: (props: PayButtonProps) => h.JSX.Element;\n pinRequired: boolean;\n expiryDateRequired?: boolean;\n fieldsLayoutComponent: FunctionComponent<GiftcardFieldsProps>;\n placeholders?: Placeholders;\n handleKeyPress?: (o: KeyboardEvent) => void;\n onSubmitAnalytics?: (event: AbstractAnalyticsEvent) => void;\n}\n\nclass Giftcard extends Component<Readonly<GiftcardComponentProps>> {\n public state = {\n status: 'ready',\n data: {},\n balance: null,\n transactionLimit: null,\n focusedElement: false,\n isValid: false,\n sfpState: {},\n isValidating: false,\n transformedErrors: {}\n };\n\n public static readonly defaultProps = {\n pinRequired: true,\n expiryDateRequired: false,\n onChange: () => {},\n onFocus: () => {},\n onBlur: () => {},\n fieldsLayoutComponent: GiftCardFields\n };\n\n public sfp: SecuredFieldsProvider;\n\n /**\n * Maps string error codes from SecuredFields to validation rule objects\n */\n public mapErrorsToValidationObjects = () => {\n // Use the sfp reference to call mapErrorsToValidationRuleResult\n if (!this.sfp) return {};\n return this.sfp.mapErrorsToValidationRuleResult();\n };\n\n private updateTransformedErrors = (balanceCheckErrors?: Record<string, any>) => {\n const transformedErrors = this.mapErrorsToValidationObjects();\n\n const mergedErrors = { ...transformedErrors, ...balanceCheckErrors };\n\n this.setState({ transformedErrors: mergedErrors });\n };\n\n public onChange = sfpState => {\n this.setState({ sfpState }, () => this.updateTransformedErrors());\n\n this.props.onChange({\n data: sfpState.data,\n isValid: sfpState.isSfpValid\n });\n };\n\n public handleFocus = e => {\n this.setState({ focusedElement: e.currentFocusObject });\n\n const isFocused = e.focus === true;\n if (isFocused) {\n this.props.onFocus(e);\n } else {\n this.props.onBlur(e);\n }\n };\n\n public setBalance = ({ balance, transactionLimit }) => {\n this.setState({ balance, transactionLimit });\n };\n\n /**\n * Generates balance check errors in the same format as SFP errors\n * Compatible with the transformedErrors structure\n */\n private generateBalanceCheckErrors(errorType?: GiftCardBalanceCheckErrorType | null): Record<string, any> {\n const balanceCheckErrors: Record<string, any> = {};\n\n // This is the field that the error is associated with, only used for SR logic\n const fieldToAnnounce = 'encryptedCardNumber';\n\n // If errorType is null, clear errors\n if (errorType === null) {\n return balanceCheckErrors;\n }\n\n // Create error in the same format as SFP errors for consistency\n balanceCheckErrors[fieldToAnnounce] = {\n isValid: false,\n errorMessage: `error.giftcard.${errorType}`,\n error: errorType\n };\n\n return balanceCheckErrors;\n }\n\n /**\n * Checks if a status represents a balance check error\n */\n private isBalanceCheckError(status: string): boolean {\n return ['no-balance', 'card-error', 'currency-error'].includes(status);\n }\n\n /**\n * Method called by GiftcardElement to set balance check errors only\n */\n public setBalanceCheckErrors = (errorType: GiftCardBalanceCheckErrorType | null): void => {\n // Check if the errors should be displayed\n if (this.isBalanceCheckError(errorType)) {\n // Generate balance check errors in the style of useForm\n // This is usefull because then we can use the same logic for SF and balance check errors\n // Also we can use the same logic for SRPanel errors\n const balanceCheckErrors = this.generateBalanceCheckErrors(errorType);\n this.updateTransformedErrors(balanceCheckErrors);\n }\n };\n\n public showValidation = () => {\n this.setState({ isValidating: true });\n\n // Validate SecuredFields\n this.sfp?.showValidation();\n };\n\n public setIsValidating = (val: boolean) => {\n this.setState({ isValidating: val });\n };\n\n render(props, { focusedElement, balance, transactionLimit, isValidating, transformedErrors }) {\n const { i18n } = useCoreContext();\n const { amount } = useAmount();\n\n // Handle SRPanel errors in render with transformed error objects\n useSRPanelForGiftcardErrors({\n errors: transformedErrors,\n isValidating,\n setIsValidating: this.setIsValidating,\n sfp: this.sfp\n });\n\n const transactionAmount = transactionLimit?.value < balance?.value ? transactionLimit : balance;\n const hasEnoughBalance = transactionAmount?.value >= amount?.value;\n\n if (transactionAmount && hasEnoughBalance) {\n return (\n <GiftcardResult\n balance={balance}\n transactionLimit={transactionLimit}\n makePayment={props.makePayment}\n status={this.state.status}\n makeBalanceCheck={props.makeBalanceCheck}\n showPayButton={this.props.showPayButton}\n payButton={this.props.payButton}\n />\n );\n }\n\n const getCardErrorMessage = sfpState => {\n if (sfpState.errors.encryptedCardNumber) return i18n.get(sfpState.errors.encryptedCardNumber);\n\n // This logic is a bit of a hack, but it's the only way to get the error message for balance check errors\n // In the future we should move this logic to useForm\n if (transformedErrors.encryptedCardNumber) {\n return i18n.get(transformedErrors.encryptedCardNumber.errorMessage);\n }\n\n return null;\n };\n\n return (\n <div className=\"adyen-checkout__giftcard\">\n {this.state.status === 'error' && <Alert icon={'cross'}>{i18n.get('error.message.unknown')}</Alert>}\n\n <SecuredFieldsProvider\n {...this.props}\n clientKey={this.props.clientKey}\n loadingContext={this.props.loadingContext}\n ref={ref => {\n this.sfp = ref;\n }}\n onChange={this.onChange}\n onFocus={this.handleFocus}\n onSubmitAnalytics={props.onSubmitAnalytics}\n type={GIFT_CARD}\n componentType={props.type}\n render={({ setRootNode, setFocusOn }, sfpState) =>\n this.props.fieldsLayoutComponent({\n i18n: i18n,\n pinRequired: this.props.pinRequired,\n focusedElement: focusedElement,\n getCardErrorMessage: getCardErrorMessage,\n setRootNode: setRootNode,\n setFocusOn: setFocusOn,\n sfpState: sfpState\n })\n }\n />\n\n {this.props.showPayButton &&\n this.props.payButton({\n status: this.state.status,\n onClick: this.props.makeBalanceCheck,\n label: i18n.get('applyGiftcard')\n })}\n </div>\n );\n }\n}\n\nexport default Giftcard;\n"],"names":["Giftcard","Component","generateBalanceCheckErrors","errorType","balanceCheckErrors","isValid","errorMessage","error","isBalanceCheckError","status","includes","render","props","focusedElement","balance","transactionLimit","isValidating","transformedErrors","i18n","useCoreContext","amount","useAmount","useSRPanelForGiftcardErrors","errors","setIsValidating","this","sfp","transactionAmount","value","h","GiftcardResult","makePayment","state","makeBalanceCheck","showPayButton","payButton","getCardErrorMessage","sfpState","encryptedCardNumber","get","div","className","Alert","icon","SecuredFieldsProvider","clientKey","loadingContext","ref","onChange","onFocus","handleFocus","onSubmitAnalytics","type","GIFT_CARD","componentType","setRootNode","setFocusOn","fieldsLayoutComponent","pinRequired","onClick","label","super","args","_define_property","data","mapErrorsToValidationObjects","mapErrorsToValidationRuleResult","updateTransformedErrors","mergedErrors","setState","isSfpValid","e","currentFocusObject","focus","onBlur","setBalance","setBalanceCheckErrors","showValidation","val","defaultProps","expiryDateRequired","GiftCardFields"],"mappings":"isBA+BA,MAAMA,UAAiBC,EAqEXC,0BAAAA,CAA2BC,GAC/B,MAAMC,EAA0C,CAAA,EAMhD,OAAkB,OAAdD,IAKJC,sBAAsC,CAClCC,SAAS,EACTC,aAAc,kBAAkBH,IAChCI,MAAOJ,IAPAC,CAWf,CAKQI,mBAAAA,CAAoBC,GACxB,MAAO,CAAC,aAAc,aAAc,kBAAkBC,SAASD,EACnE,CA2BAE,MAAAA,CAAOC,GAAOC,eAAEA,EAAcC,QAAEA,EAAOC,iBAAEA,EAAgBC,aAAEA,EAAYC,kBAAEA,IACrE,MAAMC,KAAEA,GAASC,KACXC,OAAEA,GAAWC,IAGnBC,EAA4B,CACxBC,OAAQN,EACRD,eACAQ,gBAAiBC,KAAKD,gBACtBE,IAAKD,KAAKC,MAGd,MAAMC,EAAoBZ,GAAkBa,MAAQd,GAASc,MAAQb,EAAmBD,EAGxF,GAAIa,GAFqBA,GAAmBC,OAASR,GAAQQ,MAGzD,OACIC,EAACC,EAAAA,CACGhB,QAASA,EACTC,iBAAkBA,EAClBgB,YAAanB,EAAMmB,YACnBtB,OAAQgB,KAAKO,MAAMvB,OACnBwB,iBAAkBrB,EAAMqB,iBACxBC,cAAeT,KAAKb,MAAMsB,cAC1BC,UAAWV,KAAKb,MAAMuB,YAKlC,MAAMC,EAAsBC,GACpBA,EAASd,OAAOe,oBAA4BpB,EAAKqB,IAAIF,EAASd,OAAOe,qBAIrErB,EAAkBqB,oBACXpB,EAAKqB,IAAItB,EAAkBqB,oBAAoBhC,cAGnD,KAGX,OACIuB,EAACW,MAAA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AAMoC,SAAS,CAChBgB,KAAM3B,EAAS2B,KACf3D,QAASgC,EAASiC,eAI1BP,EAAAtC,KAAOyB,cAAcqB,IACjB9C,KAAK4C,SAAS,CAAExD,eAAgB0D,EAAEC,sBAEJ,IAAZD,EAAEE,MAEhBhD,KAAKb,MAAMqC,QAAQsB,GAEnB9C,KAAKb,MAAM8D,OAAOH,KAI1BR,OAAOY,aAAa,EAAG7D,UAASC,uBAC5BU,KAAK4C,SAAS,CAAEvD,UAASC,uBAsC7BgD,EAAAtC,KAAOmD,wBAAyBzE,IAE5B,GAAIsB,KAAKjB,oBAAoBL,GAAY,CAIrC,MAAMC,EAAqBqB,KAAKvB,2BAA2BC,GAC3DsB,KAAK0C,wBAAwB/D,EACjC,IAGJ2D,OAAOc,iBAAiB,KACpBpD,KAAK4C,SAAS,CAAErD,cAAc,IAG9BS,KAAKC,KAAKmD,mBAGdd,EAAAtC,KAAOD,kBAAmBsD,IACtBrD,KAAK4C,SAAS,CAAErD,aAAc8D,OA1GlCf,EAbE/D,EAaqB+E,eAAe,CAClCrB,aAAa,EACbsB,oBAAoB,EACpBhC,SAAU,OACVC,QAAS,OACTyB,OAAQ,OACRjB,sBAAuBwB"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{render as t}from"../../../external/preact/dist/preact.js";import e from"../../../utils/uuid.js";import
|
|
1
|
+
import{render as t}from"../../../external/preact/dist/preact.js";import e from"../../../utils/uuid.js";import o from"../../../core/Errors/AdyenCheckoutError.js";import{NO_CHECKOUT_ATTEMPT_ID as r}from"../../../core/Analytics/constants.js";import{on as s,off as n}from"../../../utils/listenerUtils.js";import{createSdkData as i}from"../../../utils/createSdkData.js";import a from"../../components-name-map.js";import{PAYMENT_METHOD_BEHAVIOR as h}from"../../../core/config.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}class u{buildElementProps(t){this.props=this.formatProps({...this.constructor.defaultProps,...t})}formatProps(t){return t}formatData(){return{}}submitAnalytics(t){return null}handleKeyPress(t){return null}setState(t){this.state={...this.state,...t}}get data(){const t=this.state.order||this.props.order,e=this.formatData(),o=Boolean(a(e.paymentMethod?.type)),s=this.core.modules.risk.data,n=this.core.modules.analytics.checkoutAttemptId??r,c=o?h.NATIVE:h.GENERIC,u=i(n,s,c);return e.paymentMethod&&n&&(e.paymentMethod.checkoutAttemptId=n),e.paymentMethod&&u&&(e.paymentMethod.sdkData=u),{...s&&{riskData:{clientData:s}},...t&&{order:{orderData:t.orderData,pspReference:t.pspReference}},...e,clientStateDataIndicator:!0}}activate(){}render(){throw new Error("Payment method cannot be rendered.")}mount(e){const o="string"==typeof e?document.querySelector(e):e;if(!o)throw new Error("Component could not mount. Root node was not found.");return this._node&&this.unmount(),this._node=o,s(this._node,"keypress",this.handleKeyPress,!1),this._component=this.render(),t(this._component,o),this}update(t){return this.props=this.formatProps({...this.props,...t}),this.state={},this.unmount().mount(this._node)}unmount(){return n(this._node,"keypress",this.handleKeyPress),this._node&&t(null,this._node),this}remove(){this.unmount(),this.core&&this.core.remove(this)}constructor(t,r){c(this,"_id",`${this.constructor.type}-${e()}`),c(this,"core",void 0),c(this,"props",void 0),c(this,"state",{}),c(this,"_component",void 0),c(this,"_node",null);const s=function(t){return!!t&&("function"==typeof t.initialize&&"function"==typeof t.createFromAction)}(t);if(!s)throw new o("IMPLEMENTATION_ERROR",`Trying to initialise the component '${this.constructor.type}' without a reference to an instance of AdyenCheckout`);this.core=t,this.buildElementProps(r),this.handleKeyPress=this.handleKeyPress.bind(this)}}c(u,"defaultProps",{});export{u as default};
|
|
2
2
|
//# sourceMappingURL=BaseElement.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BaseElement.js","sources":["../../../../../src/components/internal/BaseElement/BaseElement.ts"],"sourcesContent":["import { ComponentChild, h, render } from 'preact';\nimport uuid from '../../../utils/uuid';\nimport AdyenCheckoutError from '../../../core/Errors/AdyenCheckoutError';\nimport { NO_CHECKOUT_ATTEMPT_ID } from '../../../core/Analytics/constants';\nimport type { ICore } from '../../../core/types';\nimport type { BaseElementProps, IBaseElement } from './types';\nimport type { PaymentData } from '../../../types/global-types';\nimport { off, on } from '../../../utils/listenerUtils';\nimport { AbstractAnalyticsEvent } from '../../../core/Analytics/events/AbstractAnalyticsEvent';\nimport { createSdkData } from '../../../utils/createSdkData';\n\n/**\n * Verify if the first parameter is instance of Core.\n * We do not use 'instanceof' to avoid importing the Core class directly into this class.\n * @param checkout\n */\nfunction assertIsCoreInstance(checkout: ICore): checkout is ICore {\n if (!checkout) return false;\n const isCoreObject = typeof checkout.initialize === 'function' && typeof checkout.createFromAction === 'function';\n return isCoreObject;\n}\n\nabstract class BaseElement<P extends BaseElementProps> implements IBaseElement {\n public readonly _id = `${this.constructor['type']}-${uuid()}`;\n public readonly core: ICore;\n\n public props: P;\n public state: any = {};\n public _component;\n\n protected _node: HTMLElement = null;\n\n protected static readonly defaultProps = {};\n\n constructor(checkout: ICore, props?: P) {\n const isCoreInstance = assertIsCoreInstance(checkout);\n\n if (!isCoreInstance) {\n throw new AdyenCheckoutError(\n 'IMPLEMENTATION_ERROR',\n `Trying to initialise the component '${this.constructor['type']}' without a reference to an instance of AdyenCheckout`\n );\n }\n\n this.core = checkout;\n this.buildElementProps(props);\n\n this.handleKeyPress = this.handleKeyPress.bind(this);\n }\n\n protected buildElementProps(componentProps?: P) {\n this.props = this.formatProps({ ...this.constructor['defaultProps'], ...componentProps });\n }\n\n /**\n * Executed during creation of any payment element.\n * Gives a chance to any paymentMethod to format the props we're receiving.\n */\n protected formatProps(props: P) {\n return props;\n }\n\n /**\n * Executed on the `data` getter.\n * Returns the component data necessary for the /payments request\n */\n protected formatData(): any {\n return {};\n }\n\n /* eslint-disable-next-line */\n protected submitAnalytics(analyticsObj?: AbstractAnalyticsEvent) {\n return null;\n }\n\n /* eslint-disable-next-line */\n protected handleKeyPress(e: h.JSX.TargetedKeyboardEvent<HTMLInputElement>) {\n return null;\n }\n\n protected setState(newState: object): void {\n this.state = { ...this.state, ...newState };\n }\n\n /**\n * Returns the component payment data ready to submit to the Checkout API\n * Note: this does not ensure validity, check isValid first\n */\n public get data(): PaymentData {\n const order = this.state.order || this.props.order;\n const componentData = this.formatData();\n
|
|
1
|
+
{"version":3,"file":"BaseElement.js","sources":["../../../../../src/components/internal/BaseElement/BaseElement.ts"],"sourcesContent":["import { ComponentChild, h, render } from 'preact';\nimport uuid from '../../../utils/uuid';\nimport AdyenCheckoutError from '../../../core/Errors/AdyenCheckoutError';\nimport { NO_CHECKOUT_ATTEMPT_ID } from '../../../core/Analytics/constants';\nimport type { ICore } from '../../../core/types';\nimport type { BaseElementProps, IBaseElement } from './types';\nimport type { PaymentData } from '../../../types/global-types';\nimport { off, on } from '../../../utils/listenerUtils';\nimport { AbstractAnalyticsEvent } from '../../../core/Analytics/events/AbstractAnalyticsEvent';\nimport { createSdkData } from '../../../utils/createSdkData';\nimport getComponentNameOfPaymentType from '../../components-name-map';\nimport { PAYMENT_METHOD_BEHAVIOR } from '../../../core/config';\n\n/**\n * Verify if the first parameter is instance of Core.\n * We do not use 'instanceof' to avoid importing the Core class directly into this class.\n * @param checkout\n */\nfunction assertIsCoreInstance(checkout: ICore): checkout is ICore {\n if (!checkout) return false;\n const isCoreObject = typeof checkout.initialize === 'function' && typeof checkout.createFromAction === 'function';\n return isCoreObject;\n}\n\nabstract class BaseElement<P extends BaseElementProps> implements IBaseElement {\n public readonly _id = `${this.constructor['type']}-${uuid()}`;\n public readonly core: ICore;\n\n public props: P;\n public state: any = {};\n public _component;\n\n protected _node: HTMLElement = null;\n\n protected static readonly defaultProps = {};\n\n constructor(checkout: ICore, props?: P) {\n const isCoreInstance = assertIsCoreInstance(checkout);\n\n if (!isCoreInstance) {\n throw new AdyenCheckoutError(\n 'IMPLEMENTATION_ERROR',\n `Trying to initialise the component '${this.constructor['type']}' without a reference to an instance of AdyenCheckout`\n );\n }\n\n this.core = checkout;\n this.buildElementProps(props);\n\n this.handleKeyPress = this.handleKeyPress.bind(this);\n }\n\n protected buildElementProps(componentProps?: P) {\n this.props = this.formatProps({ ...this.constructor['defaultProps'], ...componentProps });\n }\n\n /**\n * Executed during creation of any payment element.\n * Gives a chance to any paymentMethod to format the props we're receiving.\n */\n protected formatProps(props: P) {\n return props;\n }\n\n /**\n * Executed on the `data` getter.\n * Returns the component data necessary for the /payments request\n */\n protected formatData(): any {\n return {};\n }\n\n /* eslint-disable-next-line */\n protected submitAnalytics(analyticsObj?: AbstractAnalyticsEvent) {\n return null;\n }\n\n /* eslint-disable-next-line */\n protected handleKeyPress(e: h.JSX.TargetedKeyboardEvent<HTMLInputElement>) {\n return null;\n }\n\n protected setState(newState: object): void {\n this.state = { ...this.state, ...newState };\n }\n\n /**\n * Returns the component payment data ready to submit to the Checkout API\n * Note: this does not ensure validity, check isValid first\n */\n public get data(): PaymentData {\n const order = this.state.order || this.props.order;\n const componentData = this.formatData();\n const doesPaymentMethodHaveNativeComponent = Boolean(getComponentNameOfPaymentType(componentData.paymentMethod?.type));\n const clientData = this.core.modules.risk.data;\n const checkoutAttemptId = this.core.modules.analytics.checkoutAttemptId ?? NO_CHECKOUT_ATTEMPT_ID;\n const paymentMethodBehavior = doesPaymentMethodHaveNativeComponent ? PAYMENT_METHOD_BEHAVIOR.NATIVE : PAYMENT_METHOD_BEHAVIOR.GENERIC;\n\n const sdkData = createSdkData(checkoutAttemptId, clientData, paymentMethodBehavior);\n if (componentData.paymentMethod && checkoutAttemptId) {\n componentData.paymentMethod.checkoutAttemptId = checkoutAttemptId;\n }\n\n if (componentData.paymentMethod && sdkData) {\n componentData.paymentMethod.sdkData = sdkData;\n }\n\n return {\n ...(clientData && { riskData: { clientData } }),\n ...(order && { order: { orderData: order.orderData, pspReference: order.pspReference } }),\n ...componentData,\n clientStateDataIndicator: true\n };\n }\n\n /**\n * Method used to make the payment method active\n * (Useful when there are different payment methods available and activating one PM must trigger a specific task)\n */\n public activate(): void {\n return;\n }\n\n public render(): ComponentChild | Error {\n // render() not implemented in the element\n throw new Error('Payment method cannot be rendered.');\n }\n\n /**\n * Mounts an element into the dom\n * @param domNode - Node (or selector) where we will mount the payment element\n * @returns this - the payment element instance we mounted\n */\n public mount(domNode: HTMLElement | string): this {\n const node = typeof domNode === 'string' ? document.querySelector<HTMLElement>(domNode) : domNode;\n\n if (!node) {\n throw new Error('Component could not mount. Root node was not found.');\n }\n\n if (this._node) {\n this.unmount(); // new, if this._node exists then we are \"remounting\" so we first need to unmount if it's not already been done\n }\n\n this._node = node;\n\n // Add listener for key press events, notably 'Enter' key presses\n on(this._node, 'keypress', this.handleKeyPress, false);\n\n this._component = this.render();\n\n render(this._component, node);\n\n return this;\n }\n\n /**\n * Updates props, resets the internal state and remounts the element.\n *\n * @param props - props to update\n * @returns this - the element instance\n */\n public update(props: Partial<P>): this {\n this.props = this.formatProps({ ...this.props, ...props });\n this.state = {};\n\n return this.unmount().mount(this._node); // for new mount fny\n }\n\n /**\n * Unmounts a payment element from the DOM\n */\n public unmount(): this {\n // Remove listener\n off(this._node, 'keypress', this.handleKeyPress);\n\n if (this._node) {\n render(null, this._node);\n }\n\n return this;\n }\n\n /**\n * Unmounts an element and removes it from the parent instance\n * For \"destroy\" type cleanup - when you don't intend to use the component again\n */\n public remove() {\n this.unmount();\n\n if (this.core) {\n this.core.remove(this);\n }\n }\n}\n\nexport default BaseElement;\n"],"names":["BaseElement","buildElementProps","componentProps","this","props","formatProps","constructor","formatData","submitAnalytics","analyticsObj","handleKeyPress","e","setState","newState","state","data","order","componentData","doesPaymentMethodHaveNativeComponent","Boolean","getComponentNameOfPaymentType","paymentMethod","type","clientData","core","modules","risk","checkoutAttemptId","analytics","NO_CHECKOUT_ATTEMPT_ID","paymentMethodBehavior","PAYMENT_METHOD_BEHAVIOR","NATIVE","GENERIC","sdkData","createSdkData","riskData","orderData","pspReference","clientStateDataIndicator","activate","render","Error","mount","domNode","node","document","querySelector","_node","unmount","on","_component","update","off","remove","checkout","_define_property","_id","uuid","isCoreInstance","initialize","createFromAction","assertIsCoreInstance","AdyenCheckoutError","bind","defaultProps"],"mappings":"mlBAwBA,MAAeA,EA4BDC,iBAAAA,CAAkBC,GACxBC,KAAKC,MAAQD,KAAKE,YAAY,IAAKF,KAAKG,YAAY,gBAAoBJ,GAC5E,CAMUG,WAAAA,CAAYD,GAClB,OAAOA,CACX,CAMA,UAAAG,GACI,MAAO,CAAA,CACX,CAGUC,eAAAA,CAAgBC,GACtB,OAAO,IACX,CAGUC,cAAAA,CAAeC,GACrB,OAAO,IACX,CAEUC,QAAAA,CAASC,GACfV,KAAKW,MAAQ,IAAKX,KAAKW,SAAUD,EACrC,CAMA,QAAWE,GACP,MAAMC,EAAQb,KAAKW,MAAME,OAASb,KAAKC,MAAMY,MACvCC,EAAgBd,KAAKI,aACrBW,EAAuCC,QAAQC,EAA8BH,EAAcI,eAAeC,OAC1GC,EAAapB,KAAKqB,KAAKC,QAAQC,KAAKX,KACpCY,EAAoBxB,KAAKqB,KAAKC,QAAQG,UAAUD,mBAAqBE,EACrEC,EAAwBZ,EAAuCa,EAAwBC,OAASD,EAAwBE,QAExHC,EAAUC,EAAcR,EAAmBJ,EAAYO,GAS7D,OARIb,EAAcI,eAAiBM,IAC/BV,EAAcI,cAAcM,kBAAoBA,GAGhDV,EAAcI,eAAiBa,IAC/BjB,EAAcI,cAAca,QAAUA,GAGnC,IACCX,GAAc,CAAEa,SAAU,CAAEb,kBAC5BP,GAAS,CAAEA,MAAO,CAAEqB,UAAWrB,EAAMqB,UAAWC,aAActB,EAAMsB,kBACrErB,EACHsB,0BAA0B,EAElC,CAMA,QAAAC,GAEA,CAEOC,MAAAA,GAEH,MAAM,IAAIC,MAAM,qCACpB,CAOOC,KAAAA,CAAMC,GACT,MAAMC,EAA0B,iBAAZD,EAAuBE,SAASC,cAA2BH,GAAWA,EAE1F,IAAKC,EACD,MAAM,IAAIH,MAAM,uDAgBpB,OAbIvC,KAAK6C,OACL7C,KAAK8C,UAGT9C,KAAK6C,MAAQH,EAGbK,EAAG/C,KAAK6C,MAAO,WAAY7C,KAAKO,gBAAgB,GAEhDP,KAAKgD,WAAahD,KAAKsC,SAEvBA,EAAOtC,KAAKgD,WAAYN,GAEjB1C,IACX,CAQOiD,MAAAA,CAAOhD,GAIV,OAHAD,KAAKC,MAAQD,KAAKE,YAAY,IAAKF,KAAKC,SAAUA,IAClDD,KAAKW,MAAQ,CAAA,EAENX,KAAK8C,UAAUN,MAAMxC,KAAK6C,MACrC,CAKA,OAAAC,GAQI,OANAI,EAAIlD,KAAK6C,MAAO,WAAY7C,KAAKO,gBAE7BP,KAAK6C,OACLP,EAAO,KAAMtC,KAAK6C,OAGf7C,IACX,CAMA,MAAAmD,GACInD,KAAK8C,UAED9C,KAAKqB,MACLrB,KAAKqB,KAAK8B,OAAOnD,KAEzB,CA7JA,WAAAG,CAAYiD,EAAiBnD,GAX7BoD,EAAArD,KAAgBsD,MAAM,GAAGtD,KAAKG,YAAY,QAAWoD,OACrDF,EAAArD,KAAgBqB,eAEhBgC,EAAArD,KAAOC,gBACPoD,EAAArD,KAAOW,QAAa,IACpB0C,EAAArD,KAAOgD,qBAEPK,EAAArD,KAAU6C,QAAqB,MAK3B,MAAMW,EAnBd,SAA8BJ,GAC1B,QAAKA,IAC+C,mBAAxBA,EAASK,YAAkE,mBAA9BL,EAASM,iBAEtF,CAe+BC,CAAqBP,GAE5C,IAAKI,EACD,MAAM,IAAII,EACN,uBACA,uCAAuC5D,KAAKG,YAAY,6DAIhEH,KAAKqB,KAAO+B,EACZpD,KAAKF,kBAAkBG,GAEvBD,KAAKO,eAAiBP,KAAKO,eAAesD,KAAK7D,KACnD,EAhBAqD,EAVWxD,EAUeiE,eAAe"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import e from"../../../../_virtual/index.js";import{createElement as a,Fragment as n,toChildArray as t,cloneElement as l}from"../../../../external/preact/dist/preact.js";import i from"../../Spinner/Spinner.js";import o from"../../Icon/Icon.js";import{ARIA_ERROR_SUFFIX as r,ARIA_CONTEXT_SUFFIX as
|
|
1
|
+
import e from"../../../../_virtual/index.js";import{createElement as a,Fragment as n,toChildArray as t,cloneElement as l}from"../../../../external/preact/dist/preact.js";import i from"../../Spinner/Spinner.js";import o from"../../Icon/Icon.js";import{ARIA_ERROR_SUFFIX as r,ARIA_CONTEXT_SUFFIX as d}from"../../../../core/Errors/constants.js";import{useRef as s,useMemo as c,useState as u,useCallback as m}from"../../../../external/preact/hooks/dist/hooks.js";import{getUniqueId as p}from"../../../../utils/idGenerator.js";import{PREFIX as _}from"../../Icon/constants.js";import h from"../../../../utils/uuid.js";const f=f=>{const{children:k,className:y,classNameModifiers:b,dir:v,disabled:x,readOnly:E,errorMessage:N,helper:F,inputWrapperModifiers:g,isLoading:$,isValid:j,label:w,labelEndAdornment:I,name:L,onBlur:C,onFieldBlur:A,onFocus:M,onFocusField:S,showValidIcon:T,useLabelElement:V,showErrorElement:q,showContextualElement:B,staticValue:H,contextualText:R,filled:W,focused:z,i18n:G,contextVisibleToScreenReader:O,renderAlternativeToLabel:P,onInputContainerClick:D}=f,J=O??!0,K=q&&"string"==typeof N&&N.length>0,Q=B&&!K&&R&&R.length>0,U=s(p(`adyen-checkout-${L}`)),X=c(()=>H?`input-static-value-${h()}`:null,[H]),[Y,Z]=u(!1),[ee,ae]=u(!1);null!=z&&Z(!!z),null!=W&&ae(!!W);const ne=m(e=>{Z(!0),M?.(e)},[M]),te=m(e=>{Z(!1),C?.(e),A?.(e)},[C,A]),le=m(()=>a(n,null,"string"==typeof w&&a("span",{className:e({"adyen-checkout__label__text":!0,"adyen-checkout__label__text--error":N}),"data-id":L,"data-testid":L},w),"function"==typeof w&&w(),I&&a("span",{className:"adyen-checkout__label-adornment--end"},I),F&&a("span",{className:"adyen-checkout__helper-text"},F)),[w,N,I,F]),ie=m(()=>{const s=a("span",{className:e({"adyen-checkout-contextual-text--error":!0,"adyen-checkout-contextual-text--hidden":!K}),...J&&{id:`${U.current}${r}`},"aria-hidden":J?void 0:"true"},N),c=a("span",{className:e({"adyen-checkout-contextual-text":!0,"adyen-checkout-contextual-text--hidden":!Q}),...J&&{id:`${U.current}${d}`},"aria-hidden":J?void 0:"true"},R);return a(n,null,a("div",{className:e(["adyen-checkout__input-wrapper",...g.map(e=>`adyen-checkout__input-wrapper--${e}`)]),dir:v,onClick:D},H&&a("span",{id:X,className:"adyen-checkout__field-static-value"},H),t(k).map(e=>{const a={isValid:j,onFocusHandler:ne,onBlurHandler:te,isInvalid:!!N,"aria-owns":X,...L&&{uniqueId:U.current},showErrorElement:q};return l(e,a)}),$&&a("span",{className:"adyen-checkout-input__inline-validation adyen-checkout-input__inline-validation--loading"},a(i,{size:"small"})),j&&!1!==T&&a("span",{className:"adyen-checkout-input__inline-validation adyen-checkout-input__inline-validation--valid"},a(o,{type:`${_}checkmark_black`,alt:G?.get("field.valid")})),N&&a("span",{className:"adyen-checkout-input__inline-validation adyen-checkout-input__inline-validation--invalid"},a(o,{type:`${_}field_error`,alt:G?.get("error.title")}))),s,c)},[k,N,R,$,j,ne,te]),oe=m(({onFocusField:n,focused:t,filled:l,disabled:i,name:o,uniqueId:r,useLabelElement:d,isSecuredField:s,children:c,renderAlternativeToLabel:u})=>{const m={onClick:n,className:e({"adyen-checkout__label":!0,"adyen-checkout__label--focused":t,"adyen-checkout__label--filled":l,"adyen-checkout__label--disabled":i})};return d?a("label",{...m,...!s&&o&&{htmlFor:r}},c):u(m,c,r)},[]);return a("div",{"data-testid":"form-field",className:e("adyen-checkout__field",y,b?.map(e=>`adyen-checkout__field--${e}`),{"adyen-checkout__field--error":N,"adyen-checkout__field--valid":j,"adyen-checkout__field--inactive":E||x})},a(oe,{onFocusField:S,name:L,disabled:x,filled:ee,focused:Y,useLabelElement:V,uniqueId:U.current,isSecuredField:!J,renderAlternativeToLabel:P},le()),ie())};f.defaultProps={className:"",classNameModifiers:[],inputWrapperModifiers:[],useLabelElement:!0,showErrorElement:!0,showContextualElement:!0,renderAlternativeToLabel:()=>null};export{f as default};
|
|
2
2
|
//# sourceMappingURL=Field.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Field.js","sources":["../../../../../../src/components/internal/FormFields/Field/Field.tsx"],"sourcesContent":["import classNames from 'classnames';\nimport { cloneElement, ComponentChild, Fragment, FunctionalComponent, h, toChildArray, VNode } from 'preact';\nimport Spinner from '../../Spinner';\nimport Icon from '../../Icon';\nimport { ARIA_CONTEXT_SUFFIX, ARIA_ERROR_SUFFIX } from '../../../../core/Errors/constants';\nimport { useCallback, useMemo, useRef, useState } from 'preact/hooks';\nimport { getUniqueId } from '../../../../utils/idGenerator';\nimport { FieldProps } from './types';\nimport './Field.scss';\nimport { PREFIX } from '../../Icon/constants';\nimport uuid from '../../../../utils/uuid';\n\nconst Field: FunctionalComponent<Readonly<FieldProps>> = props => {\n const {\n children,\n className,\n classNameModifiers,\n dir,\n disabled,\n readOnly,\n errorMessage,\n helper,\n inputWrapperModifiers,\n isLoading,\n isValid,\n label,\n labelEndAdornment,\n name,\n onBlur,\n onFieldBlur,\n onFocus,\n // onFocusField is a securedField related function that allows a label click to set focus on a securedField (equates to CardInput setFocusOn)\n // TODO should rename it to make its purpose clear => setFocusOnSecuredField\n onFocusField,\n showValidIcon,\n useLabelElement,\n showErrorElement,\n showContextualElement,\n staticValue,\n contextualText,\n // Redeclare prop names to avoid internal clashes\n filled: propsFilled,\n focused: propsFocused,\n i18n,\n contextVisibleToScreenReader,\n renderAlternativeToLabel,\n onInputContainerClick\n } = props;\n\n // Controls whether any error element has an aria-hidden=\"true\" attr (which means it is the error for a securedField)\n // or whether it has an id attr that can be pointed to by an aria-describedby attr on an input element\n const contextVisibleToSR = contextVisibleToScreenReader ?? true;\n const showError = showErrorElement && typeof errorMessage === 'string' && errorMessage.length > 0;\n const showContext = showContextualElement && !showError && contextualText?.length > 0;\n\n const uniqueId = useRef(getUniqueId(`adyen-checkout-${name}`));\n const staticValueId = useMemo(() => (staticValue ? `input-static-value-${uuid()}` : null), [staticValue]);\n\n const [focused, setFocused] = useState(false);\n const [filled, setFilled] = useState(false);\n\n // The means by which focussed/filled is set for securedFields\n if (propsFocused != null) setFocused(!!propsFocused);\n if (propsFilled != null) setFilled(!!propsFilled);\n\n // The means by which focussed/filled is set for other fields - this function is passed down to them and triggered\n const onFocusHandler = useCallback(\n (event: h.JSX.TargetedEvent<HTMLInputElement>) => {\n setFocused(true);\n onFocus?.(event);\n },\n [onFocus]\n );\n\n const onBlurHandler = useCallback(\n (event: h.JSX.TargetedEvent<HTMLInputElement>) => {\n setFocused(false);\n onBlur?.(event);\n // When we also need to fire a specific function when a field blurs // TODO - what is the use case?\n onFieldBlur?.(event);\n },\n [onBlur, onFieldBlur]\n );\n\n const renderLabelOrAlternativeContents = useCallback(() => {\n return (\n <Fragment>\n {typeof label === 'string' && (\n <span\n className={classNames({\n 'adyen-checkout__label__text': true,\n 'adyen-checkout__label__text--error': errorMessage\n })}\n data-id={name}\n data-testid={name}\n >\n {label}\n </span>\n )}\n\n {/*TODO - in what scenario is label a function? */}\n {/*@ts-ignore - function is callable*/}\n {typeof label === 'function' && label()}\n\n {labelEndAdornment && <span className=\"adyen-checkout__label-adornment--end\">{labelEndAdornment}</span>}\n\n {helper && <span className={'adyen-checkout__helper-text'}>{helper}</span>}\n </Fragment>\n );\n }, [label, errorMessage, labelEndAdornment, helper]);\n\n const renderInputRelatedElements = useCallback(() => {\n const errorElem = (\n <span\n className={classNames({ 'adyen-checkout-contextual-text--error': true, 'adyen-checkout-contextual-text--hidden': !showError })}\n {...(contextVisibleToSR && { id: `${uniqueId.current}${ARIA_ERROR_SUFFIX}` })}\n aria-hidden={contextVisibleToSR ? null : 'true'}\n >\n {errorMessage}\n </span>\n );\n const contextualElem = (\n <span\n className={classNames({ 'adyen-checkout-contextual-text': true, 'adyen-checkout-contextual-text--hidden': !showContext })}\n {...(contextVisibleToSR && { id: `${uniqueId.current}${ARIA_CONTEXT_SUFFIX}` })}\n aria-hidden={contextVisibleToSR ? null : 'true'}\n >\n {contextualText}\n </span>\n );\n\n return (\n <Fragment>\n {/* The <div> element has a child <input> element that allows keyboard interaction */}\n {/* eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions */}\n <div\n className={classNames([\n 'adyen-checkout__input-wrapper',\n ...inputWrapperModifiers.map(m => `adyen-checkout__input-wrapper--${m}`)\n ])}\n dir={dir}\n onClick={onInputContainerClick}\n >\n {staticValue && (\n <span id={staticValueId} className=\"adyen-checkout__field-static-value\">\n {staticValue}\n </span>\n )}\n\n {toChildArray(children).map((child: ComponentChild): ComponentChild => {\n const propsFromFieldComponent = {\n isValid,\n onFocusHandler,\n onBlurHandler,\n isInvalid: !!errorMessage,\n 'aria-owns': staticValueId,\n ...(name && { uniqueId: uniqueId.current }),\n showErrorElement: showErrorElement\n };\n\n return cloneElement(child as VNode, propsFromFieldComponent);\n })}\n\n {isLoading && (\n <span className=\"adyen-checkout-input__inline-validation adyen-checkout-input__inline-validation--loading\">\n <Spinner size=\"small\" />\n </span>\n )}\n\n {isValid && showValidIcon !== false && (\n <span className=\"adyen-checkout-input__inline-validation adyen-checkout-input__inline-validation--valid\">\n <Icon type={`${PREFIX}checkmark_black`} alt={i18n?.get('field.valid')} />\n </span>\n )}\n\n {errorMessage && (\n <span className=\"adyen-checkout-input__inline-validation adyen-checkout-input__inline-validation--invalid\">\n <Icon type={`${PREFIX}field_error`} alt={i18n?.get('error.title')} />\n </span>\n )}\n </div>\n {errorElem}\n {contextualElem}\n </Fragment>\n );\n }, [children, errorMessage, contextualText, isLoading, isValid, onFocusHandler, onBlurHandler]);\n\n /**\n * Use cases:\n * - Not all form controls want/need a label e.g. many checkboxes describe what they are in their own markup and don't need the wrapping Field to also generate a labelling element\n * - securedFields *can't* have a label (screen-reader's can make the association, over different browser contexts, between the label and the input)\n */\n const LabelOrAlternative = useCallback(\n ({ onFocusField, focused, filled, disabled, name, uniqueId, useLabelElement, isSecuredField, children, renderAlternativeToLabel }) => {\n const defaultWrapperProps = {\n onClick: onFocusField,\n className: classNames({\n 'adyen-checkout__label': true,\n 'adyen-checkout__label--focused': focused,\n 'adyen-checkout__label--filled': filled,\n 'adyen-checkout__label--disabled': disabled\n })\n };\n\n return useLabelElement ? (\n // if we are NOT dealing with the label for a securedField... we can give it a `for` attribute\n <label {...defaultWrapperProps} {...(!isSecuredField && name && { htmlFor: uniqueId })}>\n {children}\n </label>\n ) : (\n renderAlternativeToLabel(defaultWrapperProps, children, uniqueId) // defaults to null\n\n // Example usage:\n // const alternativeLabelContent = (defaultWrapperProps, children, uniqueId) => {\n // return (\n // <div {...defaultWrapperProps} role={'label'} htmlFor={uniqueId}>\n // {children}\n // </div>\n // );\n // };\n // <Field name={'myField'} useLabelElement={false} renderAlternativeToLabel={alternativeLabelContent}>\n );\n },\n []\n );\n\n /**\n * RENDER\n */\n return (\n <div\n data-testid=\"form-field\"\n className={classNames(\n 'adyen-checkout__field',\n className,\n classNameModifiers.map(m => `adyen-checkout__field--${m}`),\n {\n 'adyen-checkout__field--error': errorMessage,\n 'adyen-checkout__field--valid': isValid,\n 'adyen-checkout__field--inactive': readOnly || disabled\n }\n )}\n >\n <LabelOrAlternative\n onFocusField={onFocusField}\n name={name}\n disabled={disabled}\n filled={filled}\n focused={focused}\n useLabelElement={useLabelElement}\n uniqueId={uniqueId.current}\n isSecuredField={!contextVisibleToSR}\n renderAlternativeToLabel={renderAlternativeToLabel}\n >\n {renderLabelOrAlternativeContents()}\n </LabelOrAlternative>\n {renderInputRelatedElements()}\n </div>\n );\n};\n\nField.defaultProps = {\n className: '',\n classNameModifiers: [],\n inputWrapperModifiers: [],\n useLabelElement: true,\n showErrorElement: true,\n showContextualElement: true,\n renderAlternativeToLabel: () => null\n};\n\nexport default Field;\n"],"names":["Field","props","children","className","classNameModifiers","dir","disabled","readOnly","errorMessage","helper","inputWrapperModifiers","isLoading","isValid","label","labelEndAdornment","name","onBlur","onFieldBlur","onFocus","onFocusField","showValidIcon","useLabelElement","showErrorElement","showContextualElement","staticValue","contextualText","filled","propsFilled","focused","propsFocused","i18n","contextVisibleToScreenReader","renderAlternativeToLabel","onInputContainerClick","contextVisibleToSR","showError","length","showContext","uniqueId","useRef","getUniqueId","staticValueId","useMemo","uuid","setFocused","useState","setFilled","onFocusHandler","useCallback","event","onBlurHandler","renderLabelOrAlternativeContents","h","Fragment","span","classNames","data-id","data-testid","renderInputRelatedElements","errorElem","id","current","ARIA_ERROR_SUFFIX","aria-hidden","contextualElem","ARIA_CONTEXT_SUFFIX","div","map","m","onClick","toChildArray","child","propsFromFieldComponent","isInvalid","cloneElement","Spinner","size","Icon","type","PREFIX","alt","get","LabelOrAlternative","isSecuredField","defaultWrapperProps","htmlFor","defaultProps"],"mappings":"omBAYA,MAAMA,EAAmDC,IACrD,MAAMC,SACFA,EAAQC,UACRA,EAASC,mBACTA,EAAkBC,IAClBA,EAAGC,SACHA,EAAQC,SACRA,EAAQC,aACRA,EAAYC,OACZA,EAAMC,sBACNA,EAAqBC,UACrBA,EAASC,QACTA,EAAOC,MACPA,EAAKC,kBACLA,EAAiBC,KACjBA,EAAIC,OACJA,EAAMC,YACNA,EAAWC,QACXA,EAAOC,aAGPA,EAAYC,cACZA,EAAaC,gBACbA,EAAeC,iBACfA,EAAgBC,sBAChBA,EAAqBC,YACrBA,EAAWC,eACXA,EAEAC,OAAQC,EACRC,QAASC,EAAYC,KACrBA,EAAIC,6BACJA,EAA4BC,yBAC5BA,EAAwBC,sBACxBA,GACAhC,EAIEiC,EAAqBH,IAAgC,EACrDI,EAAYb,GAA4C,iBAAjBd,GAA6BA,EAAa4B,OAAS,EAC1FC,EAAcd,IAA0BY,GAAaV,GAAgBW,OAAS,EAE9EE,EAAWC,EAAOC,EAAY,kBAAkBzB,MAChD0B,EAAgBC,EAAQ,IAAOlB,EAAc,sBAAsBmB,MAAW,KAAO,CAACnB,KAErFI,EAASgB,GAAcC,GAAS,IAChCnB,GAAQoB,IAAaD,GAAS,GAGjB,MAAhBhB,GA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AAe,CACjBnF,UAAW,GACXC,mBAAoB,GACpBM,sBAAuB,GACvBW,iBAAiB,EACjBC,kBAAkB,EAClBC,uBAAuB,EACvBS,yBAA0B,IAAM"}
|
|
1
|
+
{"version":3,"file":"Field.js","sources":["../../../../../../src/components/internal/FormFields/Field/Field.tsx"],"sourcesContent":["import classNames from 'classnames';\nimport { cloneElement, ComponentChild, Fragment, FunctionalComponent, h, toChildArray, VNode } from 'preact';\nimport Spinner from '../../Spinner';\nimport Icon from '../../Icon';\nimport { ARIA_CONTEXT_SUFFIX, ARIA_ERROR_SUFFIX } from '../../../../core/Errors/constants';\nimport { useCallback, useMemo, useRef, useState } from 'preact/hooks';\nimport { getUniqueId } from '../../../../utils/idGenerator';\nimport { FieldProps } from './types';\nimport './Field.scss';\nimport { PREFIX } from '../../Icon/constants';\nimport uuid from '../../../../utils/uuid';\n\nconst Field: FunctionalComponent<Readonly<FieldProps>> = props => {\n const {\n children,\n className,\n classNameModifiers,\n dir,\n disabled,\n readOnly,\n errorMessage,\n helper,\n inputWrapperModifiers,\n isLoading,\n isValid,\n label,\n labelEndAdornment,\n name,\n onBlur,\n onFieldBlur,\n onFocus,\n // onFocusField is a securedField related function that allows a label click to set focus on a securedField (equates to CardInput setFocusOn)\n // TODO should rename it to make its purpose clear => setFocusOnSecuredField\n onFocusField,\n showValidIcon,\n useLabelElement,\n showErrorElement,\n showContextualElement,\n staticValue,\n contextualText,\n // Redeclare prop names to avoid internal clashes\n filled: propsFilled,\n focused: propsFocused,\n i18n,\n contextVisibleToScreenReader,\n renderAlternativeToLabel,\n onInputContainerClick\n } = props;\n\n // Controls whether any error element has an aria-hidden=\"true\" attr (which means it is the error for a securedField)\n // or whether it has an id attr that can be pointed to by an aria-describedby attr on an input element\n const contextVisibleToSR = contextVisibleToScreenReader ?? true;\n const showError = showErrorElement && typeof errorMessage === 'string' && errorMessage.length > 0;\n const showContext = showContextualElement && !showError && contextualText && contextualText.length > 0;\n\n const uniqueId = useRef(getUniqueId(`adyen-checkout-${name}`));\n const staticValueId = useMemo(() => (staticValue ? `input-static-value-${uuid()}` : null), [staticValue]);\n\n const [focused, setFocused] = useState(false);\n const [filled, setFilled] = useState(false);\n\n // The means by which focussed/filled is set for securedFields\n if (propsFocused != null) setFocused(!!propsFocused);\n if (propsFilled != null) setFilled(!!propsFilled);\n\n // The means by which focussed/filled is set for other fields - this function is passed down to them and triggered\n const onFocusHandler = useCallback(\n (event: h.JSX.TargetedEvent<HTMLInputElement>) => {\n setFocused(true);\n onFocus?.(event);\n },\n [onFocus]\n );\n\n const onBlurHandler = useCallback(\n (event: h.JSX.TargetedEvent<HTMLInputElement>) => {\n setFocused(false);\n onBlur?.(event);\n // When we also need to fire a specific function when a field blurs // TODO - what is the use case?\n onFieldBlur?.(event);\n },\n [onBlur, onFieldBlur]\n );\n\n const renderLabelOrAlternativeContents = useCallback(() => {\n return (\n <Fragment>\n {typeof label === 'string' && (\n <span\n className={classNames({\n 'adyen-checkout__label__text': true,\n 'adyen-checkout__label__text--error': errorMessage\n })}\n data-id={name}\n data-testid={name}\n >\n {label}\n </span>\n )}\n\n {/*TODO - in what scenario is label a function? */}\n {/*@ts-ignore - function is callable*/}\n {typeof label === 'function' && label()}\n\n {labelEndAdornment && <span className=\"adyen-checkout__label-adornment--end\">{labelEndAdornment}</span>}\n\n {helper && <span className={'adyen-checkout__helper-text'}>{helper}</span>}\n </Fragment>\n );\n }, [label, errorMessage, labelEndAdornment, helper]);\n\n const renderInputRelatedElements = useCallback(() => {\n const errorElem = (\n <span\n className={classNames({ 'adyen-checkout-contextual-text--error': true, 'adyen-checkout-contextual-text--hidden': !showError })}\n {...(contextVisibleToSR && { id: `${uniqueId.current}${ARIA_ERROR_SUFFIX}` })}\n aria-hidden={contextVisibleToSR ? undefined : 'true'}\n >\n {errorMessage}\n </span>\n );\n const contextualElem = (\n <span\n className={classNames({ 'adyen-checkout-contextual-text': true, 'adyen-checkout-contextual-text--hidden': !showContext })}\n {...(contextVisibleToSR && { id: `${uniqueId.current}${ARIA_CONTEXT_SUFFIX}` })}\n aria-hidden={contextVisibleToSR ? undefined : 'true'}\n >\n {contextualText}\n </span>\n );\n\n return (\n <Fragment>\n {/* The <div> element has a child <input> element that allows keyboard interaction */}\n {/* eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions */}\n <div\n className={classNames([\n 'adyen-checkout__input-wrapper',\n ...inputWrapperModifiers.map(m => `adyen-checkout__input-wrapper--${m}`)\n ])}\n dir={dir}\n onClick={onInputContainerClick}\n >\n {staticValue && (\n <span id={staticValueId} className=\"adyen-checkout__field-static-value\">\n {staticValue}\n </span>\n )}\n\n {toChildArray(children).map((child: ComponentChild): ComponentChild => {\n const propsFromFieldComponent = {\n isValid,\n onFocusHandler,\n onBlurHandler,\n isInvalid: !!errorMessage,\n 'aria-owns': staticValueId,\n ...(name && { uniqueId: uniqueId.current }),\n showErrorElement: showErrorElement\n };\n\n return cloneElement(child as VNode, propsFromFieldComponent);\n })}\n\n {isLoading && (\n <span className=\"adyen-checkout-input__inline-validation adyen-checkout-input__inline-validation--loading\">\n <Spinner size=\"small\" />\n </span>\n )}\n\n {isValid && showValidIcon !== false && (\n <span className=\"adyen-checkout-input__inline-validation adyen-checkout-input__inline-validation--valid\">\n <Icon type={`${PREFIX}checkmark_black`} alt={i18n?.get('field.valid')} />\n </span>\n )}\n\n {errorMessage && (\n <span className=\"adyen-checkout-input__inline-validation adyen-checkout-input__inline-validation--invalid\">\n <Icon type={`${PREFIX}field_error`} alt={i18n?.get('error.title')} />\n </span>\n )}\n </div>\n {errorElem}\n {contextualElem}\n </Fragment>\n );\n }, [children, errorMessage, contextualText, isLoading, isValid, onFocusHandler, onBlurHandler]);\n\n /**\n * Use cases:\n * - Not all form controls want/need a label e.g. many checkboxes describe what they are in their own markup and don't need the wrapping Field to also generate a labelling element\n * - securedFields *can't* have a label (screen-reader's can make the association, over different browser contexts, between the label and the input)\n */\n const LabelOrAlternative = useCallback(\n ({ onFocusField, focused, filled, disabled, name, uniqueId, useLabelElement, isSecuredField, children, renderAlternativeToLabel }) => {\n const defaultWrapperProps = {\n onClick: onFocusField,\n className: classNames({\n 'adyen-checkout__label': true,\n 'adyen-checkout__label--focused': focused,\n 'adyen-checkout__label--filled': filled,\n 'adyen-checkout__label--disabled': disabled\n })\n };\n\n return useLabelElement ? (\n // if we are NOT dealing with the label for a securedField... we can give it a `for` attribute\n <label {...defaultWrapperProps} {...(!isSecuredField && name && { htmlFor: uniqueId })}>\n {children}\n </label>\n ) : (\n renderAlternativeToLabel(defaultWrapperProps, children, uniqueId) // defaults to null\n\n // Example usage:\n // const alternativeLabelContent = (defaultWrapperProps, children, uniqueId) => {\n // return (\n // <div {...defaultWrapperProps} role={'label'} htmlFor={uniqueId}>\n // {children}\n // </div>\n // );\n // };\n // <Field name={'myField'} useLabelElement={false} renderAlternativeToLabel={alternativeLabelContent}>\n );\n },\n []\n );\n\n /**\n * RENDER\n */\n return (\n <div\n data-testid=\"form-field\"\n className={classNames(\n 'adyen-checkout__field',\n className,\n classNameModifiers?.map(m => `adyen-checkout__field--${m}`),\n {\n 'adyen-checkout__field--error': errorMessage,\n 'adyen-checkout__field--valid': isValid,\n 'adyen-checkout__field--inactive': readOnly || disabled\n }\n )}\n >\n <LabelOrAlternative\n onFocusField={onFocusField}\n name={name}\n disabled={disabled}\n filled={filled}\n focused={focused}\n useLabelElement={useLabelElement}\n uniqueId={uniqueId.current}\n isSecuredField={!contextVisibleToSR}\n renderAlternativeToLabel={renderAlternativeToLabel}\n >\n {renderLabelOrAlternativeContents()}\n </LabelOrAlternative>\n {renderInputRelatedElements()}\n </div>\n );\n};\n\nField.defaultProps = {\n className: '',\n classNameModifiers: [],\n inputWrapperModifiers: [],\n useLabelElement: true,\n showErrorElement: true,\n showContextualElement: true,\n renderAlternativeToLabel: () => null\n};\n\nexport default Field;\n"],"names":["Field","props","children","className","classNameModifiers","dir","disabled","readOnly","errorMessage","helper","inputWrapperModifiers","isLoading","isValid","label","labelEndAdornment","name","onBlur","onFieldBlur","onFocus","onFocusField","showValidIcon","useLabelElement","showErrorElement","showContextualElement","staticValue","contextualText","filled","propsFilled","focused","propsFocused","i18n","contextVisibleToScreenReader","renderAlternativeToLabel","onInputContainerClick","contextVisibleToSR","showError","length","showContext","uniqueId","useRef","getUniqueId","staticValueId","useMemo","uuid","setFocused","useState","setFilled","onFocusHandler","useCallback","event","onBlurHandler","renderLabelOrAlternativeContents","h","Fragment","span","classNames","data-id","data-testid","renderInputRelatedElements","errorElem","id","current","ARIA_ERROR_SUFFIX","aria-hidden","undefined","contextualElem","ARIA_CONTEXT_SUFFIX","div","map","m","onClick","toChildArray","child","propsFromFieldComponent","isInvalid","cloneElement","Spinner","size","Icon","type","PREFIX","alt","get","LabelOrAlternative","isSecuredField","defaultWrapperProps","htmlFor","defaultProps"],"mappings":"omBAYA,MAAMA,EAAmDC,IACrD,MAAMC,SACFA,EAAQC,UACRA,EAASC,mBACTA,EAAkBC,IAClBA,EAAGC,SACHA,EAAQC,SACRA,EAAQC,aACRA,EAAYC,OACZA,EAAMC,sBACNA,EAAqBC,UACrBA,EAASC,QACTA,EAAOC,MACPA,EAAKC,kBACLA,EAAiBC,KACjBA,EAAIC,OACJA,EAAMC,YACNA,EAAWC,QACXA,EAAOC,aAGPA,EAAYC,cACZA,EAAaC,gBACbA,EAAeC,iBACfA,EAAgBC,sBAChBA,EAAqBC,YACrBA,EAAWC,eACXA,EAEAC,OAAQC,EACRC,QAASC,EAAYC,KACrBA,EAAIC,6BACJA,EAA4BC,yBAC5BA,EAAwBC,sBACxBA,GACAhC,EAIEiC,EAAqBH,IAAgC,EACrDI,EAAYb,GAA4C,iBAAjBd,GAA6BA,EAAa4B,OAAS,EAC1FC,EAAcd,IAA0BY,GAAaV,GAAkBA,EAAeW,OAAS,EAE/FE,EAAWC,EAAOC,EAAY,kBAAkBzB,MAChD0B,EAAgBC,EAAQ,IAAOlB,EAAc,sBAAsBmB,MAAW,KAAO,CAACnB,KAEr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AUA,EAASuB,QACnBuB,gBAAiBlD,EACjBF,yBAA0BA,GAEzBmB,MAEJO,OAKb1D,EAAMuF,aAAe,CACjBpF,UAAW,GACXC,mBAAoB,GACpBM,sBAAuB,GACvBW,iBAAiB,EACjBC,kBAAkB,EAClBC,uBAAuB,EACvBS,yBAA0B,IAAM"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{ENCRYPTED_EXPIRY_DATE as e,ENCRYPTED_EXPIRY_MONTH as r,ENCRYPTED_EXPIRY_YEAR as l,ENCRYPTED_SECURITY_CODE as i,CVC_POLICY_OPTIONAL as t,DATE_POLICY_OPTIONAL as c,CVC_POLICY_HIDDEN as o,DATE_POLICY_HIDDEN as s}from"../lib/constants.js";import{EMPTY_FIELD_ERROR_MESSAGES as d}from"../../../../core/Errors/constants.js";const a=e=>e?Array.prototype.slice.call(e.querySelectorAll('[data-cse*="encrypted"]')).map(e=>e.getAttribute("data-cse")):[],p=(i,t)=>(t===e?(i[r]=!1,i[l]=!1):i[t]=!1,i),y=(d,a)=>(p,y)=>{let n=!0!==a.valid[y]?((i,t)=>1!==t||i!==r&&i!==l?i:e)(y,d):null;return n=((e,r,l)=>{const{isFieldOfType:d,fieldIsValid:a}=l.reduce((l,i)=>(l.isFieldOfType||(l.isFieldOfType=e===i,l.fieldIsValid=!r.errors[i]),l),{isFieldOfType:!1,fieldIsValid:!1}),p=e===i?"cvcPolicy":"expiryDatePolicy",y="cvcPolicy"===p?t:c,n="cvcPolicy"===p?o:s;return(r[p]===y||r[p]===n)&&a&&d?null:e})(n,a,[i,e,r,l]),n&&!p.includes(n)&&p.push(n),p},n=(e,r,l)=>({rootNode:r,fieldType:e,error:l.errors?.[e]||d[e],type:"card"});export{n as getErrorObject,y as getErrorReducer,a as getFields,p as validFieldsReducer};
|
|
1
|
+
import{ENCRYPTED_EXPIRY_DATE as e,ENCRYPTED_EXPIRY_MONTH as r,ENCRYPTED_EXPIRY_YEAR as l,ENCRYPTED_SECURITY_CODE as i,CVC_POLICY_OPTIONAL as t,DATE_POLICY_OPTIONAL as c,CVC_POLICY_HIDDEN as o,DATE_POLICY_HIDDEN as s}from"../lib/constants.js";import{EMPTY_FIELD_ERROR_MESSAGES as d}from"../../../../core/Errors/constants.js";const a=e=>e?Array.prototype.slice.call(e.querySelectorAll('[data-cse*="encrypted"]')).map(e=>e.getAttribute("data-cse")):[],p=(i,t)=>(t===e?(i[r]=!1,i[l]=!1):i[t]=!1,i),y=(d,a)=>(p,y)=>{let n=!0!==a.valid[y]?((i,t)=>1!==t||i!==r&&i!==l?i:e)(y,d):null;return n=((e,r,l)=>{const{isFieldOfType:d,fieldIsValid:a}=l.reduce((l,i)=>(l.isFieldOfType||(l.isFieldOfType=e===i,l.fieldIsValid=!r.errors?.[i]),l),{isFieldOfType:!1,fieldIsValid:!1}),p=e===i?"cvcPolicy":"expiryDatePolicy",y="cvcPolicy"===p?t:c,n="cvcPolicy"===p?o:s;return(r[p]===y||r[p]===n)&&a&&d?null:e})(n,a,[i,e,r,l]),n&&!p.includes(n)&&p.push(n),p},n=(e,r,l)=>({rootNode:r,fieldType:e,error:l.errors?.[e]||d[e],type:"card"});export{n as getErrorObject,y as getErrorReducer,a as getFields,p as validFieldsReducer};
|
|
2
2
|
//# sourceMappingURL=SFPUtils.js.map
|