@adyen/adyen-web 6.13.1 → 6.15.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 +7 -2
- 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 +299 -205
- package/dist/es/adyen.css +7 -2
- package/dist/es/adyen.css.map +1 -1
- package/dist/es/components/AmazonPay/AmazonPay.js +1 -1
- package/dist/es/components/AmazonPay/AmazonPay.js.map +1 -1
- package/dist/es/components/ApplePay/ApplePay.js +1 -1
- package/dist/es/components/ApplePay/ApplePay.js.map +1 -1
- package/dist/es/components/Card/Card.js +1 -1
- package/dist/es/components/Card/Card.js.map +1 -1
- package/dist/es/components/Card/components/CardInput/CardInput.js +1 -1
- package/dist/es/components/Card/components/CardInput/CardInput.js.map +1 -1
- 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/components/Fastlane/FastlaneSignup.js +1 -1
- package/dist/es/components/Card/components/Fastlane/FastlaneSignup.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/Dropin/Dropin.js +1 -1
- package/dist/es/components/Dropin/Dropin.js.map +1 -1
- package/dist/es/components/Dropin/components/DropinComponent.js +1 -1
- package/dist/es/components/Dropin/components/DropinComponent.js.map +1 -1
- package/dist/es/components/GooglePay/GooglePay.js +1 -1
- package/dist/es/components/GooglePay/GooglePay.js.map +1 -1
- package/dist/es/components/PayByBankPix/PayByBankPix.js +2 -0
- package/dist/es/components/PayByBankPix/PayByBankPix.js.map +1 -0
- package/dist/es/components/PayByBankPix/components/Enrollment/Enrollment.js +2 -0
- package/dist/es/components/PayByBankPix/components/Enrollment/Enrollment.js.map +1 -0
- package/dist/es/components/PayByBankPix/components/Enrollment/components/AwaitLogoContainer.js +2 -0
- package/dist/es/components/PayByBankPix/components/Enrollment/components/AwaitLogoContainer.js.map +1 -0
- package/dist/es/components/PayByBankPix/components/Enrollment/components/IssuerListIntroduction.js +2 -0
- package/dist/es/components/PayByBankPix/components/Enrollment/components/IssuerListIntroduction.js.map +1 -0
- package/dist/es/components/PayByBankPix/components/Enrollment/components/PayByBankPixAwait.js +2 -0
- package/dist/es/components/PayByBankPix/components/Enrollment/components/PayByBankPixAwait.js.map +1 -0
- package/dist/es/components/PayByBankPix/components/Enrollment/getEnrollmentStatus.js +2 -0
- package/dist/es/components/PayByBankPix/components/Enrollment/getEnrollmentStatus.js.map +1 -0
- package/dist/es/components/PayByBankPix/components/Enrollment/useIssuerWithLogo.js +2 -0
- package/dist/es/components/PayByBankPix/components/Enrollment/useIssuerWithLogo.js.map +1 -0
- package/dist/es/components/PayByBankPix/components/StoredPayment/StoredPayment.js +2 -0
- package/dist/es/components/PayByBankPix/components/StoredPayment/StoredPayment.js.map +1 -0
- package/dist/es/components/PayByBankPix/components/StoredPayment/getAuthorizationStatus.js +2 -0
- package/dist/es/components/PayByBankPix/components/StoredPayment/getAuthorizationStatus.js.map +1 -0
- package/dist/es/components/PayByBankPix/services/PasskeySdkLoader.js +2 -0
- package/dist/es/components/PayByBankPix/services/PasskeySdkLoader.js.map +1 -0
- package/dist/es/components/PayByBankPix/services/PasskeyService.js +2 -0
- package/dist/es/components/PayByBankPix/services/PasskeyService.js.map +1 -0
- package/dist/es/components/PayByBankPix/services/authorizeEnrollment.js +2 -0
- package/dist/es/components/PayByBankPix/services/authorizeEnrollment.js.map +1 -0
- package/dist/es/components/PayByBankPix/services/authorizePayment.js +2 -0
- package/dist/es/components/PayByBankPix/services/authorizePayment.js.map +1 -0
- package/dist/es/components/PayByBankPix/services/types.js +2 -0
- package/dist/es/components/PayByBankPix/services/types.js.map +1 -0
- package/dist/es/components/PayPal/Paypal.js +1 -1
- package/dist/es/components/PayPal/Paypal.js.map +1 -1
- package/dist/es/components/Redirect/Redirect.js +1 -1
- package/dist/es/components/Redirect/Redirect.js.map +1 -1
- package/dist/es/components/Riverty/Riverty.js +1 -1
- package/dist/es/components/Riverty/Riverty.js.map +1 -1
- package/dist/es/components/ThreeDS2/ThreeDS2Challenge.js +1 -1
- package/dist/es/components/ThreeDS2/ThreeDS2Challenge.js.map +1 -1
- package/dist/es/components/ThreeDS2/ThreeDS2DeviceFingerprint.js +1 -1
- package/dist/es/components/ThreeDS2/ThreeDS2DeviceFingerprint.js.map +1 -1
- package/dist/es/components/ThreeDS2/callSubmit3DS2Fingerprint.js +1 -1
- package/dist/es/components/ThreeDS2/callSubmit3DS2Fingerprint.js.map +1 -1
- package/dist/es/components/ThreeDS2/components/Challenge/PrepareChallenge3DS2.js +1 -1
- package/dist/es/components/ThreeDS2/components/Challenge/PrepareChallenge3DS2.js.map +1 -1
- package/dist/es/components/ThreeDS2/components/DeviceFingerprint/PrepareFingerprint3DS2.js +1 -1
- package/dist/es/components/ThreeDS2/components/DeviceFingerprint/PrepareFingerprint3DS2.js.map +1 -1
- package/dist/es/components/ThreeDS2/constants.js +1 -1
- package/dist/es/components/ThreeDS2/constants.js.map +1 -1
- package/dist/es/components/components-name-map.js +1 -1
- package/dist/es/components/components-name-map.js.map +1 -1
- package/dist/es/components/index.js +1 -1
- package/dist/es/components/internal/Address/components/ReadOnlyAddress.js +1 -1
- package/dist/es/components/internal/Address/components/ReadOnlyAddress.js.map +1 -1
- package/dist/es/components/internal/Address/constants.js +1 -1
- package/dist/es/components/internal/Address/constants.js.map +1 -1
- package/dist/es/components/internal/Await/Await.js +1 -1
- package/dist/es/components/internal/Await/Await.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/DisclaimerMessage/DisclaimerMessage.js +1 -1
- package/dist/es/components/internal/DisclaimerMessage/DisclaimerMessage.js.map +1 -1
- package/dist/es/components/internal/IssuerList/IssuerList.js +1 -1
- package/dist/es/components/internal/IssuerList/IssuerList.js.map +1 -1
- package/dist/es/components/internal/OpenInvoice/utils.js.map +1 -1
- package/dist/es/components/internal/QRLoader/QRLoader.js +1 -1
- package/dist/es/components/internal/QRLoader/QRLoader.js.map +1 -1
- package/dist/es/components/internal/SecuredFields/SFP/SecuredFieldsProvider.js +1 -1
- package/dist/es/components/internal/SecuredFields/SFP/SecuredFieldsProvider.js.map +1 -1
- package/dist/es/components/internal/UIElement/UIElement.js +1 -1
- package/dist/es/components/internal/UIElement/UIElement.js.map +1 -1
- package/dist/es/components/tx-variants.js +1 -1
- package/dist/es/components/tx-variants.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/AnalyticsErrorEvent.js +2 -0
- package/dist/es/core/Analytics/AnalyticsErrorEvent.js.map +1 -0
- package/dist/es/core/Analytics/AnalyticsEvent.js +2 -0
- package/dist/es/core/Analytics/AnalyticsEvent.js.map +1 -0
- package/dist/es/core/Analytics/AnalyticsInfoEvent.js +2 -0
- package/dist/es/core/Analytics/AnalyticsInfoEvent.js.map +1 -0
- package/dist/es/core/Analytics/AnalyticsLogEvent.js +2 -0
- package/dist/es/core/Analytics/AnalyticsLogEvent.js.map +1 -0
- package/dist/es/core/Analytics/utils.js +1 -1
- package/dist/es/core/Analytics/utils.js.map +1 -1
- package/dist/es/core/Environment/Environment.js +1 -1
- package/dist/es/core/Environment/Environment.js.map +1 -1
- package/dist/es/core/ProcessResponse/PaymentMethods/filters.js +1 -1
- package/dist/es/core/ProcessResponse/PaymentMethods/filters.js.map +1 -1
- package/dist/es/core/Services/analytics/collect-id.js +1 -1
- package/dist/es/core/core.js +1 -1
- package/dist/es/core/core.js.map +1 -1
- package/dist/es/core/utils.js +1 -1
- package/dist/es/core/utils.js.map +1 -1
- package/dist/es/index.d.ts +299 -205
- package/dist/es/index.js +1 -1
- package/dist/es/utils/base64.js.map +1 -1
- package/dist/es-legacy/adyen.css +7 -2
- package/dist/es-legacy/adyen.css.map +1 -1
- package/dist/es-legacy/components/AmazonPay/AmazonPay.js +1 -1
- package/dist/es-legacy/components/AmazonPay/AmazonPay.js.map +1 -1
- package/dist/es-legacy/components/ApplePay/ApplePay.js +1 -1
- package/dist/es-legacy/components/ApplePay/ApplePay.js.map +1 -1
- package/dist/es-legacy/components/Card/Card.js +1 -1
- package/dist/es-legacy/components/Card/Card.js.map +1 -1
- package/dist/es-legacy/components/Card/components/CardInput/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/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/components/Fastlane/FastlaneSignup.js +1 -1
- package/dist/es-legacy/components/Card/components/Fastlane/FastlaneSignup.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/Dropin/Dropin.js +1 -1
- package/dist/es-legacy/components/Dropin/Dropin.js.map +1 -1
- package/dist/es-legacy/components/Dropin/components/DropinComponent.js +1 -1
- package/dist/es-legacy/components/Dropin/components/DropinComponent.js.map +1 -1
- package/dist/es-legacy/components/GooglePay/GooglePay.js +1 -1
- package/dist/es-legacy/components/GooglePay/GooglePay.js.map +1 -1
- package/dist/es-legacy/components/PayByBankPix/PayByBankPix.js +2 -0
- package/dist/es-legacy/components/PayByBankPix/PayByBankPix.js.map +1 -0
- package/dist/es-legacy/components/PayByBankPix/components/Enrollment/Enrollment.js +2 -0
- package/dist/es-legacy/components/PayByBankPix/components/Enrollment/Enrollment.js.map +1 -0
- package/dist/es-legacy/components/PayByBankPix/components/Enrollment/components/AwaitLogoContainer.js +2 -0
- package/dist/es-legacy/components/PayByBankPix/components/Enrollment/components/AwaitLogoContainer.js.map +1 -0
- package/dist/es-legacy/components/PayByBankPix/components/Enrollment/components/IssuerListIntroduction.js +2 -0
- package/dist/es-legacy/components/PayByBankPix/components/Enrollment/components/IssuerListIntroduction.js.map +1 -0
- package/dist/es-legacy/components/PayByBankPix/components/Enrollment/components/PayByBankPixAwait.js +2 -0
- package/dist/es-legacy/components/PayByBankPix/components/Enrollment/components/PayByBankPixAwait.js.map +1 -0
- package/dist/es-legacy/components/PayByBankPix/components/Enrollment/getEnrollmentStatus.js +2 -0
- package/dist/es-legacy/components/PayByBankPix/components/Enrollment/getEnrollmentStatus.js.map +1 -0
- package/dist/es-legacy/components/PayByBankPix/components/Enrollment/useIssuerWithLogo.js +2 -0
- package/dist/es-legacy/components/PayByBankPix/components/Enrollment/useIssuerWithLogo.js.map +1 -0
- package/dist/es-legacy/components/PayByBankPix/components/StoredPayment/StoredPayment.js +2 -0
- package/dist/es-legacy/components/PayByBankPix/components/StoredPayment/StoredPayment.js.map +1 -0
- package/dist/es-legacy/components/PayByBankPix/components/StoredPayment/getAuthorizationStatus.js +2 -0
- package/dist/es-legacy/components/PayByBankPix/components/StoredPayment/getAuthorizationStatus.js.map +1 -0
- package/dist/es-legacy/components/PayByBankPix/services/PasskeySdkLoader.js +2 -0
- package/dist/es-legacy/components/PayByBankPix/services/PasskeySdkLoader.js.map +1 -0
- package/dist/es-legacy/components/PayByBankPix/services/PasskeyService.js +2 -0
- package/dist/es-legacy/components/PayByBankPix/services/PasskeyService.js.map +1 -0
- package/dist/es-legacy/components/PayByBankPix/services/authorizeEnrollment.js +2 -0
- package/dist/es-legacy/components/PayByBankPix/services/authorizeEnrollment.js.map +1 -0
- package/dist/es-legacy/components/PayByBankPix/services/authorizePayment.js +2 -0
- package/dist/es-legacy/components/PayByBankPix/services/authorizePayment.js.map +1 -0
- package/dist/es-legacy/components/PayByBankPix/services/types.js +2 -0
- package/dist/es-legacy/components/PayByBankPix/services/types.js.map +1 -0
- package/dist/es-legacy/components/PayPal/Paypal.js +1 -1
- package/dist/es-legacy/components/PayPal/Paypal.js.map +1 -1
- package/dist/es-legacy/components/Redirect/Redirect.js +1 -1
- package/dist/es-legacy/components/Redirect/Redirect.js.map +1 -1
- package/dist/es-legacy/components/Riverty/Riverty.js +1 -1
- package/dist/es-legacy/components/Riverty/Riverty.js.map +1 -1
- package/dist/es-legacy/components/ThreeDS2/ThreeDS2Challenge.js +1 -1
- package/dist/es-legacy/components/ThreeDS2/ThreeDS2Challenge.js.map +1 -1
- package/dist/es-legacy/components/ThreeDS2/ThreeDS2DeviceFingerprint.js +1 -1
- package/dist/es-legacy/components/ThreeDS2/ThreeDS2DeviceFingerprint.js.map +1 -1
- package/dist/es-legacy/components/ThreeDS2/callSubmit3DS2Fingerprint.js +1 -1
- package/dist/es-legacy/components/ThreeDS2/callSubmit3DS2Fingerprint.js.map +1 -1
- package/dist/es-legacy/components/ThreeDS2/components/Challenge/PrepareChallenge3DS2.js +1 -1
- package/dist/es-legacy/components/ThreeDS2/components/Challenge/PrepareChallenge3DS2.js.map +1 -1
- package/dist/es-legacy/components/ThreeDS2/components/DeviceFingerprint/PrepareFingerprint3DS2.js +1 -1
- package/dist/es-legacy/components/ThreeDS2/components/DeviceFingerprint/PrepareFingerprint3DS2.js.map +1 -1
- package/dist/es-legacy/components/ThreeDS2/constants.js +1 -1
- package/dist/es-legacy/components/ThreeDS2/constants.js.map +1 -1
- package/dist/es-legacy/components/components-name-map.js +1 -1
- package/dist/es-legacy/components/components-name-map.js.map +1 -1
- package/dist/es-legacy/components/index.js +1 -1
- package/dist/es-legacy/components/internal/Address/components/ReadOnlyAddress.js +1 -1
- package/dist/es-legacy/components/internal/Address/components/ReadOnlyAddress.js.map +1 -1
- package/dist/es-legacy/components/internal/Address/constants.js +1 -1
- package/dist/es-legacy/components/internal/Address/constants.js.map +1 -1
- package/dist/es-legacy/components/internal/Await/Await.js +1 -1
- package/dist/es-legacy/components/internal/Await/Await.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/DisclaimerMessage/DisclaimerMessage.js +1 -1
- package/dist/es-legacy/components/internal/DisclaimerMessage/DisclaimerMessage.js.map +1 -1
- package/dist/es-legacy/components/internal/IssuerList/IssuerList.js +1 -1
- package/dist/es-legacy/components/internal/IssuerList/IssuerList.js.map +1 -1
- package/dist/es-legacy/components/internal/OpenInvoice/utils.js.map +1 -1
- package/dist/es-legacy/components/internal/QRLoader/QRLoader.js +1 -1
- package/dist/es-legacy/components/internal/QRLoader/QRLoader.js.map +1 -1
- package/dist/es-legacy/components/internal/SecuredFields/SFP/SecuredFieldsProvider.js +1 -1
- package/dist/es-legacy/components/internal/SecuredFields/SFP/SecuredFieldsProvider.js.map +1 -1
- package/dist/es-legacy/components/internal/UIElement/UIElement.js +1 -1
- package/dist/es-legacy/components/internal/UIElement/UIElement.js.map +1 -1
- package/dist/es-legacy/components/tx-variants.js +1 -1
- package/dist/es-legacy/components/tx-variants.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/AnalyticsErrorEvent.js +2 -0
- package/dist/es-legacy/core/Analytics/AnalyticsErrorEvent.js.map +1 -0
- package/dist/es-legacy/core/Analytics/AnalyticsEvent.js +2 -0
- package/dist/es-legacy/core/Analytics/AnalyticsEvent.js.map +1 -0
- package/dist/es-legacy/core/Analytics/AnalyticsInfoEvent.js +2 -0
- package/dist/es-legacy/core/Analytics/AnalyticsInfoEvent.js.map +1 -0
- package/dist/es-legacy/core/Analytics/AnalyticsLogEvent.js +2 -0
- package/dist/es-legacy/core/Analytics/AnalyticsLogEvent.js.map +1 -0
- package/dist/es-legacy/core/Analytics/utils.js +1 -1
- package/dist/es-legacy/core/Analytics/utils.js.map +1 -1
- package/dist/es-legacy/core/Environment/Environment.js +1 -1
- package/dist/es-legacy/core/Environment/Environment.js.map +1 -1
- package/dist/es-legacy/core/ProcessResponse/PaymentMethods/filters.js +1 -1
- package/dist/es-legacy/core/ProcessResponse/PaymentMethods/filters.js.map +1 -1
- package/dist/es-legacy/core/Services/analytics/collect-id.js +1 -1
- package/dist/es-legacy/core/core.js +1 -1
- package/dist/es-legacy/core/core.js.map +1 -1
- package/dist/es-legacy/core/utils.js +1 -1
- package/dist/es-legacy/core/utils.js.map +1 -1
- package/dist/es-legacy/index.js +1 -1
- package/dist/es-legacy/utils/base64.js.map +1 -1
- package/package.json +6 -7
- package/styles/adyen.css +7 -2
- package/dist/es/components/Riverty/config.js +0 -2
- package/dist/es/components/Riverty/config.js.map +0 -1
- package/dist/es/core/Analytics/analyticsPreProcessor.js +0 -2
- package/dist/es/core/Analytics/analyticsPreProcessor.js.map +0 -1
- package/dist/es-legacy/components/Riverty/config.js +0 -2
- package/dist/es-legacy/components/Riverty/config.js.map +0 -1
- package/dist/es-legacy/core/Analytics/analyticsPreProcessor.js +0 -2
- package/dist/es-legacy/core/Analytics/analyticsPreProcessor.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"IssuerList.js","sources":["../../../../../src/components/internal/IssuerList/IssuerList.tsx"],"sourcesContent":["import { Fragment, h } from 'preact';\nimport { useState, useEffect, useCallback, useRef } from 'preact/hooks';\nimport useForm from '../../../utils/useForm';\nimport Field from '../FormFields/Field';\nimport IssuerButtonGroup from './IssuerButtonGroup';\nimport ContentSeparator from '../ContentSeparator';\nimport { useCoreContext } from '../../../core/Context/CoreProvider';\nimport { ValidatorRules } from '../../../utils/Validator/types';\nimport { IssuerListProps } from './types';\nimport './IssuerList.scss';\nimport useSRPanelContext from '../../../core/Errors/useSRPanelContext';\nimport { SetSRMessagesReturnFn } from '../../../core/Errors/SRPanelProvider';\nimport { SetSRMessagesReturnObject } from '../../../core/Errors/types';\nimport { ERROR_ACTION_FOCUS_FIELD } from '../../../core/Errors/constants';\nimport { setFocusOnField } from '../../../utils/setFocus';\nimport DisclaimerMessage from '../DisclaimerMessage';\nimport Select from '../FormFields/Select';\nimport { SelectTargetObject } from '../FormFields/Select/types';\nimport {\n ANALYTICS_DISPLAYED_STR,\n ANALYTICS_FEATURED_ISSUER,\n ANALYTICS_INPUT_STR,\n ANALYTICS_LIST,\n ANALYTICS_LIST_SEARCH,\n ANALYTICS_SEARCH_DEBOUNCE_TIME,\n ANALYTICS_SELECTED_STR\n} from '../../../core/Analytics/constants';\nimport { debounce } from '../../../utils/debounce';\n\nconst payButtonLabel = ({ issuer, items }, i18n): string => {\n const issuerName = items.find(i => i.id === issuer)?.name;\n if (!issuer || !issuerName) return i18n.get('continue');\n return `${i18n.get('continueTo')} ${issuerName}`;\n};\n\nconst schema = ['issuer'];\nconst validationRules: ValidatorRules = {\n issuer: {\n validate: issuer => !!issuer && issuer.length > 0,\n errorMessage: 'issuerList.selectField.contextualText',\n modes: ['blur']\n }\n};\n\nenum IssuerListInputTypes {\n ButtonGroup,\n Dropdown\n}\n\nfunction IssuerList({ items, placeholder, issuer, highlightedIds = [], showContextualElement, contextualText, ...props }: IssuerListProps) {\n const { i18n } = useCoreContext();\n const { handleChangeFor, triggerValidation, data, valid, errors, isValid } = useForm({\n schema,\n defaultData: { issuer },\n rules: validationRules\n });\n const [status, setStatus] = useState('ready');\n const [inputType, setInputType] = useState<IssuerListInputTypes>(IssuerListInputTypes.Dropdown);\n\n const { setSRMessagesFromObjects, shouldMoveFocusSR } = useSRPanelContext();\n const setSRMessages: SetSRMessagesReturnFn = setSRMessagesFromObjects?.({});\n\n const getErrorMessage = error => (error && error.errorMessage ? i18n.get(error.errorMessage) : !!error);\n\n this.setStatus = newStatus => {\n setStatus(newStatus);\n };\n\n const handleInputChange = useCallback(\n (type: IssuerListInputTypes) => (event: h.JSX.TargetedKeyboardEvent<HTMLInputElement>) => {\n const target = type === IssuerListInputTypes.Dropdown ? ANALYTICS_LIST : ANALYTICS_FEATURED_ISSUER;\n const issuerObj = items.find(issuer => issuer.id === (event.target as SelectTargetObject).value);\n props.onSubmitAnalytics({ type: ANALYTICS_SELECTED_STR, target, issuer: issuerObj.name });\n\n setInputType(type);\n handleChangeFor('issuer')(event);\n },\n [handleChangeFor]\n );\n\n const handleListToggle = useCallback((isOpen: boolean) => {\n if (isOpen) {\n props.onSubmitAnalytics({ type: ANALYTICS_DISPLAYED_STR, target: ANALYTICS_LIST });\n }\n }, []);\n\n const debounceSearchAnalytics = useRef(debounce(props.onSubmitAnalytics, ANALYTICS_SEARCH_DEBOUNCE_TIME));\n\n const handleSearch = useCallback(() => {\n debounceSearchAnalytics.current({ type: ANALYTICS_INPUT_STR, target: ANALYTICS_LIST_SEARCH });\n }, []);\n\n useEffect(() => {\n props.onChange({ data, valid, errors, isValid });\n\n const srPanelResp: SetSRMessagesReturnObject = setSRMessages?.({ errors, isValidating: true });\n if (srPanelResp?.action === ERROR_ACTION_FOCUS_FIELD) {\n // Focus field in error, if required\n if (shouldMoveFocusSR) setFocusOnField('.adyen-checkout__issuer-list', 'issuer-list');\n }\n }, [data, valid, errors, isValid]);\n\n this.showValidation = () => {\n triggerValidation();\n };\n\n const { highlightedItems } = items.reduce(\n (memo, item) => {\n if (highlightedIds.includes(item.id)) memo.highlightedItems.push({ ...item });\n return memo;\n },\n { highlightedItems: [] }\n );\n\n return (\n <div className=\"adyen-checkout__issuer-list\">\n {!!highlightedItems.length && (\n <Fragment>\n <IssuerButtonGroup\n selectedIssuerId={inputType === IssuerListInputTypes.ButtonGroup ? data['issuer'] : null}\n items={highlightedItems}\n onChange={handleInputChange(IssuerListInputTypes.ButtonGroup)}\n />\n <ContentSeparator />\n </Fragment>\n )}\n\n <Field\n label={i18n.get('issuerList.selectField.label')}\n errorMessage={getErrorMessage(errors.issuer)}\n classNameModifiers={['issuer-list']}\n name={'issuer'}\n showContextualElement={showContextualElement}\n contextualText={contextualText}\n >\n <Select\n items={items}\n selectedValue={inputType === IssuerListInputTypes.Dropdown ? data['issuer'] : null}\n placeholder={placeholder}\n name={'issuer'}\n className={'adyen-checkout__issuer-list__dropdown'}\n onChange={handleInputChange(IssuerListInputTypes.Dropdown)}\n onListToggle={handleListToggle}\n onInput={handleSearch}\n />\n </Field>\n\n {props.termsAndConditions && (\n <div className=\"adyen-checkout__issuer-list__termsAndConditions\">\n <DisclaimerMessage message={i18n.get(props.termsAndConditions.translationKey)} urls={props.termsAndConditions.urls} />\n </div>\n )}\n\n {props.showPayButton &&\n props.payButton({\n status,\n label: payButtonLabel({ issuer: data['issuer'], items: [...items, ...highlightedItems] }, i18n)\n })}\n </div>\n );\n}\n\nIssuerList.defaultProps = {\n onChange: () => {}\n};\n\nexport default IssuerList;\n"],"names":["payButtonLabel","issuer","items","i18n","issuerName","find","i","id","name","get","schema","validationRules","validate","length","errorMessage","modes","IssuerList","placeholder","highlightedIds","showContextualElement","contextualText","props","useCoreContext","handleChangeFor","triggerValidation","data","valid","errors","isValid","useForm","defaultData","rules","status","setStatus","useState","inputType","setInputType","setSRMessagesFromObjects","shouldMoveFocusSR","useSRPanelContext","setSRMessages","this","newStatus","handleInputChange","useCallback","type","event","target","ANALYTICS_LIST","ANALYTICS_FEATURED_ISSUER","issuerObj","value","onSubmitAnalytics","ANALYTICS_SELECTED_STR","handleListToggle","isOpen","ANALYTICS_DISPLAYED_STR","debounceSearchAnalytics","useRef","debounce","ANALYTICS_SEARCH_DEBOUNCE_TIME","handleSearch","current","ANALYTICS_INPUT_STR","ANALYTICS_LIST_SEARCH","useEffect","onChange","srPanelResp","isValidating","action","ERROR_ACTION_FOCUS_FIELD","setFocusOnField","showValidation","highlightedItems","reduce","memo","item","includes","push","h","div","className","Fragment","IssuerButtonGroup","selectedIssuerId","ContentSeparator","Field","label","error","classNameModifiers","Select","selectedValue","onListToggle","onInput","termsAndConditions","DisclaimerMessage","message","translationKey","urls","showPayButton","payButton","defaultProps"],"mappings":"mjCA6BA,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,EAAM8E,eACH9E,EAAM+E,UAAU,CACZpE,SACAuD,MAAOvF,EAAe,CAAEC,OAAQwB,EAAc,OAAEvB,MAAO,IAAIA,KAAUuE,IAAqBtE,MA9FlFqF,IAAAA,CAkG5B,CAEAxE,EAAWqF,aAAe,CACtBnC,SAAU"}
|
|
1
|
+
{"version":3,"file":"IssuerList.js","sources":["../../../../../src/components/internal/IssuerList/IssuerList.tsx"],"sourcesContent":["import { Fragment, h } from 'preact';\nimport { useState, useEffect, useCallback, useRef } from 'preact/hooks';\nimport useForm from '../../../utils/useForm';\nimport Field from '../FormFields/Field';\nimport IssuerButtonGroup from './IssuerButtonGroup';\nimport ContentSeparator from '../ContentSeparator';\nimport { useCoreContext } from '../../../core/Context/CoreProvider';\nimport { ValidatorRules } from '../../../utils/Validator/types';\nimport { IssuerListProps } from './types';\nimport './IssuerList.scss';\nimport useSRPanelContext from '../../../core/Errors/useSRPanelContext';\nimport { SetSRMessagesReturnFn } from '../../../core/Errors/SRPanelProvider';\nimport { SetSRMessagesReturnObject } from '../../../core/Errors/types';\nimport { ERROR_ACTION_FOCUS_FIELD } from '../../../core/Errors/constants';\nimport { setFocusOnField } from '../../../utils/setFocus';\nimport DisclaimerMessage from '../DisclaimerMessage';\nimport Select from '../FormFields/Select';\nimport { SelectTargetObject } from '../FormFields/Select/types';\nimport {\n ANALYTICS_DISPLAYED_STR,\n ANALYTICS_FEATURED_ISSUER,\n ANALYTICS_INPUT_STR,\n ANALYTICS_LIST,\n ANALYTICS_LIST_SEARCH,\n ANALYTICS_SEARCH_DEBOUNCE_TIME,\n ANALYTICS_SELECTED_STR\n} from '../../../core/Analytics/constants';\nimport { debounce } from '../../../utils/debounce';\nimport { AnalyticsInfoEvent } from '../../../core/Analytics/AnalyticsInfoEvent';\n\nconst payButtonLabel = ({ issuer, items }, i18n): string => {\n const issuerName = items.find(i => i.id === issuer)?.name;\n if (!issuer || !issuerName) return i18n.get('continue');\n return `${i18n.get('continueTo')} ${issuerName}`;\n};\n\nconst schema = ['issuer'];\nconst validationRules: ValidatorRules = {\n issuer: {\n validate: issuer => !!issuer && issuer.length > 0,\n errorMessage: 'issuerList.selectField.contextualText',\n modes: ['blur']\n }\n};\n\nenum IssuerListInputTypes {\n ButtonGroup,\n Dropdown\n}\n\nfunction IssuerList({ items, placeholder, issuer, highlightedIds = [], showContextualElement, contextualText, ...props }: IssuerListProps) {\n const { i18n } = useCoreContext();\n const { handleChangeFor, triggerValidation, data, valid, errors, isValid } = useForm({\n schema,\n defaultData: { issuer },\n rules: validationRules\n });\n const [status, setStatus] = useState('ready');\n const [inputType, setInputType] = useState<IssuerListInputTypes>(IssuerListInputTypes.Dropdown);\n\n const { setSRMessagesFromObjects, shouldMoveFocusSR } = useSRPanelContext();\n const setSRMessages: SetSRMessagesReturnFn = setSRMessagesFromObjects?.({});\n\n const getErrorMessage = error => (error && error.errorMessage ? i18n.get(error.errorMessage) : !!error);\n\n this.setStatus = newStatus => {\n setStatus(newStatus);\n };\n\n const handleInputChange = useCallback(\n (type: IssuerListInputTypes) => (event: h.JSX.TargetedKeyboardEvent<HTMLInputElement>) => {\n const target = type === IssuerListInputTypes.Dropdown ? ANALYTICS_LIST : ANALYTICS_FEATURED_ISSUER;\n const issuerObj = items.find(issuer => issuer.id === (event.target as SelectTargetObject).value);\n\n const analyticsEvent = new AnalyticsInfoEvent({\n type: ANALYTICS_SELECTED_STR,\n target,\n issuer: issuerObj.name\n });\n props.onSubmitAnalytics(analyticsEvent);\n\n setInputType(type);\n handleChangeFor('issuer')(event);\n },\n [handleChangeFor]\n );\n\n const handleListToggle = useCallback((isOpen: boolean) => {\n if (isOpen) {\n const event = new AnalyticsInfoEvent({\n type: ANALYTICS_DISPLAYED_STR,\n target: ANALYTICS_LIST\n });\n props.onSubmitAnalytics(event);\n }\n }, []);\n\n const debounceSearchAnalytics = useRef(debounce(props.onSubmitAnalytics, ANALYTICS_SEARCH_DEBOUNCE_TIME));\n\n const handleSearch = useCallback(() => {\n debounceSearchAnalytics.current({ type: ANALYTICS_INPUT_STR, target: ANALYTICS_LIST_SEARCH });\n }, []);\n\n useEffect(() => {\n props.onChange({ data, valid, errors, isValid });\n\n const srPanelResp: SetSRMessagesReturnObject = setSRMessages?.({ errors, isValidating: true });\n if (srPanelResp?.action === ERROR_ACTION_FOCUS_FIELD) {\n // Focus field in error, if required\n if (shouldMoveFocusSR) setFocusOnField('.adyen-checkout__issuer-list', 'issuer-list');\n }\n }, [data, valid, errors, isValid]);\n\n this.showValidation = () => {\n triggerValidation();\n };\n\n const { highlightedItems } = items.reduce(\n (memo, item) => {\n if (highlightedIds.includes(item.id)) memo.highlightedItems.push({ ...item });\n return memo;\n },\n { highlightedItems: [] }\n );\n\n return (\n <div className=\"adyen-checkout__issuer-list\">\n {!!highlightedItems.length && (\n <Fragment>\n <IssuerButtonGroup\n selectedIssuerId={inputType === IssuerListInputTypes.ButtonGroup ? data['issuer'] : null}\n items={highlightedItems}\n onChange={handleInputChange(IssuerListInputTypes.ButtonGroup)}\n />\n <ContentSeparator />\n </Fragment>\n )}\n\n <Field\n label={i18n.get('issuerList.selectField.label')}\n errorMessage={getErrorMessage(errors.issuer)}\n classNameModifiers={['issuer-list']}\n name={'issuer'}\n showContextualElement={showContextualElement}\n contextualText={contextualText}\n >\n <Select\n items={items}\n selectedValue={inputType === IssuerListInputTypes.Dropdown ? data['issuer'] : null}\n placeholder={placeholder}\n name={'issuer'}\n className={'adyen-checkout__issuer-list__dropdown'}\n onChange={handleInputChange(IssuerListInputTypes.Dropdown)}\n onListToggle={handleListToggle}\n onInput={handleSearch}\n />\n </Field>\n\n {props.termsAndConditions && (\n <div className=\"adyen-checkout__issuer-list__termsAndConditions\">\n <DisclaimerMessage message={i18n.get(props.termsAndConditions.translationKey)} urls={props.termsAndConditions.urls} />\n </div>\n )}\n\n {props.showPayButton &&\n props.payButton({\n status,\n label: payButtonLabel({ issuer: data['issuer'], items: [...items, ...highlightedItems] }, i18n)\n })}\n </div>\n );\n}\n\nIssuerList.defaultProps = {\n onChange: () => {}\n};\n\nexport default IssuerList;\n"],"names":["payButtonLabel","issuer","items","i18n","issuerName","find","i","id","name","get","schema","validationRules","validate","length","errorMessage","modes","IssuerList","placeholder","highlightedIds","showContextualElement","contextualText","props","useCoreContext","handleChangeFor","triggerValidation","data","valid","errors","isValid","useForm","defaultData","rules","status","setStatus","useState","inputType","setInputType","setSRMessagesFromObjects","shouldMoveFocusSR","useSRPanelContext","setSRMessages","this","newStatus","handleInputChange","useCallback","type","event","target","ANALYTICS_LIST","ANALYTICS_FEATURED_ISSUER","issuerObj","value","analyticsEvent","AnalyticsInfoEvent","ANALYTICS_SELECTED_STR","onSubmitAnalytics","handleListToggle","isOpen","ANALYTICS_DISPLAYED_STR","debounceSearchAnalytics","useRef","debounce","ANALYTICS_SEARCH_DEBOUNCE_TIME","handleSearch","current","ANALYTICS_INPUT_STR","ANALYTICS_LIST_SEARCH","useEffect","onChange","srPanelResp","isValidating","action","ERROR_ACTION_FOCUS_FIELD","setFocusOnField","showValidation","highlightedItems","reduce","memo","item","includes","push","h","div","className","Fragment","IssuerButtonGroup","selectedIssuerId","ContentSeparator","Field","label","error","classNameModifiers","Select","selectedValue","onListToggle","onInput","termsAndConditions","DisclaimerMessage","message","translationKey","urls","showPayButton","payButton","defaultProps"],"mappings":"soCA8BA,MAAMA,EAAiB,EAAGC,SAAQC,SAASC,KACvC,MAAMC,EAAaF,EAAMG,MAAKC,GAAKA,EAAEC,KAAON,KAASO,KACrD,OAAKP,GAAWG,EACT,GAAGD,EAAKM,IAAI,iBAAiBL,IADDD,EAAKM,IAAI,WACI,EAG9CC,EAAS,CAAC,UACVC,EAAkC,CACpCV,OAAQ,CACJW,SAAUX,KAAYA,GAAUA,EAAOY,OAAS,EAChDC,aAAc,wCACdC,MAAO,CAAC,UAShB,SAASC,GAAWd,MAAEA,EAAKe,YAAEA,EAAWhB,OAAEA,EAAMiB,eAAEA,EAAiB,GAAEC,sBAAEA,EAAqBC,eAAEA,KAAmBC,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EA,GAAqBzE,EAAM0E,QAC/B,CAACC,EAAMC,KACC5D,EAAe6D,SAASD,EAAKvE,KAAKsE,EAAKF,iBAAiBK,KAAK,IAAKF,IAC/DD,IAEX,CAAEF,iBAAkB,KAGxB,OACIM,EAACC,MAAAA,CAAIC,UAAU,iCACRR,EAAiB9D,QAChBoE,EAACG,OACGH,EAACI,EAAAA,CACGC,iBAAmE7D,IAAjDU,EAAiDV,EAAK,OAAY,KACpFvB,MAAOyE,EACPP,SAAUzB,EAAAA,KAEdsC,EAACM,SAITN,EAACO,EAAAA,CACGC,MAAOtF,EAAKM,IAAI,gCAChBK,cA7EY4E,GA6EkB/D,EAAO1B,OA7EfyF,IAASA,GAAM5E,aAAeX,EAAKM,IAAIiF,GAAM5E,gBAAkB4E,IA8ErFC,mBAAoB,CAAC,eACrBnF,KAAM,SACNW,sBAAuBA,EACvBC,eAAgBA,GAEhB6D,EAACW,EAAAA,CACG1F,MAAOA,EACP2F,cAA6DpE,IAA9CU,EAA8CV,EAAK,OAAY,KAC9ER,YAAaA,EACbT,KAAM,SACN2E,UAAW,wCACXf,SAAUzB,EAAAA,GACVmD,aAActC,EACduC,QAAShC,KAIhB1C,EAAM2E,oBACHf,EAACC,MAAAA,CAAIC,UAAU,mDACXF,EAACgB,EAAAA,CAAkBC,QAAS/F,EAAKM,IAAIY,EAAM2E,mBAAmBG,gBAAiBC,KAAM/E,EAAM2E,mBAAmBI,QAIrH/E,EAAMgF,eACHhF,EAAMiF,UAAU,CACZtE,SACAyD,MAAOzF,EAAe,CAAEC,OAAQwB,EAAc,OAAEvB,MAAO,IAAIA,KAAUyE,IAAqBxE,MAxGlFuF,IAAAA,EA4G5B,CAEA1E,EAAWuF,aAAe,CACtBnC,SAAU"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","sources":["../../../../../src/components/internal/OpenInvoice/utils.ts"],"sourcesContent":["import { OpenInvoiceActiveFieldsets, OpenInvoiceStateData, OpenInvoiceVisibility } from './types';\nimport Language from '../../../language';\nimport { mapFieldKey as mapFieldKeyAddress } from '../Address/utils';\nimport { StringObject } from '../Address/types';\n\nexport const fieldsetsSchema: Array<keyof OpenInvoiceStateData> = [\n 'companyDetails',\n 'personalDetails',\n 'billingAddress',\n 'deliveryAddress',\n 'bankAccount'\n];\n\nconst isPrefilled = (fieldsetData: object = {}): boolean => Object.keys(fieldsetData).length > 1;\n\nexport const getActiveFieldsData = (activeFieldsets: OpenInvoiceActiveFieldsets, data: OpenInvoiceStateData): OpenInvoiceStateData =>\n Object.keys(data)\n .filter(fieldset => activeFieldsets[fieldset])\n .reduce((acc, cur) => {\n acc[cur] = data[cur];\n return acc;\n }, {});\n\nexport const getInitialActiveFieldsets = (visibility: OpenInvoiceVisibility, data: OpenInvoiceStateData = {}): OpenInvoiceActiveFieldsets =>\n fieldsetsSchema.reduce((acc, fieldset) => {\n const isVisible = visibility[fieldset] !== 'hidden';\n const isDeliveryAddress = fieldset === 'deliveryAddress';\n const billingAddressIsHidden = visibility?.billingAddress === 'hidden';\n\n // The delivery address will be active not only when set as visible\n // but also when the billing address is hidden or when it has prefilled data\n acc[fieldset] = isVisible && (!isDeliveryAddress || billingAddressIsHidden || isPrefilled(data[fieldset]));\n return acc;\n }, {} as OpenInvoiceActiveFieldsets);\n\n/**\n * Used by the SRPanel sorting function to tell it whether we need to add the field type to the SR panel message, and, if so, we retrieve the correct translation for the field type.\n * (Whether we need to add the field type depends on whether we know that the error message correctly reflects the label of the field. Ultimately all error messages should do this\n * and this mapping fn will become redundant)\n */\nexport const mapFieldKey = (key: string, i18n: Language, countrySpecificLabels: StringObject): string => {\n let refKey = key;\n let label;\n\n // Differentiate between address types (billing and delivery)\n const splitKey = refKey.split(':');\n const hasSplitKey = splitKey.length > 1;\n if (hasSplitKey) {\n label = splitKey[0];\n refKey = splitKey[1];\n }\n\n const addressKey = mapFieldKeyAddress(refKey, i18n, countrySpecificLabels);\n // Also use the presence of a label to know that we are dealing with address related fields. (This matters now that addresses can contain first & last name fields.)\n if (addressKey && label) return hasSplitKey ? `${i18n.get(label)} ${addressKey}` : addressKey;\n\n switch (refKey) {\n case 'dateOfBirth':\n case 'shopperEmail':\n case 'telephoneNumber':\n return i18n.get(refKey);\n default:\n break;\n }\n\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\n return null;\n};\n"],"names":["fieldsetsSchema","getActiveFieldsData","activeFieldsets","data","Object","keys","filter","fieldset","reduce","acc","cur","getInitialActiveFieldsets","visibility","isVisible","isDeliveryAddress","billingAddressIsHidden","billingAddress","fieldsetData","length","isPrefilled","mapFieldKey","key","i18n","countrySpecificLabels","label","refKey","splitKey","split","hasSplitKey","addressKey","mapFieldKeyAddress","get"],"mappings":"wDAKaA,EAAqD,CAC9D,iBACA,kBACA,iBACA,kBACA,eAKSC,EAAsB,CAACC,EAA6CC,IAC7EC,OAAOC,KAAKF,GACPG,QAAOC,GAAYL,EAAgBK,KACnCC,QAAO,CAACC,EAAKC,KACVD,EAAIC,GAAOP,EAAKO,GACTD,IACR,CAAI,GAEFE,EAA4B,CAACC,EAAmCT,EAA6B,CAAA,IACtGH,EAAgBQ,QAAO,CAACC,EAAKF,KACzB,MAAMM,EAAqC,WAAzBD,EAAWL,GACvBO,EAAiC,oBAAbP,EACpBQ,EAAwD,WAA/BH,GAAYI,eAK3C,OADAP,EAAIF,GAAYM,KAAeC,GAAqBC,GAlBxC,EAACE,EAAuB,KAAgBb,OAAOC,KAAKY,GAAcC,OAAS,EAkBTC,CAAYhB,EAAKI,KACxFE,CAAAA,GACR,CAAkC,GAO5BW,EAAc,CAACC,EAAaC,EAAgBC,KACrD,IACIC,EADAC,EAASJ,EAIb,MAAMK,EAAWD,EAAOE,MAAM,KACxBC,EAAcF,EAASR,OAAS,
|
|
1
|
+
{"version":3,"file":"utils.js","sources":["../../../../../src/components/internal/OpenInvoice/utils.ts"],"sourcesContent":["import { OpenInvoiceActiveFieldsets, OpenInvoiceStateData, OpenInvoiceVisibility } from './types';\nimport Language from '../../../language';\nimport { mapFieldKey as mapFieldKeyAddress } from '../Address/utils';\nimport { StringObject } from '../Address/types';\n\nexport const fieldsetsSchema: Array<keyof OpenInvoiceStateData> = [\n 'companyDetails',\n 'personalDetails',\n 'billingAddress',\n 'deliveryAddress',\n 'bankAccount'\n];\n\nconst isPrefilled = (fieldsetData: object = {}): boolean => Object.keys(fieldsetData).length > 1;\n\nexport const getActiveFieldsData = (activeFieldsets: OpenInvoiceActiveFieldsets, data: OpenInvoiceStateData): OpenInvoiceStateData =>\n Object.keys(data)\n .filter(fieldset => activeFieldsets[fieldset])\n .reduce((acc, cur) => {\n acc[cur] = data[cur];\n return acc;\n }, {});\n\nexport const getInitialActiveFieldsets = (visibility: OpenInvoiceVisibility, data: OpenInvoiceStateData = {}): OpenInvoiceActiveFieldsets =>\n fieldsetsSchema.reduce((acc, fieldset) => {\n const isVisible = visibility[fieldset] !== 'hidden';\n const isDeliveryAddress = fieldset === 'deliveryAddress';\n const billingAddressIsHidden = visibility?.billingAddress === 'hidden';\n\n // The delivery address will be active not only when set as visible\n // but also when the billing address is hidden or when it has prefilled data\n acc[fieldset] = isVisible && (!isDeliveryAddress || billingAddressIsHidden || isPrefilled(data[fieldset]));\n return acc;\n }, {} as OpenInvoiceActiveFieldsets);\n\n/**\n * Used by the SRPanel sorting function to tell it whether we need to add the field type to the SR panel message, and, if so, we retrieve the correct translation for the field type.\n * (Whether we need to add the field type depends on whether we know that the error message correctly reflects the label of the field. Ultimately all error messages should do this\n * and this mapping fn will become redundant)\n */\nexport const mapFieldKey = (key: string, i18n: Language, countrySpecificLabels: StringObject): string => {\n let refKey = key;\n let label;\n\n // Differentiate between address types (billing and delivery)\n const splitKey = refKey.split(':');\n const hasSplitKey = splitKey.length > 1;\n\n if (hasSplitKey) {\n label = splitKey[0];\n refKey = splitKey[1];\n }\n\n const addressKey = mapFieldKeyAddress(refKey, i18n, countrySpecificLabels);\n // Also use the presence of a label to know that we are dealing with address related fields. (This matters now that addresses can contain first & last name fields.)\n if (addressKey && label) return hasSplitKey ? `${i18n.get(label)} ${addressKey}` : addressKey;\n\n switch (refKey) {\n case 'dateOfBirth':\n case 'shopperEmail':\n case 'telephoneNumber':\n return i18n.get(refKey);\n default:\n break;\n }\n\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\n return null;\n};\n"],"names":["fieldsetsSchema","getActiveFieldsData","activeFieldsets","data","Object","keys","filter","fieldset","reduce","acc","cur","getInitialActiveFieldsets","visibility","isVisible","isDeliveryAddress","billingAddressIsHidden","billingAddress","fieldsetData","length","isPrefilled","mapFieldKey","key","i18n","countrySpecificLabels","label","refKey","splitKey","split","hasSplitKey","addressKey","mapFieldKeyAddress","get"],"mappings":"wDAKaA,EAAqD,CAC9D,iBACA,kBACA,iBACA,kBACA,eAKSC,EAAsB,CAACC,EAA6CC,IAC7EC,OAAOC,KAAKF,GACPG,QAAOC,GAAYL,EAAgBK,KACnCC,QAAO,CAACC,EAAKC,KACVD,EAAIC,GAAOP,EAAKO,GACTD,IACR,CAAI,GAEFE,EAA4B,CAACC,EAAmCT,EAA6B,CAAA,IACtGH,EAAgBQ,QAAO,CAACC,EAAKF,KACzB,MAAMM,EAAqC,WAAzBD,EAAWL,GACvBO,EAAiC,oBAAbP,EACpBQ,EAAwD,WAA/BH,GAAYI,eAK3C,OADAP,EAAIF,GAAYM,KAAeC,GAAqBC,GAlBxC,EAACE,EAAuB,KAAgBb,OAAOC,KAAKY,GAAcC,OAAS,EAkBTC,CAAYhB,EAAKI,KACxFE,CAAAA,GACR,CAAkC,GAO5BW,EAAc,CAACC,EAAaC,EAAgBC,KACrD,IACIC,EADAC,EAASJ,EAIb,MAAMK,EAAWD,EAAOE,MAAM,KACxBC,EAAcF,EAASR,OAAS,EAElCU,IACAJ,EAAQE,EAAS,GACjBD,EAASC,EAAS,IAGtB,MAAMG,EAAaC,EAAmBL,EAAQH,EAAMC,GAEpD,GAAIM,GAAcL,EAAO,OAAOI,EAAc,GAAGN,EAAKS,IAAIP,MAAUK,IAAeA,EAEnF,OAAQJ,GACJ,IAAK,cACL,IAAK,eACL,IAAK,kBACD,OAAOH,EAAKS,IAAIN,GAMxB,OAAO,IAAA"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{Component as t,createElement as e}from"../../../external/preact/dist/preact.js";import o from"../Countdown/index.js";import r from"../Button/Button.js";import s from"../Spinner/Spinner.js";import a from"../../../core/Services/payment-status.js";import{processResponse as i}from"../../../core/ProcessResponse/process-response.js";import{copyToClipboard as n}from"../../../utils/clipboard.js";import c from"../../../core/Errors/AdyenCheckoutError.js";import{useCoreContext as p}from"../../../core/Context/CoreProvider.js";import d from"../ContentSeparator/ContentSeparator.js";import l from"../../../core/Context/useImage.js";import{useA11yReporter as m}from"../../../core/Errors/useA11yReporter.js";import u from"../../../utils/useAutoFocus.js";import{ANALYTICS_QR_CODE_DOWNLOAD as h,ANALYTICS_DOWNLOAD_STR as _}from"../../../core/Analytics/constants.js";import{PREFIX as y}from"../Icon/constants.js";function
|
|
1
|
+
import{Component as t,createElement as e}from"../../../external/preact/dist/preact.js";import o from"../Countdown/index.js";import r from"../Button/Button.js";import s from"../Spinner/Spinner.js";import a from"../../../core/Services/payment-status.js";import{processResponse as i}from"../../../core/ProcessResponse/process-response.js";import{copyToClipboard as n}from"../../../utils/clipboard.js";import c from"../../../core/Errors/AdyenCheckoutError.js";import{useCoreContext as p}from"../../../core/Context/CoreProvider.js";import d from"../ContentSeparator/ContentSeparator.js";import l from"../../../core/Context/useImage.js";import{useA11yReporter as m}from"../../../core/Errors/useA11yReporter.js";import u from"../../../utils/useAutoFocus.js";import{ANALYTICS_QR_CODE_DOWNLOAD as h,ANALYTICS_DOWNLOAD_STR as _}from"../../../core/Analytics/constants.js";import{PREFIX as y}from"../Icon/constants.js";import{AnalyticsInfoEvent as g}from"../../../core/Analytics/AnalyticsInfoEvent.js";function f(t,e,o){return e in t?Object.defineProperty(t,e,{value:o,enumerable:!0,configurable:!0,writable:!0}):t[e]=o,t}class k extends t{componentDidMount(){this.statusInterval()}componentWillUnmount(){clearTimeout(this.timeoutId)}pollStatus(t){clearTimeout(this.timeoutId),this.timeoutId=setTimeout((async()=>{const t=performance.now();await this.checkStatus();const e=performance.now();this.statusInterval(Math.round(e-t))}),t)}render({amount:t,url:a,brandLogo:i,brandName:c,countdownTime:f,type:k,onActionHandled:q},{expired:v,completed:b,loading:C}){const{i18n:w,loadingContext:N}=p(),I=l(),T=this.props.qrCodeData?`${N}utility/v1/barcode.png?type=qrCode&data=${this.props.qrCodeData}&clientKey=${this.props.clientKey}`:this.props.qrCodeImage,j=(t,o)=>{const r=w.get(o);return m(r),e("div",{className:"adyen-checkout__qr-loader adyen-checkout__qr-loader--result"},e("img",{className:"adyen-checkout__qr-loader__icon adyen-checkout__qr-loader__icon--result",src:I({imageFolder:"components/"})(t),alt:r}),e("div",{className:"adyen-checkout__qr-loader__subtitle"},r))};if(v)return j("error","error.subtitle.payment");if(b)return j("success","creditCard.success");if(C)return e("div",{className:"adyen-checkout__qr-loader"},i&&e("div",{className:"adyen-checkout__qr-loader__brand-logo-wrapper"},e("img",{alt:c,src:i,className:"adyen-checkout__qr-loader__brand-logo"})),e(s,null));const S=w.get(this.props.timeToPay).split("%@"),x=u(),E=this.props.classNameModifiers.map((t=>`adyen-checkout__qr-loader--${t}`));return e("div",{className:`adyen-checkout__qr-loader adyen-checkout__qr-loader--${k} ${E.join(" ")}`},i&&e("div",{className:"adyen-checkout__qr-loader__brand-logo-wrapper"},e("img",{src:i,alt:c,className:"adyen-checkout__qr-loader__brand-logo"})),t&&t.value&&t.currency&&e("div",{className:"adyen-checkout__qr-loader__payment_amount"},w.amount(t.value,t.currency)),a&&e("div",{className:"adyen-checkout__qr-loader__app-link"},this.props.redirectIntroduction&&e("div",{className:"adyen-checkout__qr-loader__subtitle"},w.get(this.props.redirectIntroduction)),e(r,{classNameModifiers:["qr-loader"],onClick:()=>this.redirectToApp(a),label:w.get(this.props.buttonLabel)}),e(d,null)),e("div",{ref:x,tabIndex:0,className:"adyen-checkout__qr-loader__subtitle"},"string"==typeof this.props.introduction?w.get(this.props.introduction):this.props.introduction?.()),e("img",{src:T,alt:w.get("wechatpay.scanqrcode"),onLoad:()=>{q?.({componentType:this.props.type,actionDescription:"qr-code-loaded"})}}),e("div",{className:"adyen-checkout__qr-loader__progress"},e("span",{className:"adyen-checkout__qr-loader__percentage",style:{width:`${this.state.percentage}%`}})),e("div",{className:"adyen-checkout__qr-loader__countdown"},S[0]," ",e(o,{minutesFromNow:f,onTick:this.onTick,onCompleted:this.onTimeUp})," ",S[1]),this.props.instructions&&e("div",{className:"adyen-checkout__qr-loader__instructions"},"string"==typeof this.props.instructions?w.get(this.props.instructions):this.props.instructions?.()),this.props.copyBtn&&e("div",{className:"adyen-checkout__qr-loader__actions"},e(r,{inline:!0,variant:"action",onClick:(t,{complete:e})=>{n(this.props.qrCodeData);const o=new g({type:_,target:h});this.props.onSubmitAnalytics(o),e()},icon:I({imageFolder:"components/"})(`${y}copy`),label:w.get("button.copy")})))}constructor(t){super(t),f(this,"timeoutId",void 0),f(this,"redirectToApp",(t=>{window.location.assign(t)})),f(this,"statusInterval",((t=0)=>{if(this.state.expired||this.state.completed)return;this.setState((e=>({timePassed:e.timePassed+this.props.delay+t})));const e=this.state.timePassed>=this.props.throttleTime?this.props.throttledInterval:this.state.delay;this.pollStatus(e)})),f(this,"onTick",(t=>{this.setState({percentage:t.percentage})})),f(this,"onTimeUp",(()=>{this.setState({expired:!0}),clearTimeout(this.timeoutId),this.props.onError(new c("ERROR","Payment Expired"))})),f(this,"onComplete",(t=>{clearTimeout(this.timeoutId),this.setState({completed:!0,loading:!1});const e={data:{details:{payload:t.props.payload},paymentData:this.props.paymentData}};this.props.onComplete(e,this)})),f(this,"onError",(t=>{if(clearTimeout(this.timeoutId),this.setState({expired:!0,loading:!1}),t.props.payload){const e={data:{details:{payload:t.props.payload},paymentData:this.props.paymentData}};this.props.onComplete(e,this)}const e=new c("ERROR","error result with no payload in response");return this.props.onError(e)})),f(this,"checkStatus",(()=>{const{paymentData:t,clientKey:e,loadingContext:o,throttledInterval:r}=this.props;return a(t,e,o,r).then(i).catch((t=>({type:"network-error",props:t}))).then((t=>{switch(t.type){case"success":this.onComplete(t);break;case"error":this.onError(t);break;default:this.setState({loading:!1})}return t}))})),this.state={buttonStatus:"default",completed:!1,delay:t.delay,expired:!1,loading:!0,percentage:100,timePassed:0}}}f(k,"defaultProps",{delay:2e3,countdownTime:15,onError:()=>{},onComplete:()=>{},throttleTime:6e4,classNameModifiers:[],throttledInterval:1e4,introduction:"wechatpay.scanqrcode",timeToPay:"wechatpay.timetopay",buttonLabel:"openApp"});export{k as default};
|
|
2
2
|
//# sourceMappingURL=QRLoader.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"QRLoader.js","sources":["../../../../../src/components/internal/QRLoader/QRLoader.tsx"],"sourcesContent":["import { Component, h } from 'preact';\nimport Countdown from '../Countdown';\nimport Button from '../Button';\nimport Spinner from '../Spinner';\nimport checkPaymentStatus from '../../../core/Services/payment-status';\nimport processResponse from '../../../core/ProcessResponse';\n\nimport './QRLoader.scss';\nimport { QRLoaderProps, QRLoaderState } from './types';\nimport copyToClipboard from '../../../utils/clipboard';\nimport AdyenCheckoutError from '../../../core/Errors/AdyenCheckoutError';\nimport { useCoreContext } from '../../../core/Context/CoreProvider';\nimport ContentSeparator from '../ContentSeparator';\nimport { StatusObject } from '../Await/types';\nimport useImage from '../../../core/Context/useImage';\nimport { useA11yReporter } from '../../../core/Errors/useA11yReporter';\nimport useAutoFocus from '../../../utils/useAutoFocus';\nimport { ANALYTICS_DOWNLOAD_STR, ANALYTICS_QR_CODE_DOWNLOAD } from '../../../core/Analytics/constants';\nimport { PREFIX } from '../Icon/constants';\n\nconst QRCODE_URL = 'utility/v1/barcode.png?type=qrCode&data=';\n\nclass QRLoader extends Component<QRLoaderProps, QRLoaderState> {\n private timeoutId;\n\n constructor(props) {\n super(props);\n\n this.state = {\n buttonStatus: 'default',\n completed: false,\n delay: props.delay,\n expired: false,\n loading: true,\n percentage: 100,\n timePassed: 0\n };\n }\n\n public static defaultProps = {\n delay: 2000,\n countdownTime: 15,\n onError: () => {},\n onComplete: () => {},\n throttleTime: 60000,\n classNameModifiers: [],\n throttledInterval: 10000,\n introduction: 'wechatpay.scanqrcode',\n timeToPay: 'wechatpay.timetopay',\n buttonLabel: 'openApp'\n };\n\n componentDidMount() {\n this.statusInterval();\n }\n\n componentWillUnmount() {\n clearTimeout(this.timeoutId);\n }\n\n public redirectToApp = (url: string | URL) => {\n window.location.assign(url);\n };\n\n // Retry until getting a complete response from the server, or it times out\n public statusInterval = (responseTime = 0) => {\n // If we are already in the final statuses, do not poll!\n if (this.state.expired || this.state.completed) return;\n\n this.setState(previous => ({ timePassed: previous.timePassed + this.props.delay + responseTime }));\n // Changes interval time to 10 seconds after 1 minute (60 seconds)\n const newDelay = this.state.timePassed >= this.props.throttleTime ? this.props.throttledInterval : this.state.delay;\n this.pollStatus(newDelay);\n };\n\n private pollStatus(delay: number) {\n clearTimeout(this.timeoutId);\n\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n this.timeoutId = setTimeout(async () => {\n // Wait for previous status call to finish.\n // Also taking the server response time into the consideration to calculate timePassed.\n const start = performance.now();\n await this.checkStatus();\n const end = performance.now();\n this.statusInterval(Math.round(end - start));\n }, delay);\n }\n\n private onTick = (time): void => {\n this.setState({ percentage: time.percentage });\n };\n\n private onTimeUp = (): void => {\n this.setState({ expired: true });\n clearTimeout(this.timeoutId);\n this.props.onError(new AdyenCheckoutError('ERROR', 'Payment Expired'));\n };\n\n private onComplete = (status: StatusObject): void => {\n clearTimeout(this.timeoutId);\n this.setState({ completed: true, loading: false });\n\n const state = {\n data: {\n details: { payload: status.props.payload },\n paymentData: this.props.paymentData\n }\n };\n\n this.props.onComplete(state, this);\n };\n\n private onError = (status: StatusObject): void => {\n clearTimeout(this.timeoutId);\n this.setState({ expired: true, loading: false });\n\n if (status.props.payload) {\n const state = {\n data: {\n details: { payload: status.props.payload },\n paymentData: this.props.paymentData\n }\n };\n this.props.onComplete(state, this);\n }\n\n const error = new AdyenCheckoutError('ERROR', 'error result with no payload in response');\n return this.props.onError(error);\n };\n\n private checkStatus = () => {\n const { paymentData, clientKey, loadingContext, throttledInterval } = this.props;\n\n return checkPaymentStatus(paymentData, clientKey, loadingContext, throttledInterval)\n .then(processResponse)\n .catch(response => ({ type: 'network-error', props: response }))\n .then((status: StatusObject) => {\n switch (status.type) {\n case 'success':\n this.onComplete(status);\n break;\n case 'error':\n this.onError(status);\n break;\n default:\n this.setState({ loading: false });\n }\n return status;\n });\n };\n\n render({ amount, url, brandLogo, brandName, countdownTime, type, onActionHandled }: QRLoaderProps, { expired, completed, loading }) {\n const { i18n, loadingContext } = useCoreContext();\n const getImage = useImage();\n\n const qrCodeImage = this.props.qrCodeData\n ? `${loadingContext}${QRCODE_URL}${this.props.qrCodeData}&clientKey=${this.props.clientKey}`\n : this.props.qrCodeImage;\n\n const finalState = (image, message) => {\n const status = i18n.get(message);\n useA11yReporter(status);\n return (\n <div className=\"adyen-checkout__qr-loader adyen-checkout__qr-loader--result\">\n <img\n className=\"adyen-checkout__qr-loader__icon adyen-checkout__qr-loader__icon--result\"\n src={getImage({ imageFolder: 'components/' })(image)}\n alt={status}\n />\n <div className=\"adyen-checkout__qr-loader__subtitle\">{status}</div>\n </div>\n );\n };\n\n if (expired) {\n return finalState('error', 'error.subtitle.payment');\n }\n\n if (completed) {\n return finalState('success', 'creditCard.success');\n }\n\n if (loading) {\n return (\n <div className=\"adyen-checkout__qr-loader\">\n {brandLogo && (\n <div className=\"adyen-checkout__qr-loader__brand-logo-wrapper\">\n <img alt={brandName} src={brandLogo} className=\"adyen-checkout__qr-loader__brand-logo\" />\n </div>\n )}\n <Spinner />\n </div>\n );\n }\n\n const timeToPayString = i18n.get(this.props.timeToPay).split('%@');\n\n const qrSubtitleRef = useAutoFocus();\n const classnames = this.props.classNameModifiers.map(m => `adyen-checkout__qr-loader--${m}`);\n\n return (\n <div className={`adyen-checkout__qr-loader adyen-checkout__qr-loader--${type} ${classnames.join(' ')}`}>\n {brandLogo && (\n <div className=\"adyen-checkout__qr-loader__brand-logo-wrapper\">\n <img src={brandLogo} alt={brandName} className=\"adyen-checkout__qr-loader__brand-logo\" />\n </div>\n )}\n\n {amount && amount.value && amount.currency && (\n <div className=\"adyen-checkout__qr-loader__payment_amount\">{i18n.amount(amount.value, amount.currency)}</div>\n )}\n\n {url && (\n <div className=\"adyen-checkout__qr-loader__app-link\">\n {this.props.redirectIntroduction && (\n <div className=\"adyen-checkout__qr-loader__subtitle\">{i18n.get(this.props.redirectIntroduction)}</div>\n )}\n <Button classNameModifiers={['qr-loader']} onClick={() => this.redirectToApp(url)} label={i18n.get(this.props.buttonLabel)} />\n <ContentSeparator />\n </div>\n )}\n\n {/* eslint-disable-next-line jsx-a11y/no-noninteractive-tabindex */}\n <div ref={qrSubtitleRef} tabIndex={0} className=\"adyen-checkout__qr-loader__subtitle\">\n {typeof this.props.introduction === 'string' ? i18n.get(this.props.introduction) : this.props.introduction?.()}\n </div>\n\n <img\n src={qrCodeImage}\n alt={i18n.get('wechatpay.scanqrcode')}\n onLoad={() => {\n onActionHandled?.({\n componentType: this.props.type,\n actionDescription: 'qr-code-loaded'\n });\n }}\n />\n\n <div className=\"adyen-checkout__qr-loader__progress\">\n <span className=\"adyen-checkout__qr-loader__percentage\" style={{ width: `${this.state.percentage}%` }} />\n </div>\n\n <div className=\"adyen-checkout__qr-loader__countdown\">\n {timeToPayString[0]} \n <Countdown minutesFromNow={countdownTime} onTick={this.onTick} onCompleted={this.onTimeUp} />\n {timeToPayString[1]}\n </div>\n\n {this.props.instructions && (\n <div className=\"adyen-checkout__qr-loader__instructions\">\n {typeof this.props.instructions === 'string' ? i18n.get(this.props.instructions) : this.props.instructions?.()}\n </div>\n )}\n\n {this.props.copyBtn && (\n <div className=\"adyen-checkout__qr-loader__actions\">\n <Button\n inline\n variant=\"action\"\n onClick={(e, { complete }) => {\n copyToClipboard(this.props.qrCodeData);\n this.props.onSubmitAnalytics({\n type: ANALYTICS_DOWNLOAD_STR,\n target: ANALYTICS_QR_CODE_DOWNLOAD\n });\n complete();\n }}\n icon={getImage({ imageFolder: 'components/' })(`${PREFIX}copy`)}\n label={i18n.get('button.copy')}\n />\n </div>\n )}\n </div>\n );\n }\n}\n\nexport default QRLoader;\n"],"names":["QRLoader","Component","componentDidMount","this","statusInterval","componentWillUnmount","clearTimeout","timeoutId","pollStatus","delay","setTimeout","async","start","performance","now","checkStatus","end","Math","round","render","amount","url","brandLogo","brandName","countdownTime","type","onActionHandled","expired","completed","loading","i18n","loadingContext","useCoreContext","getImage","useImage","qrCodeImage","props","qrCodeData","clientKey","finalState","image","message","status","get","useA11yReporter","h","div","className","img","src","imageFolder","alt","Spinner","timeToPayString","timeToPay","split","qrSubtitleRef","useAutoFocus","classnames","classNameModifiers","map","m","join","value","currency","redirectIntroduction","Button","onClick","redirectToApp","label","buttonLabel","ContentSeparator","ref","tabIndex","introduction","onLoad","componentType","actionDescription","span","style","width","state","percentage","Countdown","minutesFromNow","onTick","onCompleted","onTimeUp","instructions","copyBtn","inline","variant","e","complete","copyToClipboard","onSubmitAnalytics","ANALYTICS_DOWNLOAD_STR","target","ANALYTICS_QR_CODE_DOWNLOAD","icon","PREFIX","constructor","super","_define_property","window","location","assign","responseTime","setState","previous","timePassed","newDelay","throttleTime","throttledInterval","time","onError","AdyenCheckoutError","onComplete","data","details","payload","paymentData","error","checkPaymentStatus","then","processResponse","catch","response","buttonStatus","defaultProps"],"mappings":"mgCAsBA,MAAMA,UAAiBC,EA8BnBC,iBAAAA,GACIC,KAAKC,gBACT,CAEAC,oBAAAA,GACIC,aAAaH,KAAKI,UACtB,CAiBQC,UAAAA,CAAWC,GACfH,aAAaH,KAAKI,WAGlBJ,KAAKI,UAAYG,YAAWC,UAGxB,MAAMC,EAAQC,YAAYC,YACpBX,KAAKY,cACX,MAAMC,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
1
|
+
{"version":3,"file":"QRLoader.js","sources":["../../../../../src/components/internal/QRLoader/QRLoader.tsx"],"sourcesContent":["import { Component, h } from 'preact';\nimport Countdown from '../Countdown';\nimport Button from '../Button';\nimport Spinner from '../Spinner';\nimport checkPaymentStatus from '../../../core/Services/payment-status';\nimport processResponse from '../../../core/ProcessResponse';\n\nimport './QRLoader.scss';\nimport { QRLoaderProps, QRLoaderState } from './types';\nimport copyToClipboard from '../../../utils/clipboard';\nimport AdyenCheckoutError from '../../../core/Errors/AdyenCheckoutError';\nimport { useCoreContext } from '../../../core/Context/CoreProvider';\nimport ContentSeparator from '../ContentSeparator';\nimport { StatusObject } from '../Await/types';\nimport useImage from '../../../core/Context/useImage';\nimport { useA11yReporter } from '../../../core/Errors/useA11yReporter';\nimport useAutoFocus from '../../../utils/useAutoFocus';\nimport { ANALYTICS_DOWNLOAD_STR, ANALYTICS_QR_CODE_DOWNLOAD } from '../../../core/Analytics/constants';\nimport { PREFIX } from '../Icon/constants';\nimport { AnalyticsInfoEvent } from '../../../core/Analytics/AnalyticsInfoEvent';\n\nconst QRCODE_URL = 'utility/v1/barcode.png?type=qrCode&data=';\n\nclass QRLoader extends Component<QRLoaderProps, QRLoaderState> {\n private timeoutId;\n\n constructor(props) {\n super(props);\n\n this.state = {\n buttonStatus: 'default',\n completed: false,\n delay: props.delay,\n expired: false,\n loading: true,\n percentage: 100,\n timePassed: 0\n };\n }\n\n public static defaultProps = {\n delay: 2000,\n countdownTime: 15,\n onError: () => {},\n onComplete: () => {},\n throttleTime: 60000,\n classNameModifiers: [],\n throttledInterval: 10000,\n introduction: 'wechatpay.scanqrcode',\n timeToPay: 'wechatpay.timetopay',\n buttonLabel: 'openApp'\n };\n\n componentDidMount() {\n this.statusInterval();\n }\n\n componentWillUnmount() {\n clearTimeout(this.timeoutId);\n }\n\n public redirectToApp = (url: string | URL) => {\n window.location.assign(url);\n };\n\n // Retry until getting a complete response from the server, or it times out\n public statusInterval = (responseTime = 0) => {\n // If we are already in the final statuses, do not poll!\n if (this.state.expired || this.state.completed) return;\n\n this.setState(previous => ({ timePassed: previous.timePassed + this.props.delay + responseTime }));\n // Changes interval time to 10 seconds after 1 minute (60 seconds)\n const newDelay = this.state.timePassed >= this.props.throttleTime ? this.props.throttledInterval : this.state.delay;\n this.pollStatus(newDelay);\n };\n\n private pollStatus(delay: number) {\n clearTimeout(this.timeoutId);\n\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n this.timeoutId = setTimeout(async () => {\n // Wait for previous status call to finish.\n // Also taking the server response time into the consideration to calculate timePassed.\n const start = performance.now();\n await this.checkStatus();\n const end = performance.now();\n this.statusInterval(Math.round(end - start));\n }, delay);\n }\n\n private onTick = (time): void => {\n this.setState({ percentage: time.percentage });\n };\n\n private onTimeUp = (): void => {\n this.setState({ expired: true });\n clearTimeout(this.timeoutId);\n this.props.onError(new AdyenCheckoutError('ERROR', 'Payment Expired'));\n };\n\n private onComplete = (status: StatusObject): void => {\n clearTimeout(this.timeoutId);\n this.setState({ completed: true, loading: false });\n\n const state = {\n data: {\n details: { payload: status.props.payload },\n paymentData: this.props.paymentData\n }\n };\n\n this.props.onComplete(state, this);\n };\n\n private onError = (status: StatusObject): void => {\n clearTimeout(this.timeoutId);\n this.setState({ expired: true, loading: false });\n\n if (status.props.payload) {\n const state = {\n data: {\n details: { payload: status.props.payload },\n paymentData: this.props.paymentData\n }\n };\n this.props.onComplete(state, this);\n }\n\n const error = new AdyenCheckoutError('ERROR', 'error result with no payload in response');\n return this.props.onError(error);\n };\n\n private checkStatus = () => {\n const { paymentData, clientKey, loadingContext, throttledInterval } = this.props;\n\n return checkPaymentStatus(paymentData, clientKey, loadingContext, throttledInterval)\n .then(processResponse)\n .catch(response => ({ type: 'network-error', props: response }))\n .then((status: StatusObject) => {\n switch (status.type) {\n case 'success':\n this.onComplete(status);\n break;\n case 'error':\n this.onError(status);\n break;\n default:\n this.setState({ loading: false });\n }\n return status;\n });\n };\n\n render({ amount, url, brandLogo, brandName, countdownTime, type, onActionHandled }: QRLoaderProps, { expired, completed, loading }) {\n const { i18n, loadingContext } = useCoreContext();\n const getImage = useImage();\n\n const qrCodeImage = this.props.qrCodeData\n ? `${loadingContext}${QRCODE_URL}${this.props.qrCodeData}&clientKey=${this.props.clientKey}`\n : this.props.qrCodeImage;\n\n const finalState = (image, message) => {\n const status = i18n.get(message);\n useA11yReporter(status);\n return (\n <div className=\"adyen-checkout__qr-loader adyen-checkout__qr-loader--result\">\n <img\n className=\"adyen-checkout__qr-loader__icon adyen-checkout__qr-loader__icon--result\"\n src={getImage({ imageFolder: 'components/' })(image)}\n alt={status}\n />\n <div className=\"adyen-checkout__qr-loader__subtitle\">{status}</div>\n </div>\n );\n };\n\n if (expired) {\n return finalState('error', 'error.subtitle.payment');\n }\n\n if (completed) {\n return finalState('success', 'creditCard.success');\n }\n\n if (loading) {\n return (\n <div className=\"adyen-checkout__qr-loader\">\n {brandLogo && (\n <div className=\"adyen-checkout__qr-loader__brand-logo-wrapper\">\n <img alt={brandName} src={brandLogo} className=\"adyen-checkout__qr-loader__brand-logo\" />\n </div>\n )}\n <Spinner />\n </div>\n );\n }\n\n const timeToPayString = i18n.get(this.props.timeToPay).split('%@');\n\n const qrSubtitleRef = useAutoFocus();\n const classnames = this.props.classNameModifiers.map(m => `adyen-checkout__qr-loader--${m}`);\n\n return (\n <div className={`adyen-checkout__qr-loader adyen-checkout__qr-loader--${type} ${classnames.join(' ')}`}>\n {brandLogo && (\n <div className=\"adyen-checkout__qr-loader__brand-logo-wrapper\">\n <img src={brandLogo} alt={brandName} className=\"adyen-checkout__qr-loader__brand-logo\" />\n </div>\n )}\n\n {amount && amount.value && amount.currency && (\n <div className=\"adyen-checkout__qr-loader__payment_amount\">{i18n.amount(amount.value, amount.currency)}</div>\n )}\n\n {url && (\n <div className=\"adyen-checkout__qr-loader__app-link\">\n {this.props.redirectIntroduction && (\n <div className=\"adyen-checkout__qr-loader__subtitle\">{i18n.get(this.props.redirectIntroduction)}</div>\n )}\n <Button classNameModifiers={['qr-loader']} onClick={() => this.redirectToApp(url)} label={i18n.get(this.props.buttonLabel)} />\n <ContentSeparator />\n </div>\n )}\n\n {/* eslint-disable-next-line jsx-a11y/no-noninteractive-tabindex */}\n <div ref={qrSubtitleRef} tabIndex={0} className=\"adyen-checkout__qr-loader__subtitle\">\n {typeof this.props.introduction === 'string' ? i18n.get(this.props.introduction) : this.props.introduction?.()}\n </div>\n\n <img\n src={qrCodeImage}\n alt={i18n.get('wechatpay.scanqrcode')}\n onLoad={() => {\n onActionHandled?.({\n componentType: this.props.type,\n actionDescription: 'qr-code-loaded'\n });\n }}\n />\n\n <div className=\"adyen-checkout__qr-loader__progress\">\n <span className=\"adyen-checkout__qr-loader__percentage\" style={{ width: `${this.state.percentage}%` }} />\n </div>\n\n <div className=\"adyen-checkout__qr-loader__countdown\">\n {timeToPayString[0]} \n <Countdown minutesFromNow={countdownTime} onTick={this.onTick} onCompleted={this.onTimeUp} />\n {timeToPayString[1]}\n </div>\n\n {this.props.instructions && (\n <div className=\"adyen-checkout__qr-loader__instructions\">\n {typeof this.props.instructions === 'string' ? i18n.get(this.props.instructions) : this.props.instructions?.()}\n </div>\n )}\n\n {this.props.copyBtn && (\n <div className=\"adyen-checkout__qr-loader__actions\">\n <Button\n inline\n variant=\"action\"\n onClick={(e, { complete }) => {\n copyToClipboard(this.props.qrCodeData);\n\n const event = new AnalyticsInfoEvent({\n type: ANALYTICS_DOWNLOAD_STR,\n target: ANALYTICS_QR_CODE_DOWNLOAD\n });\n this.props.onSubmitAnalytics(event);\n\n complete();\n }}\n icon={getImage({ imageFolder: 'components/' })(`${PREFIX}copy`)}\n label={i18n.get('button.copy')}\n />\n </div>\n )}\n </div>\n );\n }\n}\n\nexport default QRLoader;\n"],"names":["QRLoader","Component","componentDidMount","this","statusInterval","componentWillUnmount","clearTimeout","timeoutId","pollStatus","delay","setTimeout","async","start","performance","now","checkStatus","end","Math","round","render","amount","url","brandLogo","brandName","countdownTime","type","onActionHandled","expired","completed","loading","i18n","loadingContext","useCoreContext","getImage","useImage","qrCodeImage","props","qrCodeData","clientKey","finalState","image","message","status","get","useA11yReporter","h","div","className","img","src","imageFolder","alt","Spinner","timeToPayString","timeToPay","split","qrSubtitleRef","useAutoFocus","classnames","classNameModifiers","map","m","join","value","currency","redirectIntroduction","Button","onClick","redirectToApp","label","buttonLabel","ContentSeparator","ref","tabIndex","introduction","onLoad","componentType","actionDescription","span","style","width","state","percentage","Countdown","minutesFromNow","onTick","onCompleted","onTimeUp","instructions","copyBtn","inline","variant","e","complete","copyToClipboard","event","AnalyticsInfoEvent","ANALYTICS_DOWNLOAD_STR","target","ANALYTICS_QR_CODE_DOWNLOAD","onSubmitAnalytics","icon","PREFIX","constructor","super","_define_property","window","location","assign","responseTime","setState","previous","timePassed","newDelay","throttleTime","throttledInterval","time","onError","AdyenCheckoutError","onComplete","data","details","payload","paymentData","error","checkPaymentStatus","then","processResponse","catch","response","buttonStatus","defaultProps"],"mappings":"slCAuBA,MAAMA,UAAiBC,EA8BnBC,iBAAAA,GACIC,KAAKC,gBACT,CAEAC,oBAAAA,GACIC,aAAaH,KAAKI,UACtB,CAiBQC,UAAAA,CAAWC,GACfH,aAAaH,KAAKI,WAGlBJ,KAAKI,UAAYG,YAAWC,UAGxB,MAAMC,EAAQC,YAAYC,YACpBX,KAAKY,cACX,MAAMC,EAAMH,YAAYC,MACxBX,KAAKC,eAAea,KAAKC,MAAMF,EAAMJ,GAAAA,GACtCH,EACP,CAiEAU,MAAAA,EAAOC,OAAEA,EAAMC,IAAEA,EAAGC,UAAEA,EAASC,UAAEA,EAASC,cAAEA,EAAaC,KAAEA,EAAIC,gBAAEA,IAAkCC,QAAEA,EAAOC,UAAEA,EAASC,QAAEA,IACrH,MAAMC,KAAEA,EAAIC,eAAEA,GAAmBC,IAC3BC,EAAWC,IAEXC,EAAchC,KAAKiC,MAAMC,WACzB,GAAGN,4CAA8B5B,KAAKiC,MAAMC,wBAAwBlC,KAAKiC,MAA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AAaxH,KAAKiC,MAAMuF,cAGhCxH,KAAKiC,MAAMmF,WAAWtC,EAAO9E,KACjC,CAEA,MAAMyH,EAAQ,IAAIN,EAAmB,QAAS,4CAC9C,OAAOnH,KAAKiC,MAAMiF,QAAQO,EAAAA,IAG9BnB,OAAQ1F,eAAc,KAClB,MAAM4G,YAAEA,EAAWrF,UAAEA,EAASP,eAAEA,EAAcoF,kBAAEA,GAAsBhH,KAAKiC,MAE3E,OAAOyF,EAAmBF,EAAarF,EAAWP,EAAgBoF,GAC7DW,KAAKC,GACLC,OAAMC,IAAa,CAAExG,KAAM,gBAAiBW,MAAO6F,MACnDH,MAAMpF,IACH,OAAQA,EAAOjB,MACX,IAAK,UACDtB,KAAKoH,WAAW7E,GAChB,MACJ,IAAK,QACDvC,KAAKkH,QAAQ3E,GACb,MACJ,QACIvC,KAAK2G,SAAS,CAAEjF,SAAS,IAEjC,OAAOa,CAAAA,GACX,IAzHJvC,KAAK8E,MAAQ,CACTiD,aAAc,UACdtG,WAAW,EACXnB,MAAO2B,EAAM3B,MACbkB,SAAS,EACTE,SAAS,EACTqD,WAAY,IACZ8B,WAAY,EAEpB,EAEAP,EAjBEzG,EAiBYmI,eAAe,CACzB1H,MAAO,IACPe,cAAe,GACf6F,QAAS,OACTE,WAAY,OACZL,aAAc,IACdvD,mBAAoB,GACpBwD,kBAAmB,IACnBzC,aAAc,uBACdpB,UAAW,sBACXgB,YAAa"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{Component as s}from"../../../../external/preact/dist/preact.js";import{getFields as t,validFieldsReducer as e,getErrorReducer as i,getErrorObject as o}from"./SFPUtils.js";import n from"../lib/CSF/initCSF.js";import r from"./SecuredFieldsProviderHandlers.js";import d from"./defaultProps.js";import{ENCRYPTED_PWD_FIELD as a,ENCRYPTED_CARD_NUMBER as h,DEDICATED_CARD_COMPONENTS as l,DATE_POLICY_REQUIRED as p,CVC_POLICY_REQUIRED as c}from"../lib/constants.js";import u from"../../../../core/Errors/AdyenCheckoutError.js";import{getErrorMessageFromCode as f}from"../../../../core/Errors/utils.js";import{SF_ErrorCodes as m}from"../../../../core/Errors/constants.js";function F(s,t,e){return t in s?Object.defineProperty(s,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):s[t]=e,s}class C extends s{componentDidMount(){this.props.rootNode&&this.setRootNode(this.props.rootNode);const s=t(this.rootNode),i=s.reduce(e,{});this.setState({valid:i}),s.forEach((s=>{this.numCharsInField[s]=0})),this.numDateFields=s.filter((s=>s.match(/Expiry/))).length,s.length?(this.destroy(),this.initializeCSF(this.rootNode)):this.handleOnNoDataRequired()}componentDidUpdate(){this.checkForKCPFields()}componentWillUnmount(){this.csf=null,clearTimeout(this.csfLoadFailTimeout),clearTimeout(this.csfConfigFailTimeout)}initializeCSF(s){let t=this.props.loadingContext;const e={rootNode:s,type:this.props.type,clientKey:this.props.clientKey,cardGroupTypes:this.props.brands,autoFocus:this.props.autoFocus,trimTrailingSeparator:this.props.trimTrailingSeparator,loadingContext:t,keypadFix:this.props.keypadFix,showWarnings:this.props.showWarnings,iframeUIConfig:{sfStyles:this.props.styles},i18n:this.props.i18n,callbacks:{onLoad:this.handleOnLoad,onConfigSuccess:this.handleOnConfigSuccess,onFieldValid:this.handleOnFieldValid,onAllValid:this.handleOnAllValid,onBrand:this.handleOnBrand,onError:this.handleOnError,onFocus:this.handleFocus,onBinValue:this.props.onBinValue,onAutoComplete:this.handleOnAutoComplete,onAdditionalSFConfig:this.props.onAdditionalSFConfig,onAdditionalSFRemoved:this.props.onAdditionalSFRemoved,onTouchstartIOS:this.handleOnTouchstartIOS,onKeyPressed:this.handleKeyPressed},isKCP:this.state.hasKoreanFields,legacyInputMode:this.props.legacyInputMode,minimumExpiryDate:this.props.minimumExpiryDate,implementationType:this.props.implementationType||"components",forceCompat:this.props.forceCompat,maskSecurityCode:this.props.maskSecurityCode,exposeExpiryDate:this.props.exposeExpiryDate,shouldDisableIOSArrowKeys:!!this.props.disableIOSArrowKeys,placeholders:this.props.placeholders??{},showContextualElement:this.props.showContextualElement};this.csf=n(e),this.csfLoadFailTimeout=setTimeout((()=>{"ready"!==this.state.status&&(this.setState({status:"csfLoadFailure"}),this.props.onError(new u("ERROR","secured field iframes have failed to load")))}),this.csfLoadFailTimeoutMS)}checkForKCPFields(){let s=!1;if(this.props.koreanAuthenticationRequired&&(s=this.issuingCountryCode?"kr"===this.issuingCountryCode:"kr"===this.props.countryCode),this.state.hasKoreanFields&&!s){const s=s=>({data:{...s.data,[a]:void 0},valid:{...s.valid,[a]:!1},errors:{...s.errors,[a]:!1},hasKoreanFields:!1});this.setState(s,(()=>{this.props.onChange(this.state)})),this.csf.removeSecuredField(a),this.csf.setKCPStatus(!1)}if(!this.state.hasKoreanFields&&s){const s=s=>({valid:{...s.valid,[a]:!1},hasKoreanFields:!0,isSfpValid:!1});this.setState(s,(()=>{this.props.onChange(this.state)})),this.csf.addSecuredField(a),this.csf.setKCPStatus(!0)}}getChildContext(){return{i18n:this.props.i18n}}handleUnsupportedCard(s){const t=!!s.error;return t&&this.setState({detectedUnsupportedBrands:s.detectedBrands}),s.rootNode=this.rootNode,this.handleOnError(s,t),this.csf&&this.csf.hasUnsupportedCard(h,s.error),t}setFocusOn(s){this.csf&&this.csf.setFocusOnFrame(s)}updateStyles(s){this.csf&&this.csf.updateStyles(s)}sfIsOptionalOrHidden(s){return this.csf.sfIsOptionalOrHidden(s)}destroy(){this.csf&&this.csf.destroy()}showValidation(){const{numDateFields:s,state:t}=this;Object.keys(t.valid).reduce(i(s,t),[]).forEach((s=>{const e=o(s,this.rootNode,t);this.handleOnError(e,!!t.detectedUnsupportedBrands),this.csf&&this.csf.isValidated&&this.csf.isValidated(s,e.error)}))}mapErrorsToValidationRuleResult(){return Object.keys(this.state.errors).reduce(((s,t)=>{const e=this.state.errors[t];return s[t]=e?{isValid:!1,errorMessage:f(e,m),errorI18n:this.props.i18n.get(e),error:e,rootNode:this.rootNode,...this.state.detectedUnsupportedBrands&&{detectedBrands:this.state.detectedUnsupportedBrands}}:null,s}),{})}processBinLookupResponse(s,t){if(this.state.detectedUnsupportedBrands&&(this.setState((s=>({errors:{...s.errors,[h]:!1},detectedUnsupportedBrands:null}))),this.csf&&s)){const s={type:"card",fieldType:"encryptedCardNumber",error:""};this.handleUnsupportedCard(s)}this.issuingCountryCode=s?.issuingCountryCode?.toLowerCase();const e=t?.brand,i=e&&l.includes(t.brand);i&&this.setState(t,(()=>{this.props.onChange(this.state)})),this.csf&&this.csf.brandsFromBinLookup(s,i?t:null)}render(s,t){return s.render({setRootNode:this.setRootNode,setFocusOn:this.setFocusOn},t)}constructor(s){super(s),F(this,"csfLoadFailTimeout",void 0),F(this,"csfLoadFailTimeoutMS",void 0),F(this,"csfConfigFailTimeout",void 0),F(this,"csfConfigFailTimeoutMS",void 0),F(this,"numCharsInField",void 0),F(this,"rootNode",void 0),F(this,"numDateFields",void 0),F(this,"csf",void 0),F(this,"handleOnLoad",void 0),F(this,"handleOnConfigSuccess",void 0),F(this,"handleOnFieldValid",void 0),F(this,"handleOnAllValid",void 0),F(this,"handleOnBrand",void 0),F(this,"handleFocus",void 0),F(this,"handleOnError",void 0),F(this,"handleOnAutoComplete",void 0),F(this,"handleOnNoDataRequired",void 0),F(this,"handleOnTouchstartIOS",void 0),F(this,"handleKeyPressed",void 0),F(this,"state",void 0),F(this,"props",void 0),F(this,"issuingCountryCode",void 0),F(this,"setRootNode",(s=>{this.rootNode=s}));const t={status:"loading",brand:s.type,errors:{},valid:{},data:{},cvcPolicy:c,expiryDatePolicy:p,isSfpValid:!1,hasKoreanFields:s.hasKoreanFields};this.state=t,this.csfLoadFailTimeout=null,this.csfLoadFailTimeoutMS=3e4,this.csfConfigFailTimeout=null,this.csfConfigFailTimeoutMS=15e3,this.numCharsInField={},this.handleOnLoad=r.handleOnLoad.bind(this),this.handleOnConfigSuccess=r.handleOnConfigSuccess.bind(this),this.handleOnFieldValid=r.handleOnFieldValid.bind(this),this.handleOnAllValid=r.handleOnAllValid.bind(this),this.handleOnBrand=r.handleOnBrand.bind(this),this.handleFocus=r.handleFocus.bind(this),this.handleOnError=r.handleOnError.bind(this),this.handleOnNoDataRequired=r.handleOnNoDataRequired.bind(this),this.handleOnAutoComplete=r.handleOnAutoComplete.bind(this),this.handleOnTouchstartIOS=r.handleOnTouchstartIOS.bind(this),this.handleKeyPressed=r.handleKeyPressed.bind(this),this.processBinLookupResponse=this.processBinLookupResponse.bind(this),this.setFocusOn=this.setFocusOn.bind(this),this.updateStyles=this.updateStyles.bind(this),this.handleUnsupportedCard=this.handleUnsupportedCard.bind(this),this.showValidation=this.showValidation.bind(this),this.destroy=this.destroy.bind(this)}}F(C,"defaultProps",d);export{C as default};
|
|
1
|
+
import{Component as s}from"../../../../external/preact/dist/preact.js";import{getFields as t,validFieldsReducer as e,getErrorReducer as i,getErrorObject as o}from"./SFPUtils.js";import n from"../lib/CSF/initCSF.js";import r from"./SecuredFieldsProviderHandlers.js";import d from"./defaultProps.js";import{ENCRYPTED_PWD_FIELD as a,ENCRYPTED_CARD_NUMBER as h,DEDICATED_CARD_COMPONENTS as l,DATE_POLICY_REQUIRED as p,CVC_POLICY_REQUIRED as c}from"../lib/constants.js";import u from"../../../../core/Errors/AdyenCheckoutError.js";import{getErrorMessageFromCode as f}from"../../../../core/Errors/utils.js";import{SF_ErrorCodes as m}from"../../../../core/Errors/constants.js";function F(s,t,e){return t in s?Object.defineProperty(s,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):s[t]=e,s}class C extends s{componentDidMount(){this.props.rootNode&&this.setRootNode(this.props.rootNode);const s=t(this.rootNode),i=s.reduce(e,{});this.setState({valid:i}),s.forEach((s=>{this.numCharsInField[s]=0})),this.numDateFields=s.filter((s=>s.match(/Expiry/))).length,s.length?(this.destroy(),this.initializeCSF(this.rootNode)):this.handleOnNoDataRequired()}componentDidUpdate(){this.checkForKCPFields(),this.props.onStateUpdate?.(this.state)}componentWillUnmount(){this.csf=null,clearTimeout(this.csfLoadFailTimeout),clearTimeout(this.csfConfigFailTimeout)}initializeCSF(s){let t=this.props.loadingContext;const e={rootNode:s,type:this.props.type,clientKey:this.props.clientKey,cardGroupTypes:this.props.brands,autoFocus:this.props.autoFocus,trimTrailingSeparator:this.props.trimTrailingSeparator,loadingContext:t,keypadFix:this.props.keypadFix,showWarnings:this.props.showWarnings,iframeUIConfig:{sfStyles:this.props.styles},i18n:this.props.i18n,callbacks:{onLoad:this.handleOnLoad,onConfigSuccess:this.handleOnConfigSuccess,onFieldValid:this.handleOnFieldValid,onAllValid:this.handleOnAllValid,onBrand:this.handleOnBrand,onError:this.handleOnError,onFocus:this.handleFocus,onBinValue:this.props.onBinValue,onAutoComplete:this.handleOnAutoComplete,onAdditionalSFConfig:this.props.onAdditionalSFConfig,onAdditionalSFRemoved:this.props.onAdditionalSFRemoved,onTouchstartIOS:this.handleOnTouchstartIOS,onKeyPressed:this.handleKeyPressed},isKCP:this.state.hasKoreanFields,legacyInputMode:this.props.legacyInputMode,minimumExpiryDate:this.props.minimumExpiryDate,implementationType:this.props.implementationType||"components",forceCompat:this.props.forceCompat,maskSecurityCode:this.props.maskSecurityCode,exposeExpiryDate:this.props.exposeExpiryDate,shouldDisableIOSArrowKeys:!!this.props.disableIOSArrowKeys,placeholders:this.props.placeholders??{},showContextualElement:this.props.showContextualElement};this.csf=n(e),this.csfLoadFailTimeout=setTimeout((()=>{"ready"!==this.state.status&&(this.setState({status:"csfLoadFailure"}),this.props.onError(new u("ERROR","secured field iframes have failed to load")))}),this.csfLoadFailTimeoutMS)}checkForKCPFields(){let s=!1;if(this.props.koreanAuthenticationRequired&&(s=this.issuingCountryCode?"kr"===this.issuingCountryCode:"kr"===this.props.countryCode),this.state.hasKoreanFields&&!s){const s=s=>({data:{...s.data,[a]:void 0},valid:{...s.valid,[a]:!1},errors:{...s.errors,[a]:!1},hasKoreanFields:!1});this.setState(s,(()=>{this.props.onChange(this.state)})),this.csf.removeSecuredField(a),this.csf.setKCPStatus(!1)}if(!this.state.hasKoreanFields&&s){const s=s=>({valid:{...s.valid,[a]:!1},hasKoreanFields:!0,isSfpValid:!1});this.setState(s,(()=>{this.props.onChange(this.state)})),this.csf.addSecuredField(a),this.csf.setKCPStatus(!0)}}getChildContext(){return{i18n:this.props.i18n}}handleUnsupportedCard(s){const t=!!s.error;return t&&this.setState({detectedUnsupportedBrands:s.detectedBrands}),s.rootNode=this.rootNode,this.handleOnError(s,t),this.csf&&this.csf.hasUnsupportedCard(h,s.error),t}setFocusOn(s){this.csf&&this.csf.setFocusOnFrame(s)}updateStyles(s){this.csf&&this.csf.updateStyles(s)}sfIsOptionalOrHidden(s){return this.csf.sfIsOptionalOrHidden(s)}destroy(){this.csf&&this.csf.destroy()}showValidation(){const{numDateFields:s,state:t}=this;Object.keys(t.valid).reduce(i(s,t),[]).forEach((s=>{const e=o(s,this.rootNode,t);this.handleOnError(e,!!t.detectedUnsupportedBrands),this.csf&&this.csf.isValidated&&this.csf.isValidated(s,e.error)}))}mapErrorsToValidationRuleResult(){return Object.keys(this.state.errors).reduce(((s,t)=>{const e=this.state.errors[t];return s[t]=e?{isValid:!1,errorMessage:f(e,m),errorI18n:this.props.i18n.get(e),error:e,rootNode:this.rootNode,...this.state.detectedUnsupportedBrands&&{detectedBrands:this.state.detectedUnsupportedBrands}}:null,s}),{})}processBinLookupResponse(s,t){if(this.state.detectedUnsupportedBrands&&(this.setState((s=>({errors:{...s.errors,[h]:!1},detectedUnsupportedBrands:null}))),this.csf&&s)){const s={type:"card",fieldType:"encryptedCardNumber",error:""};this.handleUnsupportedCard(s)}this.issuingCountryCode=s?.issuingCountryCode?.toLowerCase();const e=t?.brand,i=e&&l.includes(t.brand);i&&this.setState(t,(()=>{this.props.onChange(this.state)})),this.csf&&this.csf.brandsFromBinLookup(s,i?t:null)}render(s,t){return s.render({setRootNode:this.setRootNode,setFocusOn:this.setFocusOn},t)}constructor(s){super(s),F(this,"csfLoadFailTimeout",void 0),F(this,"csfLoadFailTimeoutMS",void 0),F(this,"csfConfigFailTimeout",void 0),F(this,"csfConfigFailTimeoutMS",void 0),F(this,"numCharsInField",void 0),F(this,"rootNode",void 0),F(this,"numDateFields",void 0),F(this,"csf",void 0),F(this,"handleOnLoad",void 0),F(this,"handleOnConfigSuccess",void 0),F(this,"handleOnFieldValid",void 0),F(this,"handleOnAllValid",void 0),F(this,"handleOnBrand",void 0),F(this,"handleFocus",void 0),F(this,"handleOnError",void 0),F(this,"handleOnAutoComplete",void 0),F(this,"handleOnNoDataRequired",void 0),F(this,"handleOnTouchstartIOS",void 0),F(this,"handleKeyPressed",void 0),F(this,"state",void 0),F(this,"props",void 0),F(this,"issuingCountryCode",void 0),F(this,"setRootNode",(s=>{this.rootNode=s}));const t={status:"loading",brand:s.type,errors:{},valid:{},data:{},cvcPolicy:c,expiryDatePolicy:p,isSfpValid:!1,hasKoreanFields:s.hasKoreanFields};this.state=t,this.csfLoadFailTimeout=null,this.csfLoadFailTimeoutMS=3e4,this.csfConfigFailTimeout=null,this.csfConfigFailTimeoutMS=15e3,this.numCharsInField={},this.handleOnLoad=r.handleOnLoad.bind(this),this.handleOnConfigSuccess=r.handleOnConfigSuccess.bind(this),this.handleOnFieldValid=r.handleOnFieldValid.bind(this),this.handleOnAllValid=r.handleOnAllValid.bind(this),this.handleOnBrand=r.handleOnBrand.bind(this),this.handleFocus=r.handleFocus.bind(this),this.handleOnError=r.handleOnError.bind(this),this.handleOnNoDataRequired=r.handleOnNoDataRequired.bind(this),this.handleOnAutoComplete=r.handleOnAutoComplete.bind(this),this.handleOnTouchstartIOS=r.handleOnTouchstartIOS.bind(this),this.handleKeyPressed=r.handleKeyPressed.bind(this),this.processBinLookupResponse=this.processBinLookupResponse.bind(this),this.setFocusOn=this.setFocusOn.bind(this),this.updateStyles=this.updateStyles.bind(this),this.handleUnsupportedCard=this.handleUnsupportedCard.bind(this),this.showValidation=this.showValidation.bind(this),this.destroy=this.destroy.bind(this)}}F(C,"defaultProps",d);export{C as default};
|
|
2
2
|
//# sourceMappingURL=SecuredFieldsProvider.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SecuredFieldsProvider.js","sources":["../../../../../../src/components/internal/SecuredFields/SFP/SecuredFieldsProvider.ts"],"sourcesContent":["import { Component } from 'preact';\nimport { getErrorObject, getFields, getErrorReducer, validFieldsReducer } from './SFPUtils';\nimport initCSF from '../lib/CSF';\nimport handlers from './SecuredFieldsProviderHandlers';\nimport defaultProps from './defaultProps';\nimport { SFPProps, SFPState, SingleBrandResetObject } from './types';\nimport {\n StylesObject,\n CardErrorData,\n CardFocusData,\n CardBrandData,\n CardAllValidData,\n CardFieldValidData,\n CardAutoCompleteData,\n CardConfigSuccessData,\n CardLoadData,\n SFKeyPressObj\n} from '../lib/types';\nimport { CSFReturnObject, CSFSetupObject } from '../lib/CSF/types';\nimport { CVC_POLICY_REQUIRED, DATE_POLICY_REQUIRED, DEDICATED_CARD_COMPONENTS, ENCRYPTED_CARD_NUMBER, ENCRYPTED_PWD_FIELD } from '../lib/constants';\nimport { BinLookupResponse } from '../../../Card/types';\nimport AdyenCheckoutError from '../../../../core/Errors/AdyenCheckoutError';\nimport { SFStateErrorObj } from '../../../Card/components/CardInput/types';\nimport { getErrorMessageFromCode } from '../../../../core/Errors/utils';\nimport { SF_ErrorCodes } from '../../../../core/Errors/constants';\n\n/**\n * SecuredFieldsProvider:\n * Initialises & handles the client-side part of SecuredFields\n */\nclass SecuredFieldsProvider extends Component<SFPProps, SFPState> {\n private csfLoadFailTimeout: number;\n private csfLoadFailTimeoutMS: number;\n private csfConfigFailTimeout: number;\n private csfConfigFailTimeoutMS: number;\n private numCharsInField: object;\n private rootNode;\n private numDateFields: number;\n private csf: CSFReturnObject;\n private handleOnLoad: (obj: CardLoadData) => void;\n private handleOnConfigSuccess: (obj: CardConfigSuccessData) => void;\n private handleOnFieldValid: (obj: CardFieldValidData) => void;\n private handleOnAllValid: (obj: CardAllValidData) => void;\n private handleOnBrand: (obj: CardBrandData) => void;\n private handleFocus: (obj: CardFocusData) => void;\n private handleOnError: (obj: CardErrorData, hasUnsupportedCard?: boolean) => void;\n private handleOnAutoComplete: (obj: CardAutoCompleteData) => void;\n private handleOnNoDataRequired: () => void;\n private handleOnTouchstartIOS: (obj) => void;\n private handleKeyPressed: (obj: SFKeyPressObj) => void;\n public state: SFPState;\n public props;\n private issuingCountryCode;\n\n constructor(props: SFPProps) {\n super(props);\n\n const stateObj: SFPState = {\n status: 'loading',\n brand: props.type,\n errors: {},\n valid: {},\n data: {},\n cvcPolicy: CVC_POLICY_REQUIRED,\n expiryDatePolicy: DATE_POLICY_REQUIRED,\n isSfpValid: false,\n hasKoreanFields: props.hasKoreanFields\n };\n this.state = stateObj;\n\n this.csfLoadFailTimeout = null;\n this.csfLoadFailTimeoutMS = 30000;\n\n this.csfConfigFailTimeout = null;\n this.csfConfigFailTimeoutMS = 15000;\n\n this.numCharsInField = {};\n\n // Handlers\n this.handleOnLoad = handlers.handleOnLoad.bind(this);\n this.handleOnConfigSuccess = handlers.handleOnConfigSuccess.bind(this);\n this.handleOnFieldValid = handlers.handleOnFieldValid.bind(this);\n this.handleOnAllValid = handlers.handleOnAllValid.bind(this);\n this.handleOnBrand = handlers.handleOnBrand.bind(this);\n this.handleFocus = handlers.handleFocus.bind(this);\n this.handleOnError = handlers.handleOnError.bind(this);\n this.handleOnNoDataRequired = handlers.handleOnNoDataRequired.bind(this);\n this.handleOnAutoComplete = handlers.handleOnAutoComplete.bind(this);\n this.handleOnTouchstartIOS = handlers.handleOnTouchstartIOS.bind(this); // Only called when iOS detected\n this.handleKeyPressed = handlers.handleKeyPressed.bind(this);\n\n this.processBinLookupResponse = this.processBinLookupResponse.bind(this);\n\n // Bindings for functions exposed to users of this component: SecuredFields & CardInput\n this.setFocusOn = this.setFocusOn.bind(this);\n this.updateStyles = this.updateStyles.bind(this);\n this.handleUnsupportedCard = this.handleUnsupportedCard.bind(this);\n this.showValidation = this.showValidation.bind(this);\n this.destroy = this.destroy.bind(this);\n }\n\n public static defaultProps = defaultProps;\n\n public componentDidMount(): void {\n // When SFP instantiated through SecuredFieldsInput c.f. CardInput\n if (this.props.rootNode) {\n this.setRootNode(this.props.rootNode);\n }\n\n // Find encryptedFields and map them to the values we use to store valid states\n const fields = getFields(this.rootNode);\n const valid = fields.reduce(validFieldsReducer, {});\n\n this.setState({ valid });\n\n // Populate numCharsInField object\n fields.forEach(field => {\n this.numCharsInField[field] = 0;\n });\n\n // Store how many dateFields we are dealing with visually\n this.numDateFields = fields.filter(f => f.match(/Expiry/)).length;\n\n if (fields.length) {\n this.destroy(); // TODO test if this solves the React double render problem.\n this.initializeCSF(this.rootNode);\n } else {\n this.handleOnNoDataRequired();\n }\n }\n\n public componentDidUpdate() {\n this.checkForKCPFields();\n }\n\n public componentWillUnmount(): void {\n this.csf = null;\n clearTimeout(this.csfLoadFailTimeout);\n clearTimeout(this.csfConfigFailTimeout);\n }\n\n private initializeCSF(root: HTMLElement): void {\n let loadingContext = this.props.loadingContext;\n\n // For loading securedFields from local server during development\n if (process.env.NODE_ENV === 'development' && process.env.__SF_ENV__ !== 'build') {\n loadingContext = process.env.__SF_ENV__;\n }\n\n // TODO\n // if(!this.props.keypadFix){\n // send analytics action because to know if anyone *ever* sets this config prop\n // }\n\n const csfSetupObj: CSFSetupObject = {\n rootNode: root,\n type: this.props.type,\n clientKey: this.props.clientKey,\n cardGroupTypes: this.props.brands,\n autoFocus: this.props.autoFocus,\n trimTrailingSeparator: this.props.trimTrailingSeparator,\n loadingContext,\n keypadFix: this.props.keypadFix,\n showWarnings: this.props.showWarnings,\n iframeUIConfig: {\n sfStyles: this.props.styles\n },\n i18n: this.props.i18n,\n callbacks: {\n onLoad: this.handleOnLoad,\n onConfigSuccess: this.handleOnConfigSuccess,\n onFieldValid: this.handleOnFieldValid,\n onAllValid: this.handleOnAllValid,\n onBrand: this.handleOnBrand,\n onError: this.handleOnError,\n onFocus: this.handleFocus,\n onBinValue: this.props.onBinValue,\n onAutoComplete: this.handleOnAutoComplete,\n onAdditionalSFConfig: this.props.onAdditionalSFConfig,\n onAdditionalSFRemoved: this.props.onAdditionalSFRemoved,\n onTouchstartIOS: this.handleOnTouchstartIOS,\n onKeyPressed: this.handleKeyPressed\n },\n isKCP: this.state.hasKoreanFields,\n legacyInputMode: this.props.legacyInputMode,\n minimumExpiryDate: this.props.minimumExpiryDate,\n implementationType: this.props.implementationType || 'components', // to distinguish between 'regular' and 'custom' card component\n forceCompat: this.props.forceCompat,\n maskSecurityCode: this.props.maskSecurityCode,\n exposeExpiryDate: this.props.exposeExpiryDate,\n shouldDisableIOSArrowKeys: !!this.props.disableIOSArrowKeys, // convert whether function has been defined into a boolean\n placeholders: this.props.placeholders ?? {},\n showContextualElement: this.props.showContextualElement\n };\n\n this.csf = initCSF(csfSetupObj);\n\n /**\n * Expect to at least have had the handleOnLoad callback called within this time\n * - if this hasn't happened then something has happened to interrupt the loading of the securedFields\n * So we need to clear the loading spinner to see if the securedFields are reporting anything\n */\n // @ts-ignore - timout 'type' is a number\n this.csfLoadFailTimeout = setTimeout(() => {\n if (this.state.status !== 'ready') {\n // Hide the spinner\n this.setState({ status: 'csfLoadFailure' });\n // Report the error\n this.props.onError(new AdyenCheckoutError('ERROR', 'secured field iframes have failed to load'));\n }\n }, this.csfLoadFailTimeoutMS);\n }\n\n private checkForKCPFields() {\n let needsKoreanFields = false;\n if (this.props.koreanAuthenticationRequired) {\n needsKoreanFields = this.issuingCountryCode ? this.issuingCountryCode === 'kr' : this.props.countryCode === 'kr';\n }\n\n // Was korean, now isn't - hide password field\n if (this.state.hasKoreanFields && !needsKoreanFields) {\n // Clear any stored data\n const setRemovedFieldState = prevState => ({\n data: { ...prevState.data, [ENCRYPTED_PWD_FIELD]: undefined },\n valid: { ...prevState.valid, [ENCRYPTED_PWD_FIELD]: false },\n errors: { ...prevState.errors, [ENCRYPTED_PWD_FIELD]: false },\n hasKoreanFields: false\n });\n\n this.setState(setRemovedFieldState, () => {\n this.props.onChange(this.state);\n });\n\n this.csf.removeSecuredField(ENCRYPTED_PWD_FIELD);\n this.csf.setKCPStatus(false);\n }\n\n // Wasn't korean, now is - show password field\n if (!this.state.hasKoreanFields && needsKoreanFields) {\n const setAddedFieldState = prevState => ({\n valid: { ...prevState.valid, [ENCRYPTED_PWD_FIELD]: false },\n hasKoreanFields: true,\n isSfpValid: false\n });\n\n this.setState(setAddedFieldState, () => {\n this.props.onChange(this.state);\n });\n\n this.csf.addSecuredField(ENCRYPTED_PWD_FIELD);\n this.csf.setKCPStatus(true);\n }\n }\n\n public getChildContext(): object {\n return { i18n: this.props.i18n };\n }\n\n public handleUnsupportedCard(errObj: CardErrorData): boolean {\n const hasUnsupportedCard = !!errObj.error;\n\n // Store the brand(s) we detected and which we don't support\n if (hasUnsupportedCard) {\n this.setState({ detectedUnsupportedBrands: errObj.detectedBrands });\n }\n\n errObj.rootNode = this.rootNode; // Needed for CustomCard\n this.handleOnError(errObj, hasUnsupportedCard);\n // Inform CSF that the number field has an unsupportedCard error (or that it has been cleared)\n if (this.csf) {\n this.csf.hasUnsupportedCard(ENCRYPTED_CARD_NUMBER, errObj.error);\n }\n return hasUnsupportedCard;\n }\n\n public setFocusOn(frame: string): void {\n if (this.csf) this.csf.setFocusOnFrame(frame);\n }\n\n public updateStyles(stylesObj: StylesObject): void {\n if (this.csf) this.csf.updateStyles(stylesObj);\n }\n\n public sfIsOptionalOrHidden(fieldType: string): boolean {\n return this.csf.sfIsOptionalOrHidden(fieldType);\n }\n\n public destroy(): void {\n if (this.csf) this.csf.destroy();\n }\n\n public showValidation(): void {\n const { numDateFields, state }: SecuredFieldsProvider = this;\n\n Object.keys(state.valid)\n .reduce(getErrorReducer(numDateFields, state), [])\n .forEach(field => {\n // For each detected error pass an error object to the handler (calls error callback & sets state)\n const errorObj: CardErrorData = getErrorObject(field, this.rootNode, state);\n this.handleOnError(errorObj, !!state.detectedUnsupportedBrands);\n // Inform the secured-fields instance of which fields have been found to have errors\n if (this.csf && this.csf.isValidated) {\n this.csf.isValidated(field, errorObj.error);\n }\n });\n }\n\n /**\n * Map SF errors to ValidationRuleResult-like objects, for CardInput component\n */\n public mapErrorsToValidationRuleResult(): SFStateErrorObj {\n const fieldNames: string[] = Object.keys(this.state.errors);\n\n const sfStateErrorsObj = fieldNames.reduce((acc, fieldName) => {\n const errorCode = this.state.errors[fieldName];\n if (errorCode) {\n acc[fieldName] = {\n isValid: false,\n errorMessage: getErrorMessageFromCode(errorCode, SF_ErrorCodes), // this is the human-readable, untranslated, explanation of the error that will exist on the error object in card.state.errors\n // For v5 the object found in state.errors should also contain the additional properties that used to be sent to the onError callback\n // namely: translation, errorCode, a ref to rootNode &, in the case of failed binLookup, an array of the detectedBrands\n errorI18n: this.props.i18n.get(errorCode),\n error: errorCode,\n rootNode: this.rootNode,\n ...(this.state.detectedUnsupportedBrands && { detectedBrands: this.state.detectedUnsupportedBrands })\n };\n } else {\n acc[fieldName] = null;\n }\n return acc;\n }, {});\n return sfStateErrorsObj;\n }\n\n public processBinLookupResponse(binLookupResponse: BinLookupResponse, resetObject: SingleBrandResetObject): void {\n // If we were dealing with an unsupported card & now we have a valid /binLookup response (or a response triggering a reset of the UI),\n // - reset state to clear the error & the stored unsupportedBrands and, in the case of a valid /binLookup response, inform CSF (via handleUnsupportedCard)\n // (Scenario: from an unsupportedCard state the shopper has pasted another number long enough to trigger a /binLookup)\n if (this.state.detectedUnsupportedBrands) {\n this.setState(prevState => ({\n errors: { ...prevState.errors, [ENCRYPTED_CARD_NUMBER]: false },\n detectedUnsupportedBrands: null\n }));\n\n // If we have some sort of binLookupResponse object then this isn't the reset caused by digits dropping below a threshold\n // - so call handleUnsupportedCard to clear the error\n if (this.csf && binLookupResponse) {\n const errObj: CardErrorData = {\n type: 'card',\n fieldType: 'encryptedCardNumber',\n error: ''\n };\n this.handleUnsupportedCard(errObj);\n }\n }\n\n this.issuingCountryCode = binLookupResponse?.issuingCountryCode?.toLowerCase();\n\n const hasBrandedResetObj = resetObject?.brand;\n\n /**\n * Are we dealing with a \"dedicated\" card scenario i.e a card component created as: checkout.create('bcmc') but which can accept multiple brands\n * - in which case we will need to reset brand and pass on the resetObj to CSF\n */\n const mustResetDedicatedBrand = hasBrandedResetObj && DEDICATED_CARD_COMPONENTS.includes(resetObject.brand);\n\n if (mustResetDedicatedBrand) {\n // resetObject.brand will be the value of the brand whose logo we want to reshow in the UI\n this.setState(resetObject, () => {\n this.props.onChange(this.state);\n });\n }\n\n /**\n * Scenarios:\n *\n * - RESET (binLookupResponse === null): The number of digits in number field has dropped below threshold for BIN lookup\n * - RESULT (binLookupResponse.supportedBrands.length === 1): binLookup has found a result so inform CSF\n *\n * In the RESET scenario, for \"dedicated\" card components we also need to pass on the resetObject since this contains information about\n * the brand that CSF needs to reset to, internally.\n */\n if (this.csf) this.csf.brandsFromBinLookup(binLookupResponse, mustResetDedicatedBrand ? resetObject : null);\n }\n\n private setRootNode = (input: HTMLElement): void => {\n this.rootNode = input;\n };\n\n public render(props, state) {\n return props.render({ setRootNode: this.setRootNode, setFocusOn: this.setFocusOn }, state);\n }\n}\n\nexport default SecuredFieldsProvider;\n"],"names":["SecuredFieldsProvider","Component","componentDidMount","this","props","rootNode","setRootNode","fields","getFields","valid","reduce","validFieldsReducer","setState","forEach","field","numCharsInField","numDateFields","filter","f","match","length","destroy","initializeCSF","handleOnNoDataRequired","componentDidUpdate","checkForKCPFields","componentWillUnmount","csf","clearTimeout","csfLoadFailTimeout","csfConfigFailTimeout","root","loadingContext","csfSetupObj","type","clientKey","cardGroupTypes","brands","autoFocus","trimTrailingSeparator","keypadFix","showWarnings","iframeUIConfig","sfStyles","styles","i18n","callbacks","onLoad","handleOnLoad","onConfigSuccess","handleOnConfigSuccess","onFieldValid","handleOnFieldValid","onAllValid","handleOnAllValid","onBrand","handleOnBrand","onError","handleOnError","onFocus","handleFocus","onBinValue","onAutoComplete","handleOnAutoComplete","onAdditionalSFConfig","onAdditionalSFRemoved","onTouchstartIOS","handleOnTouchstartIOS","onKeyPressed","handleKeyPressed","isKCP","state","hasKoreanFields","legacyInputMode","minimumExpiryDate","implementationType","forceCompat","maskSecurityCode","exposeExpiryDate","shouldDisableIOSArrowKeys","disableIOSArrowKeys","placeholders","showContextualElement","initCSF","setTimeout","status","AdyenCheckoutError","csfLoadFailTimeoutMS","needsKoreanFields","koreanAuthenticationRequired","issuingCountryCode","countryCode","setRemovedFieldState","prevState","data","ENCRYPTED_PWD_FIELD","undefined","errors","onChange","removeSecuredField","setKCPStatus","setAddedFieldState","isSfpValid","addSecuredField","getChildContext","handleUnsupportedCard","errObj","hasUnsupportedCard","error","detectedUnsupportedBrands","detectedBrands","ENCRYPTED_CARD_NUMBER","setFocusOn","frame","setFocusOnFrame","updateStyles","stylesObj","sfIsOptionalOrHidden","fieldType","showValidation","Object","keys","getErrorReducer","errorObj","getErrorObject","isValidated","mapErrorsToValidationRuleResult","acc","fieldName","errorCode","isValid","errorMessage","getErrorMessageFromCode","SF_ErrorCodes","errorI18n","get","processBinLookupResponse","binLookupResponse","resetObject","toLowerCase","hasBrandedResetObj","brand","mustResetDedicatedBrand","DEDICATED_CARD_COMPONENTS","includes","brandsFromBinLookup","render","constructor","super","_define_property","csfConfigFailTimeoutMS","input","stateObj","cvcPolicy","CVC_POLICY_REQUIRED","expiryDatePolicy","DATE_POLICY_REQUIRED","handlers","bind","defaultProps"],"mappings":"sxBA8BA,MAAMA,UAA8BC,EAyEzBC,iBAAAA,GAECC,KAAKC,MAAMC,UACXF,KAAKG,YAAYH,KAAKC,MAAMC,UAIhC,MAAME,EAASC,EAAUL,KAAKE,UACxBI,EAAQF,EAAOG,OAAOC,EAAoB,CAAA,GAEhDR,KAAKS,SAAS,CAAEH,UAGhBF,EAAOM,SAAQC,IACXX,KAAKY,gBAAgBD,GAAS,CAAA,IAIlCX,KAAKa,cAAgBT,EAAOU,QAAOC,GAAKA,EAAEC,MAAM,YAAWC,OAEvDb,EAAOa,QACPjB,KAAKkB,UACLlB,KAAKmB,cAAcnB,KAAKE,WAExBF,KAAKoB,wBAEb,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nEA,KAAK6G,WAAa7G,KAAK6G,WAAW8C,KAAK3J,MACvCA,KAAKgH,aAAehH,KAAKgH,aAAa2C,KAAK3J,MAC3CA,KAAKsG,sBAAwBtG,KAAKsG,sBAAsBqD,KAAK3J,MAC7DA,KAAKoH,eAAiBpH,KAAKoH,eAAeuC,KAAK3J,MAC/CA,KAAKkB,QAAUlB,KAAKkB,QAAQyI,KAAK3J,KACrC,EAEAkJ,EAvEErJ,EAuEY+J,eAAeA"}
|
|
1
|
+
{"version":3,"file":"SecuredFieldsProvider.js","sources":["../../../../../../src/components/internal/SecuredFields/SFP/SecuredFieldsProvider.ts"],"sourcesContent":["import { Component } from 'preact';\nimport { getErrorObject, getFields, getErrorReducer, validFieldsReducer } from './SFPUtils';\nimport initCSF from '../lib/CSF';\nimport handlers from './SecuredFieldsProviderHandlers';\nimport defaultProps from './defaultProps';\nimport { SFPProps, SFPState, SingleBrandResetObject } from './types';\nimport {\n StylesObject,\n CardErrorData,\n CardFocusData,\n CardBrandData,\n CardAllValidData,\n CardFieldValidData,\n CardAutoCompleteData,\n CardConfigSuccessData,\n CardLoadData,\n SFKeyPressObj\n} from '../lib/types';\nimport { CSFReturnObject, CSFSetupObject } from '../lib/CSF/types';\nimport { CVC_POLICY_REQUIRED, DATE_POLICY_REQUIRED, DEDICATED_CARD_COMPONENTS, ENCRYPTED_CARD_NUMBER, ENCRYPTED_PWD_FIELD } from '../lib/constants';\nimport { BinLookupResponse } from '../../../Card/types';\nimport AdyenCheckoutError from '../../../../core/Errors/AdyenCheckoutError';\nimport { SFStateErrorObj } from '../../../Card/components/CardInput/types';\nimport { getErrorMessageFromCode } from '../../../../core/Errors/utils';\nimport { SF_ErrorCodes } from '../../../../core/Errors/constants';\n\n/**\n * SecuredFieldsProvider:\n * Initialises & handles the client-side part of SecuredFields\n */\nclass SecuredFieldsProvider extends Component<SFPProps, SFPState> {\n private csfLoadFailTimeout: number;\n private csfLoadFailTimeoutMS: number;\n private csfConfigFailTimeout: number;\n private csfConfigFailTimeoutMS: number;\n private numCharsInField: object;\n private rootNode;\n private numDateFields: number;\n private csf: CSFReturnObject;\n private handleOnLoad: (obj: CardLoadData) => void;\n private handleOnConfigSuccess: (obj: CardConfigSuccessData) => void;\n private handleOnFieldValid: (obj: CardFieldValidData) => void;\n private handleOnAllValid: (obj: CardAllValidData) => void;\n private handleOnBrand: (obj: CardBrandData) => void;\n private handleFocus: (obj: CardFocusData) => void;\n private handleOnError: (obj: CardErrorData, hasUnsupportedCard?: boolean) => void;\n private handleOnAutoComplete: (obj: CardAutoCompleteData) => void;\n private handleOnNoDataRequired: () => void;\n private handleOnTouchstartIOS: (obj) => void;\n private handleKeyPressed: (obj: SFKeyPressObj) => void;\n public state: SFPState;\n public props;\n private issuingCountryCode;\n\n constructor(props: SFPProps) {\n super(props);\n\n const stateObj: SFPState = {\n status: 'loading',\n brand: props.type,\n errors: {},\n valid: {},\n data: {},\n cvcPolicy: CVC_POLICY_REQUIRED,\n expiryDatePolicy: DATE_POLICY_REQUIRED,\n isSfpValid: false,\n hasKoreanFields: props.hasKoreanFields\n };\n this.state = stateObj;\n\n this.csfLoadFailTimeout = null;\n this.csfLoadFailTimeoutMS = 30000;\n\n this.csfConfigFailTimeout = null;\n this.csfConfigFailTimeoutMS = 15000;\n\n this.numCharsInField = {};\n\n // Handlers\n this.handleOnLoad = handlers.handleOnLoad.bind(this);\n this.handleOnConfigSuccess = handlers.handleOnConfigSuccess.bind(this);\n this.handleOnFieldValid = handlers.handleOnFieldValid.bind(this);\n this.handleOnAllValid = handlers.handleOnAllValid.bind(this);\n this.handleOnBrand = handlers.handleOnBrand.bind(this);\n this.handleFocus = handlers.handleFocus.bind(this);\n this.handleOnError = handlers.handleOnError.bind(this);\n this.handleOnNoDataRequired = handlers.handleOnNoDataRequired.bind(this);\n this.handleOnAutoComplete = handlers.handleOnAutoComplete.bind(this);\n this.handleOnTouchstartIOS = handlers.handleOnTouchstartIOS.bind(this); // Only called when iOS detected\n this.handleKeyPressed = handlers.handleKeyPressed.bind(this);\n\n this.processBinLookupResponse = this.processBinLookupResponse.bind(this);\n\n // Bindings for functions exposed to users of this component: SecuredFields & CardInput\n this.setFocusOn = this.setFocusOn.bind(this);\n this.updateStyles = this.updateStyles.bind(this);\n this.handleUnsupportedCard = this.handleUnsupportedCard.bind(this);\n this.showValidation = this.showValidation.bind(this);\n this.destroy = this.destroy.bind(this);\n }\n\n public static defaultProps = defaultProps;\n\n public componentDidMount(): void {\n // When SFP instantiated through SecuredFieldsInput c.f. CardInput\n if (this.props.rootNode) {\n this.setRootNode(this.props.rootNode);\n }\n\n // Find encryptedFields and map them to the values we use to store valid states\n const fields = getFields(this.rootNode);\n const valid = fields.reduce(validFieldsReducer, {});\n\n this.setState({ valid });\n\n // Populate numCharsInField object\n fields.forEach(field => {\n this.numCharsInField[field] = 0;\n });\n\n // Store how many dateFields we are dealing with visually\n this.numDateFields = fields.filter(f => f.match(/Expiry/)).length;\n\n if (fields.length) {\n this.destroy(); // TODO test if this solves the React double render problem.\n this.initializeCSF(this.rootNode);\n } else {\n this.handleOnNoDataRequired();\n }\n }\n\n public componentDidUpdate() {\n this.checkForKCPFields();\n // Pass all the state data up - Used right now for loading status\n this.props.onStateUpdate?.(this.state);\n }\n\n public componentWillUnmount(): void {\n this.csf = null;\n clearTimeout(this.csfLoadFailTimeout);\n clearTimeout(this.csfConfigFailTimeout);\n }\n\n private initializeCSF(root: HTMLElement): void {\n let loadingContext = this.props.loadingContext;\n\n // For loading securedFields from local server during development\n if (process.env.NODE_ENV === 'development' && process.env.__SF_ENV__ !== 'build') {\n loadingContext = process.env.__SF_ENV__;\n }\n\n const csfSetupObj: CSFSetupObject = {\n rootNode: root,\n type: this.props.type,\n clientKey: this.props.clientKey,\n cardGroupTypes: this.props.brands,\n autoFocus: this.props.autoFocus,\n trimTrailingSeparator: this.props.trimTrailingSeparator,\n loadingContext,\n keypadFix: this.props.keypadFix,\n showWarnings: this.props.showWarnings,\n iframeUIConfig: {\n sfStyles: this.props.styles\n },\n i18n: this.props.i18n,\n callbacks: {\n onLoad: this.handleOnLoad,\n onConfigSuccess: this.handleOnConfigSuccess,\n onFieldValid: this.handleOnFieldValid,\n onAllValid: this.handleOnAllValid,\n onBrand: this.handleOnBrand,\n onError: this.handleOnError,\n onFocus: this.handleFocus,\n onBinValue: this.props.onBinValue,\n onAutoComplete: this.handleOnAutoComplete,\n onAdditionalSFConfig: this.props.onAdditionalSFConfig,\n onAdditionalSFRemoved: this.props.onAdditionalSFRemoved,\n onTouchstartIOS: this.handleOnTouchstartIOS,\n onKeyPressed: this.handleKeyPressed\n },\n isKCP: this.state.hasKoreanFields,\n legacyInputMode: this.props.legacyInputMode,\n minimumExpiryDate: this.props.minimumExpiryDate,\n implementationType: this.props.implementationType || 'components', // to distinguish between 'regular' and 'custom' card component\n forceCompat: this.props.forceCompat,\n maskSecurityCode: this.props.maskSecurityCode,\n exposeExpiryDate: this.props.exposeExpiryDate,\n shouldDisableIOSArrowKeys: !!this.props.disableIOSArrowKeys, // convert whether function has been defined into a boolean\n placeholders: this.props.placeholders ?? {},\n showContextualElement: this.props.showContextualElement\n };\n\n this.csf = initCSF(csfSetupObj);\n\n /**\n * Expect to at least have had the handleOnLoad callback called within this time\n * - if this hasn't happened then something has happened to interrupt the loading of the securedFields\n * So we need to clear the loading spinner to see if the securedFields are reporting anything\n */\n // @ts-ignore - timout 'type' is a number\n this.csfLoadFailTimeout = setTimeout(() => {\n if (this.state.status !== 'ready') {\n // Hide the spinner\n this.setState({ status: 'csfLoadFailure' });\n // Report the error\n this.props.onError(new AdyenCheckoutError('ERROR', 'secured field iframes have failed to load'));\n }\n }, this.csfLoadFailTimeoutMS);\n }\n\n private checkForKCPFields() {\n let needsKoreanFields = false;\n if (this.props.koreanAuthenticationRequired) {\n needsKoreanFields = this.issuingCountryCode ? this.issuingCountryCode === 'kr' : this.props.countryCode === 'kr';\n }\n\n // Was korean, now isn't - hide password field\n if (this.state.hasKoreanFields && !needsKoreanFields) {\n // Clear any stored data\n const setRemovedFieldState = prevState => ({\n data: { ...prevState.data, [ENCRYPTED_PWD_FIELD]: undefined },\n valid: { ...prevState.valid, [ENCRYPTED_PWD_FIELD]: false },\n errors: { ...prevState.errors, [ENCRYPTED_PWD_FIELD]: false },\n hasKoreanFields: false\n });\n\n this.setState(setRemovedFieldState, () => {\n this.props.onChange(this.state);\n });\n\n this.csf.removeSecuredField(ENCRYPTED_PWD_FIELD);\n this.csf.setKCPStatus(false);\n }\n\n // Wasn't korean, now is - show password field\n if (!this.state.hasKoreanFields && needsKoreanFields) {\n const setAddedFieldState = prevState => ({\n valid: { ...prevState.valid, [ENCRYPTED_PWD_FIELD]: false },\n hasKoreanFields: true,\n isSfpValid: false\n });\n\n this.setState(setAddedFieldState, () => {\n this.props.onChange(this.state);\n });\n\n this.csf.addSecuredField(ENCRYPTED_PWD_FIELD);\n this.csf.setKCPStatus(true);\n }\n }\n\n public getChildContext(): object {\n return { i18n: this.props.i18n };\n }\n\n public handleUnsupportedCard(errObj: CardErrorData): boolean {\n const hasUnsupportedCard = !!errObj.error;\n\n // Store the brand(s) we detected and which we don't support\n if (hasUnsupportedCard) {\n this.setState({ detectedUnsupportedBrands: errObj.detectedBrands });\n }\n\n errObj.rootNode = this.rootNode; // Needed for CustomCard\n this.handleOnError(errObj, hasUnsupportedCard);\n // Inform CSF that the number field has an unsupportedCard error (or that it has been cleared)\n if (this.csf) {\n this.csf.hasUnsupportedCard(ENCRYPTED_CARD_NUMBER, errObj.error);\n }\n return hasUnsupportedCard;\n }\n\n public setFocusOn(frame: string): void {\n if (this.csf) this.csf.setFocusOnFrame(frame);\n }\n\n public updateStyles(stylesObj: StylesObject): void {\n if (this.csf) this.csf.updateStyles(stylesObj);\n }\n\n public sfIsOptionalOrHidden(fieldType: string): boolean {\n return this.csf.sfIsOptionalOrHidden(fieldType);\n }\n\n public destroy(): void {\n if (this.csf) this.csf.destroy();\n }\n\n public showValidation(): void {\n const { numDateFields, state }: SecuredFieldsProvider = this;\n\n Object.keys(state.valid)\n .reduce(getErrorReducer(numDateFields, state), [])\n .forEach(field => {\n // For each detected error pass an error object to the handler (calls error callback & sets state)\n const errorObj: CardErrorData = getErrorObject(field, this.rootNode, state);\n this.handleOnError(errorObj, !!state.detectedUnsupportedBrands);\n // Inform the secured-fields instance of which fields have been found to have errors\n if (this.csf && this.csf.isValidated) {\n this.csf.isValidated(field, errorObj.error);\n }\n });\n }\n\n /**\n * Map SF errors to ValidationRuleResult-like objects, for CardInput component\n */\n public mapErrorsToValidationRuleResult(): SFStateErrorObj {\n const fieldNames: string[] = Object.keys(this.state.errors);\n\n const sfStateErrorsObj = fieldNames.reduce((acc, fieldName) => {\n const errorCode = this.state.errors[fieldName];\n if (errorCode) {\n acc[fieldName] = {\n isValid: false,\n errorMessage: getErrorMessageFromCode(errorCode, SF_ErrorCodes), // this is the human-readable, untranslated, explanation of the error that will exist on the error object in card.state.errors\n // For v5 the object found in state.errors should also contain the additional properties that used to be sent to the onError callback\n // namely: translation, errorCode, a ref to rootNode &, in the case of failed binLookup, an array of the detectedBrands\n errorI18n: this.props.i18n.get(errorCode),\n error: errorCode,\n rootNode: this.rootNode,\n ...(this.state.detectedUnsupportedBrands && { detectedBrands: this.state.detectedUnsupportedBrands })\n };\n } else {\n acc[fieldName] = null;\n }\n return acc;\n }, {});\n return sfStateErrorsObj;\n }\n\n public processBinLookupResponse(binLookupResponse: BinLookupResponse, resetObject: SingleBrandResetObject): void {\n // If we were dealing with an unsupported card & now we have a valid /binLookup response (or a response triggering a reset of the UI),\n // - reset state to clear the error & the stored unsupportedBrands and, in the case of a valid /binLookup response, inform CSF (via handleUnsupportedCard)\n // (Scenario: from an unsupportedCard state the shopper has pasted another number long enough to trigger a /binLookup)\n if (this.state.detectedUnsupportedBrands) {\n this.setState(prevState => ({\n errors: { ...prevState.errors, [ENCRYPTED_CARD_NUMBER]: false },\n detectedUnsupportedBrands: null\n }));\n\n // If we have some sort of binLookupResponse object then this isn't the reset caused by digits dropping below a threshold\n // - so call handleUnsupportedCard to clear the error\n if (this.csf && binLookupResponse) {\n const errObj: CardErrorData = {\n type: 'card',\n fieldType: 'encryptedCardNumber',\n error: ''\n };\n this.handleUnsupportedCard(errObj);\n }\n }\n\n this.issuingCountryCode = binLookupResponse?.issuingCountryCode?.toLowerCase();\n\n const hasBrandedResetObj = resetObject?.brand;\n\n /**\n * Are we dealing with a \"dedicated\" card scenario i.e a card component created as: checkout.create('bcmc') but which can accept multiple brands\n * - in which case we will need to reset brand and pass on the resetObj to CSF\n */\n const mustResetDedicatedBrand = hasBrandedResetObj && DEDICATED_CARD_COMPONENTS.includes(resetObject.brand);\n\n if (mustResetDedicatedBrand) {\n // resetObject.brand will be the value of the brand whose logo we want to reshow in the UI\n this.setState(resetObject, () => {\n this.props.onChange(this.state);\n });\n }\n\n /**\n * Scenarios:\n *\n * - RESET (binLookupResponse === null): The number of digits in number field has dropped below threshold for BIN lookup\n * - RESULT (binLookupResponse.supportedBrands.length === 1): binLookup has found a result so inform CSF\n *\n * In the RESET scenario, for \"dedicated\" card components we also need to pass on the resetObject since this contains information about\n * the brand that CSF needs to reset to, internally.\n */\n if (this.csf) this.csf.brandsFromBinLookup(binLookupResponse, mustResetDedicatedBrand ? resetObject : null);\n }\n\n private setRootNode = (input: HTMLElement): void => {\n this.rootNode = input;\n };\n\n public render(props, state) {\n return props.render({ setRootNode: this.setRootNode, setFocusOn: this.setFocusOn }, state);\n }\n}\n\nexport default SecuredFieldsProvider;\n"],"names":["SecuredFieldsProvider","Component","componentDidMount","this","props","rootNode","setRootNode","fields","getFields","valid","reduce","validFieldsReducer","setState","forEach","field","numCharsInField","numDateFields","filter","f","match","length","destroy","initializeCSF","handleOnNoDataRequired","componentDidUpdate","checkForKCPFields","onStateUpdate","state","componentWillUnmount","csf","clearTimeout","csfLoadFailTimeout","csfConfigFailTimeout","root","loadingContext","csfSetupObj","type","clientKey","cardGroupTypes","brands","autoFocus","trimTrailingSeparator","keypadFix","showWarnings","iframeUIConfig","sfStyles","styles","i18n","callbacks","onLoad","handleOnLoad","onConfigSuccess","handleOnConfigSuccess","onFieldValid","handleOnFieldValid","onAllValid","handleOnAllValid","onBrand","handleOnBrand","onError","handleOnError","onFocus","handleFocus","onBinValue","onAutoComplete","handleOnAutoComplete","onAdditionalSFConfig","onAdditionalSFRemoved","onTouchstartIOS","handleOnTouchstartIOS","onKeyPressed","handleKeyPressed","isKCP","hasKoreanFields","legacyInputMode","minimumExpiryDate","implementationType","forceCompat","maskSecurityCode","exposeExpiryDate","shouldDisableIOSArrowKeys","disableIOSArrowKeys","placeholders","showContextualElement","initCSF","setTimeout","status","AdyenCheckoutError","csfLoadFailTimeoutMS","needsKoreanFields","koreanAuthenticationRequired","issuingCountryCode","countryCode","setRemovedFieldState","prevState","data","ENCRYPTED_PWD_FIELD","undefined","errors","onChange","removeSecuredField","setKCPStatus","setAddedFieldState","isSfpValid","addSecuredField","getChildContext","handleUnsupportedCard","errObj","hasUnsupportedCard","error","detectedUnsupportedBrands","detectedBrands","ENCRYPTED_CARD_NUMBER","setFocusOn","frame","setFocusOnFrame","updateStyles","stylesObj","sfIsOptionalOrHidden","fieldType","showValidation","Object","keys","getErrorReducer","errorObj","getErrorObject","isValidated","mapErrorsToValidationRuleResult","acc","fieldName","errorCode","isValid","errorMessage","getErrorMessageFromCode","SF_ErrorCodes","errorI18n","get","processBinLookupResponse","binLookupResponse","resetObject","toLowerCase","hasBrandedResetObj","brand","mustResetDedicatedBrand","DEDICATED_CARD_COMPONENTS","includes","brandsFromBinLookup","render","constructor","super","_define_property","csfConfigFailTimeoutMS","input","stateObj","cvcPolicy","CVC_POLICY_REQUIRED","expiryDatePolicy","DATE_POLICY_REQUIRED","handlers","bind","defaultProps"],"mappings":"sxBA8BA,MAAMA,UAA8BC,EAyEzBC,iBAAAA,GAECC,KAAKC,MAAMC,UACXF,KAAKG,YAAYH,KAAKC,MAAMC,UAIhC,MAAME,EAASC,EAAUL,KAAKE,UACxBI,EAAQF,EAAOG,OA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KyD,cAAgBkG,EAASlG,cAAcmG,KAAK5J,MACjDA,KAAKoB,uBAAyBuI,EAASvI,uBAAuBwI,KAAK5J,MACnEA,KAAK8D,qBAAuB6F,EAAS7F,qBAAqB8F,KAAK5J,MAC/DA,KAAKkE,sBAAwByF,EAASzF,sBAAsB0F,KAAK5J,MACjEA,KAAKoE,iBAAmBuF,EAASvF,iBAAiBwF,KAAK5J,MAEvDA,KAAKsI,yBAA2BtI,KAAKsI,yBAAyBsB,KAAK5J,MAGnEA,KAAK8G,WAAa9G,KAAK8G,WAAW8C,KAAK5J,MACvCA,KAAKiH,aAAejH,KAAKiH,aAAa2C,KAAK5J,MAC3CA,KAAKuG,sBAAwBvG,KAAKuG,sBAAsBqD,KAAK5J,MAC7DA,KAAKqH,eAAiBrH,KAAKqH,eAAeuC,KAAK5J,MAC/CA,KAAKkB,QAAUlB,KAAKkB,QAAQ0I,KAAK5J,KACrC,EAEAmJ,EAvEEtJ,EAuEYgK,eAAeA"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createElement as t}from"../../../external/preact/dist/preact.js";import e from"../BaseElement/BaseElement.js";import s from"../PayButton/PayButton.js";import{assertIsDropin as i,getRegulatoryDefaults as n,sanitizeResponse as o,verifyPaymentDidNotFail as r,cleanupFinalResult as a}from"./utils.js";import h,{NETWORK_ERROR as l}from"../../../core/Errors/AdyenCheckoutError.js";import{hasOwnProperty as d}from"../../../utils/hasOwnProperty.js";import{ANALYTICS_SUBMIT_STR as
|
|
1
|
+
import{createElement as t}from"../../../external/preact/dist/preact.js";import e from"../BaseElement/BaseElement.js";import s from"../PayButton/PayButton.js";import{assertIsDropin as i,getRegulatoryDefaults as n,sanitizeResponse as o,verifyPaymentDidNotFail as r,cleanupFinalResult as a}from"./utils.js";import h,{NETWORK_ERROR as l}from"../../../core/Errors/AdyenCheckoutError.js";import{hasOwnProperty as d}from"../../../utils/hasOwnProperty.js";import{ANALYTICS_SUBMIT_STR as c,ANALYTICS_ERROR_TYPE as p}from"../../../core/Analytics/constants.js";import m from"../../../core/Errors/CancelError.js";import{AnalyticsLogEvent as u}from"../../../core/Analytics/AnalyticsLogEvent.js";import{AnalyticsErrorEvent as y}from"../../../core/Analytics/AnalyticsErrorEvent.js";function f(t,e,s){return e in t?Object.defineProperty(t,e,{value:s,enumerable:!0,configurable:!0,writable:!0}):t[e]=s,t}class R extends e{buildElementProps(t){const e={showPayButton:!0,...this.core.getCorePropsForComponent(),...!!t?.isStoredPaymentMethod?{}:this.getPaymentMethodFromPaymentMethodsResponse(t?.type),...t},s=i(this);this.props=this.formatProps({...this.constructor.defaultProps,...n(this.core.options.countryCode,s),...e})}getPaymentMethodFromPaymentMethodsResponse(t){return this.core.paymentMethodsResponse.find(t||this.constructor.type)}storeElementRefOnCore(t){t?.isDropin||this.core.storeElementReference(this)}isAvailable(){return Promise.resolve()}setState(t){this.state={...this.state,...t},this.onChange()}showValidation(){return this.componentRef&&this.componentRef.showValidation&&this.componentRef.showValidation(),this}setElementStatus(t,e){return this.elementRef?.setStatus(t,e),this}setStatus(t,e){return this.componentRef?.setStatus&&this.componentRef.setStatus(t,e),this}onChange(){this.props.onChange?.({data:this.data,isValid:this.isValid,errors:this.state.errors,valid:this.state.valid},this.elementRef)}setUpAnalytics(t){const e=this.props.session?.id;return this.props.modules.analytics.setUp({...t,...e&&{sessionId:e}})}submitAnalytics(t){try{t.component=this.getComponent(t),this.props.modules.analytics.sendAnalytics(t)}catch(t){console.warn("Failed to submit the analytics event. Error:",t)}}getComponent({component:t}){return t||(this.constructor.analyticsType?this.constructor.analyticsType:"scheme"===this.constructor.type||"bcmc"===this.constructor.type?this.constructor.type:this.type)}submit(){this.isValid?this.makePaymentsCall().then(o).then(r).then(this.handleResponse).catch((t=>{t instanceof m?this.setElementStatus("ready"):this.handleFailedResult(t)})):this.showValidation()}makePaymentsCall(){if(this.setElementStatus("loading"),this.props.onSubmit)return this.submitUsingAdvancedFlow();if(this.core.session){return(this.props.beforeSubmit?new Promise(((t,e)=>this.props.beforeSubmit(this.data,this.elementRef,{resolve:t,reject:()=>e(new m("beforeSubmitRejected"))}))):Promise.resolve(this.data)).then(this.submitUsingSessionsFlow)}this.handleError(new h("IMPLEMENTATION_ERROR",'It can not perform /payments call. Callback "onSubmit" is missing or Checkout session is not available'))}async submitUsingAdvancedFlow(){return new Promise(((t,e)=>{const s=new u({type:c,message:"Shopper clicked pay"});this.submitAnalytics(s),this.props.onSubmit({data:this.data,isValid:this.isValid},this.elementRef,{resolve:t,reject:e})}))}async submitUsingSessionsFlow(t){const e=new u({type:c,message:"Shopper clicked pay"});this.submitAnalytics(e);try{return await this.core.session.submitPayment(t)}catch(t){return t instanceof h?this.handleError(t):this.handleError(new h("ERROR","Error when making /payments call",{cause:t})),Promise.reject(t)}}onComplete(t){this.props.onComplete&&this.props.onComplete(t,this.elementRef)}handleAdditionalDetails(t){this.makeAdditionalDetailsCall(t).then(o).then(r).then(this.handleResponse).catch(this.handleFailedResult)}makeAdditionalDetailsCall(t){return this.props.onAdditionalDetails?new Promise(((e,s)=>{this.props.onAdditionalDetails(t,this.elementRef,{resolve:e,reject:s})})):this.core.session?this.submitAdditionalDetailsUsingSessionsFlow(t.data):void this.handleError(new h("IMPLEMENTATION_ERROR",'It can not perform /payments/details call. Callback "onAdditionalDetails" is missing or Checkout session is not available'))}async submitAdditionalDetailsUsingSessionsFlow(t){try{return await this.core.session.submitDetails(t)}catch(t){return t instanceof h?this.handleError(t):this.handleError(new h("ERROR","Error when making /details call",{cause:t})),Promise.reject(t)}}handleAction(t,e={}){if(!t||!t.type){if(d(t,"action")&&d(t,"resultCode"))throw new Error('handleAction::Invalid Action - the passed action object itself has an "action" property and a "resultCode": have you passed in the whole response object by mistake?');throw new Error('handleAction::Invalid Action - the passed action object does not have a "type" property')}const s=this.core.createFromAction(t,{...this.elementRef.props,...e,onAdditionalDetails:this.handleAdditionalDetails});return s?(this.unmount(),s.mount(this._node)):null}onActionHandled(t){this.props?.onActionHandled?.({originalAction:this.props.originalAction,...t})}handleResponse(t){t.action?this.elementRef.handleAction(t.action):t.order?.remainingAmount?.value>0?this.handleOrder(t):this.handleSuccessResult(t)}handleKeyPress(t){"Enter"!==t.key&&"Enter"!==t.code||(t.preventDefault(),this.onEnterKeyPressed(document?.activeElement,this))}onEnterKeyPressed(t,e){this.props.onEnterKeyPressed?this.props.onEnterKeyPressed(t,e):(t.blur(),this.submit())}updateParent(t={}){return this.elementRef.core.update(t)}get isValid(){return!1}get icon(){const t=this.props.paymentMethodType||this.type;return this.props.icon??this.resources.getImage()(t)}get displayName(){const t=this.core.paymentMethodsResponse?.paymentMethods?.find((t=>t.type===this.type));return this.props.name||t?.name||this.type}get accessibleName(){return this.displayName}get additionalInfo(){return null}get type(){return this.props.type||this.constructor.type}async handleAdvanceFlowPaymentMethodsUpdate(t,e){return new Promise(((e,s)=>{if(!this.props.onPaymentMethodsRequest)return e();this.props.onPaymentMethodsRequest({...t&&{order:{orderData:t.orderData,pspReference:t.pspReference}},locale:this.core.options.locale},{resolve:e,reject:s})})).catch((t=>{this.handleError(new h("IMPLEMENTATION_ERROR","Something failed during payment methods update or onPaymentMethodsRequest was not implemented",{cause:t}))})).then((s=>this.core.update({...s&&{paymentMethodsResponse:s},order:t,amount:t?t.remainingAmount:e})))}constructor(e,n){super(e,n),f(this,"componentRef",void 0),f(this,"resources",void 0),f(this,"elementRef",void 0),f(this,"handleError",(t=>{if(this.setElementStatus("ready"),t.name===l&&t.options.code){const e=new y({errorType:p.apiError,code:t.options.code});this.submitAnalytics(e)}this.props.onError&&this.props.onError(t,this.elementRef)})),f(this,"handleOrder",(t=>{const{order:e}=t;(this.core.session?this.core.update({order:e}):this.handleAdvanceFlowPaymentMethodsUpdate(e)).then((()=>{this.props.onOrderUpdated?.({order:e})}))})),f(this,"handleFailedResult",(t=>{i(this.elementRef)&&this.elementRef.displayFinalAnimation("error"),a(t),this.props.onPaymentFailed?.(t,this.elementRef)})),f(this,"handleSuccessResult",(t=>{i(this.elementRef)&&this.elementRef.displayFinalAnimation("success"),a(t),this.props.onPaymentCompleted?.(t,this.elementRef)})),f(this,"setComponentRef",(t=>{this.componentRef=t})),f(this,"payButton",(e=>t(s,{...e,amount:this.props.amount,secondaryAmount:this.props.secondaryAmount,onClick:this.submit}))),this.core.register(this.constructor),this.submit=this.submit.bind(this),this.setState=this.setState.bind(this),this.onComplete=this.onComplete.bind(this),this.handleAction=this.handleAction.bind(this),this.handleOrder=this.handleOrder.bind(this),this.handleAdditionalDetails=this.handleAdditionalDetails.bind(this),this.handleResponse=this.handleResponse.bind(this),this.setElementStatus=this.setElementStatus.bind(this),this.submitAnalytics=this.submitAnalytics.bind(this),this.makePaymentsCall=this.makePaymentsCall.bind(this),this.makeAdditionalDetailsCall=this.makeAdditionalDetailsCall.bind(this),this.submitUsingSessionsFlow=this.submitUsingSessionsFlow.bind(this),this.elementRef=n&&n.elementRef||this,this.resources=this.props.modules?this.props.modules.resources:void 0,this.storeElementRefOnCore(this.props),this.onEnterKeyPressed=this.onEnterKeyPressed.bind(this),this.onActionHandled=this.onActionHandled.bind(this)}}f(R,"type",void 0),f(R,"txVariants",[]);export{R as UIElement,R as default};
|
|
2
2
|
//# sourceMappingURL=UIElement.js.map
|