repo
stringclasses
4 values
file_path
stringlengths
6
193
extension
stringclasses
23 values
content
stringlengths
0
1.73M
token_count
int64
0
724k
__index_level_0__
int64
0
10.8k
hyperswitch-client-core
src/utility/constants/SdkStatusMessages.res
.res
type statusMessages = { successMsg: string, errorMsg: string, apiCallFailure: string, } let retrievePaymentStatus = { successMsg: "payment successful", errorMsg: "payment failed", apiCallFailure: "retrieve failure, cannot fetch the status of payment", } let pollingCallStatus = { successMsg: "polling status complete", errorMsg: "payment status pending", apiCallFailure: "polling failure, cannot fetch the status of payment", } let externalThreeDsModuleStatus = { successMsg: "external 3DS dependency found", errorMsg: "integration error, external 3DS dependency not found", apiCallFailure: "", } let authorizeCallStatus = { successMsg: "payment authorised successfully", errorMsg: "authorize failed", apiCallFailure: "authorize failure, cannot process this payment", } let authenticationCallStatus = { successMsg: "authentication call successful", errorMsg: "authentication call fail", apiCallFailure: "authentication failure,something wrong with AReq", } let threeDsSdkChallengeStatus = { successMsg: "challenge generated successfully", errorMsg: "challenge generation failed", apiCallFailure: "", } let threeDsSDKGetAReqStatus = { successMsg: "", errorMsg: "3DS SDK DDC failure, cannot generate AReq params", apiCallFailure: "", }
293
10,631
hyperswitch-client-core
src/utility/config/next/NextImpl.native.res
.res
1
10,632
hyperswitch-client-core
src/utility/test/TestUtils.res
.res
let cardNumberInputTestId = "CardNumberInputTestId" let cvcInputTestId = "CVCInputTestId" let expiryInputTestId = "ExpiryInputTestId" let payButtonTestId = "PayButtonTestId"
45
10,633
hyperswitch-client-core
src/contexts/CountryStateDataContext.res
.res
type data = | Localdata(CountryStateDataHookTypes.countryStateData) | FetchData(CountryStateDataHookTypes.countryStateData) | Loading let countryStateDataContext = React.createContext((Loading, () => ())) module Provider = { let make = React.Context.provider(countryStateDataContext) } module WrapperProvider = { @react.component let make = ( ~children, ~initialData: CountryStateDataHookTypes.countryStateData={ countries: [], states: Dict.make(), }, ) => { let (state, setState) = React.useState(_ => Localdata(initialData)) let (nativeProp, _) = React.useContext(NativePropContext.nativePropContext) let locale = nativeProp.configuration.appearance.locale let countryStateDataHook = S3ApiHook.useFetchDataFromS3WithGZipDecoding() let isDataFetched = React.useRef(false) let logger = LoggerHook.useLoggerHook() let path = "/location" let fetchCountryStateData = () => { if !isDataFetched.current { ///do not change the ordering of the code below isDataFetched.current = true setState(_ => Loading) countryStateDataHook( ~decodeJsonToRecord=S3ApiHook.decodeJsonTocountryStateData, ~s3Path=`${path}/${SdkTypes.localeTypeToString(locale)}`, ) ->Promise.then(res => { let fetchedData = res->Option.getExn if fetchedData.countries->Js.Array2.length == 0 { Promise.reject(Exn.raiseError("API call failed")) } else { setState(_ => FetchData(fetchedData)) Promise.resolve() } }) ->Promise.catch(_ => { countryStateDataHook( ~decodeJsonToRecord=S3ApiHook.decodeJsonTocountryStateData, ~s3Path=`${path}/${SdkTypes.localeTypeToString(Some(En))}`, ) ->Promise.then(res => { let fetchedData = res->Option.getExn if fetchedData.countries->Js.Array2.length == 0 { Promise.reject(Exn.raiseError("Api call failed again")) } else { setState(_ => FetchData(fetchedData)) Promise.resolve() } }) ->Promise.catch(_ => { setState(_ => Localdata(initialData)) Promise.resolve() }) }) ->ignore } else { logger( ~logType=INFO, ~value="tried to call country state api call agian", ~category=API, ~eventName=S3_API, (), ) } } <Provider value=(state, fetchCountryStateData)> children </Provider> } } type temp = option<CountryStateDataHookTypes.countryStateData> @react.component let make = (~children) => { let (state: temp, setState) = React.useState(_ => None) React.useEffect0(() => { RequiredFieldsTypes.importStatesAndCountries( "./../utility/reusableCodeFromWeb/StatesAndCountry.json", ) ->Promise.then(res => { let initialData = S3ApiHook.decodeJsonTocountryStateData(res) setState(_ => Some(initialData)) Promise.resolve() }) ->Promise.catch(_ => Promise.resolve()) ->ignore None }) switch state { | None => <WrapperProvider> children </WrapperProvider> | Some(data) => <WrapperProvider initialData={data}> children </WrapperProvider> } }
763
10,634
hyperswitch-client-core
src/contexts/PaymentScreenContext.res
.res
type paymentScreenType = PAYMENTSHEET | SAVEDCARDSCREEN let dafaultVal = SAVEDCARDSCREEN let paymentScreenTypeContext = React.createContext((dafaultVal, (_: paymentScreenType) => ())) module Provider = { let make = React.Context.provider(paymentScreenTypeContext) } @react.component let make = (~children) => { let (state, setState) = React.useState(_ => dafaultVal) let setState = React.useCallback1(val => { setState(_ => val) }, [setState]) <Provider value=(state, setState)> children </Provider> }
130
10,635
hyperswitch-client-core
src/contexts/LocaleStringDataContext.res
.res
type data = | Loading | Some(LocaleDataType.localeStrings) let localeDataContext = React.createContext((Loading, (_: data => data) => ())) module Provider = { let make = React.Context.provider(localeDataContext) } @react.component let make = (~children) => { let (state, setState) = React.useState(_ => Loading) let (nativeProp, _) = React.useContext(NativePropContext.nativePropContext) let locale = nativeProp.configuration.appearance.locale let fetchDataFromS3WithGZipDecoding = S3ApiHook.useFetchDataFromS3WithGZipDecoding() //getLocaleStringsFromJson let path = "/locales" React.useEffect0(() => { fetchDataFromS3WithGZipDecoding( ~decodeJsonToRecord=S3ApiHook.getLocaleStringsFromJson, ~s3Path=`${path}/${SdkTypes.localeTypeToString(locale)}`, ) ->Promise.then(res => { switch res { | Some(data) => setState(_ => Some(data)) Promise.resolve() | _ => Promise.reject(Exn.raiseError("API Failed")) } }) ->Promise.catch(_ => { fetchDataFromS3WithGZipDecoding( ~decodeJsonToRecord=S3ApiHook.getLocaleStringsFromJson, ~s3Path=`${path}/${SdkTypes.localeTypeToString(Some(En))}`, ) ->Promise.then( res => { switch res { | Some(data) => setState(_ => Some(data)) Promise.resolve() | _ => Promise.reject(Exn.raiseError("API Failed")) } }, ) ->Promise.catch( _ => { setState(_ => Some(LocaleDataType.defaultLocale)) Promise.resolve() }, ) }) ->ignore None }) <Provider value=(state, setState)> children </Provider> }
406
10,636
hyperswitch-client-core
src/contexts/AllApiDataContext.res
.res
type retryObject = { processor: string, redirectUrl: string, } type additionalPMLData = { retryEnabled: option<retryObject>, redirect_url: option<string>, mandateType: PaymentMethodListType.mandateType, paymentType: option<string>, merchantName: option<string>, requestExternalThreeDsAuthentication: option<bool>, } let additionalPMLData = { retryEnabled: None, redirect_url: None, mandateType: NORMAL, paymentType: None, merchantName: None, requestExternalThreeDsAuthentication: None, } type paymentList = array<PaymentMethodListType.payment_method> let paymentList = [ PaymentMethodListType.CARD({ payment_method: "card", payment_method_type: "debit", card_networks: None, required_field: [], }), ] type sessions = Some(array<SessionsType.sessions>) | Loading | None let sessions = Loading // type paymentMethodSelected= CARD|WALLET|NONE type selectedPMObject = { walletName: SdkTypes.payment_method_type_wallet, token: option<string>, } type savedPaymentMethodDataObj = { pmList: option<array<SdkTypes.savedDataType>>, isGuestCustomer: bool, selectedPaymentMethod: option<selectedPMObject>, } type savedPaymentMethods = Loading | Some(savedPaymentMethodDataObj) | None let savedPaymentMethods: savedPaymentMethods = Loading let dafaultsavePMObj = {pmList: None, isGuestCustomer: false, selectedPaymentMethod: None} type allApiData = { additionalPMLData: additionalPMLData, paymentList: paymentList, sessions: sessions, savedPaymentMethods: savedPaymentMethods, } let dafaultVal = { additionalPMLData, paymentList, sessions, savedPaymentMethods, } let allApiDataContext = React.createContext((dafaultVal, (_: allApiData) => ())) module Provider = { let make = React.Context.provider(allApiDataContext) } @react.component let make = (~children, ~defaultViewEnabled=false) => { let (state, setState) = React.useState(_ => dafaultVal) let setState = React.useCallback1(val => { setState(_ => val) }, [setState]) <Provider value=(state, setState)> children </Provider> }
508
10,637
hyperswitch-client-core
src/contexts/CardDataContext.res
.res
type cardData = { cardNumber: string, expireDate: string, cvv: string, zip: string, isCardNumberValid: option<bool>, isCardBrandSupported: option<bool>, isExpireDataValid: option<bool>, isCvvValid: option<bool>, isZipValid: option<bool>, cardBrand: string, selectedCoBadgedCardBrand: option<string>, } let dafaultVal = { cardNumber: "", expireDate: "", cvv: "", zip: "", isCardNumberValid: None, isCardBrandSupported: None, isExpireDataValid: None, isCvvValid: None, isZipValid: None, cardBrand: "", selectedCoBadgedCardBrand: None, } let cardDataContext = React.createContext((dafaultVal, (_: cardData => cardData) => ())) module Provider = { let make = React.Context.provider(cardDataContext) } @react.component let make = (~children) => { let (state, setState) = React.useState(_ => dafaultVal) <Provider value=(state, setState)> children </Provider> }
254
10,638
hyperswitch-client-core
src/contexts/NativePropContext.res
.res
let defaultValue: SdkTypes.nativeProp = SdkTypes.nativeJsonToRecord(JSON.Encode.null, 1) let defaultSetter = (_: SdkTypes.nativeProp) => () let nativePropContext = React.createContext((defaultValue, defaultSetter)) module Provider = { let make = React.Context.provider(nativePropContext) } @react.component let make = (~nativeProp: SdkTypes.nativeProp, ~children) => { let (state, setState) = React.useState(_ => nativeProp) React.useEffect1(() => { setState(_ => nativeProp) None }, [nativeProp]) let setState = React.useCallback1(val => { setState(_ => val) }, [setState]) let value = React.useMemo2(() => { (state, setState) }, (state, setState)) <Provider value> children </Provider> }
185
10,639
hyperswitch-client-core
src/contexts/LoggerContext.res
.res
let defaultSetter = (_: Dict.t<float>) => () let loggingContext = React.createContext((Dict.make(), defaultSetter)) module Provider = { let make = React.Context.provider(loggingContext) } @react.component let make = (~children) => { let (state, setState) = React.useState(_ => Dict.make()) let setState = React.useCallback1(val => { setState(_ => val) }, [setState]) <Provider value=(state, setState)> children </Provider> }
104
10,640
hyperswitch-client-core
src/contexts/ThemeContext.res
.res
type appObj = SdkTypes.appearance type themeType = Light(appObj) | Dark(appObj) let defaultValue: themeType = Light(SdkTypes.defaultAppearance) let defaultSetter = (_: themeType) => () let themeContext = React.createContext((defaultValue, defaultSetter)) module Provider = { let make = React.Context.provider(themeContext) } @react.component let make = (~children) => { let (nativeProp, _) = React.useContext(NativePropContext.nativePropContext) let isDarkMode = LightDarkTheme.useIsDarkMode() let (theme, setTheme) = React.useState(_ => isDarkMode ? Dark(nativeProp.configuration.appearance) : Light(nativeProp.configuration.appearance) ) let setTheme = React.useCallback1(val => { setTheme(_ => val) }, [setTheme]) let value = React.useMemo2(() => { (theme, setTheme) }, (theme, setTheme)) <Provider value> children </Provider> }
221
10,641
hyperswitch-client-core
src/contexts/LoadingContext.res
.res
type processingPayments = {showOverlay: bool} type sdkPaymentState = | FillingDetails | ProcessingPayments(option<processingPayments>) | PaymentSuccess | PaymentCancelled let defaultSetter = (_: sdkPaymentState) => () let loadingContext = React.createContext((FillingDetails, defaultSetter)) module Provider = { let makeProps = (~value, ~children, ()) => { "value": value, "children": children, } let make = React.Context.provider(loadingContext) } @react.component let make = (~children) => { let (state, setState) = React.useState(_ => FillingDetails) let setState = React.useCallback1(val => { setState(_ => val) }, [setState]) <Provider value=(state, setState)> children </Provider> }
176
10,642
hyperswitch-client-core
src/contexts/ViewportContext.res
.res
type viewPortContants = { windowHeight: float, windowWidth: float, screenHeight: float, screenWidth: float, navigationBarHeight: float, maxPaymentSheetHeight: float, } let defaultNavbarHeight = 25. let windowHeight = ReactNative.Dimensions.get(#window).height let windowWidth = ReactNative.Dimensions.get(#window).width let screenHeight = ReactNative.Dimensions.get(#screen).height let screenWidth = ReactNative.Dimensions.get(#screen).width let statusBarHeight = ReactNative.StatusBar.currentHeight let navigationBarHeight = if ReactNative.Platform.os !== #android { defaultNavbarHeight } else { let navigationHeight = screenHeight -. windowHeight -. statusBarHeight Math.min(75., Math.max(0., navigationHeight) +. defaultNavbarHeight) } let maxPaymentSheetHeight = 95. // pct let defaultVal: viewPortContants = { windowHeight, windowWidth, screenHeight, screenWidth, navigationBarHeight, maxPaymentSheetHeight, } let viewPortContext = React.createContext((defaultVal, (_: viewPortContants) => ())) module Provider = { let make = React.Context.provider(viewPortContext) } @react.component let make = (~children) => { let (state, setState) = React.useState(_ => defaultVal) let setState = React.useCallback1(val => { setState(_ => val) }, [setState]) <Provider value=(state, setState)> children </Provider> }
326
10,643
hyperswitch-client-core
src/icons/ChevronIcon.res
.res
open ReactNative open Style @react.component let make = (~width=20., ~height=16., ~fill="#ffffff") => { <Icon style={viewStyle(~transform=[rotate(~rotate=270.->deg)], ())} name="back" height width fill /> }
75
10,644
hyperswitch-client-core
src/icons/Icon.res
.res
let card = `<svg class="p-Icon p-Icon--card Icon p-Icon--md p-TabIcon TabIcon p-TabIcon--selected TabIcon--selected" role="presentation" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill-rule="evenodd" clip-rule="evenodd" d="M0 4a2 2 0 012-2h12a2 2 0 012 2H0zm0 2v6a2 2 0 002 2h12a2 2 0 002-2V6H0zm3 5a1 1 0 011-1h1a1 1 0 110 2H4a1 1 0 01-1-1z"></path></svg>` let cardv1 = `<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M17.5 3.75H2.5C2.16848 3.75 1.85054 3.8817 1.61612 4.11612C1.3817 4.35054 1.25 4.66848 1.25 5V15C1.25 15.3315 1.3817 15.6495 1.61612 15.8839C1.85054 16.1183 2.16848 16.25 2.5 16.25H17.5C17.8315 16.25 18.1495 16.1183 18.3839 15.8839C18.6183 15.6495 18.75 15.3315 18.75 15V5C18.75 4.66848 18.6183 4.35054 18.3839 4.11612C18.1495 3.8817 17.8315 3.75 17.5 3.75ZM17.5 5V6.875H2.5V5H17.5ZM17.5 15H2.5V8.125H17.5V15ZM16.25 13.125C16.25 13.2908 16.1842 13.4497 16.0669 13.5669C15.9497 13.6842 15.7908 13.75 15.625 13.75H13.125C12.9592 13.75 12.8003 13.6842 12.6831 13.5669C12.5658 13.4497 12.5 13.2908 12.5 13.125C12.5 12.9592 12.5658 12.8003 12.6831 12.6831C12.8003 12.5658 12.9592 12.5 13.125 12.5H15.625C15.7908 12.5 15.9497 12.5658 16.0669 12.6831C16.1842 12.8003 16.25 12.9592 16.25 13.125ZM11.25 13.125C11.25 13.2908 11.1842 13.4497 11.0669 13.5669C10.9497 13.6842 10.7908 13.75 10.625 13.75H9.375C9.20924 13.75 9.05027 13.6842 8.93306 13.5669C8.81585 13.4497 8.75 13.2908 8.75 13.125C8.75 12.9592 8.81585 12.8003 8.93306 12.6831C9.05027 12.5658 9.20924 12.5 9.375 12.5H10.625C10.7908 12.5 10.9497 12.5658 11.0669 12.6831C11.1842 12.8003 11.25 12.9592 11.25 13.125Z" fill="#006DF9"/></svg>` let close = `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16" fill="none"><path d="M13.7429 2.27713C13.3877 1.92197 12.8117 1.92197 12.4618 2.27713L8.01009 6.71659L3.55299 2.26637C3.19771 1.91121 2.62173 1.91121 2.27184 2.26637C1.91656 2.62152 1.91656 3.19731 2.27184 3.54709L6.72356 7.99731L2.26646 12.4529C1.91118 12.8081 1.91118 13.3839 2.26646 13.7336C2.62173 14.0888 3.19771 14.0888 3.5476 13.7336L7.99932 9.28341L12.451 13.7336C12.8063 14.0888 13.3823 14.0888 13.7322 13.7336C14.0875 13.3785 14.0875 12.8027 13.7322 12.4529L9.28047 8.00269L13.7322 3.55247C14.0875 3.20807 14.0875 2.62152 13.7429 2.27713Z" fill="#8D8D8D"/></svg>` let cvvempty = `<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path opacity="0.3" fill-rule="evenodd" clip-rule="evenodd" d="M5 6C3.89543 6 3 6.89543 3 8V8.37275H21V8C21 6.89543 20.1046 6 19 6H5ZM21 11.0728H3V16.2727C3 17.3773 3.89543 18.2727 5 18.2727H19C20.1046 18.2727 21 17.3773 21 16.2727V11.0728ZM4.15385 15.4616C4.15385 15.3341 4.25717 15.2308 4.38462 15.2308H7.15385C7.2813 15.2308 7.38462 15.3341 7.38462 15.4616C7.38462 15.589 7.2813 15.6923 7.15385 15.6923H4.38462C4.25717 15.6923 4.15385 15.589 4.15385 15.4616ZM4.38462 16.1538C4.25717 16.1538 4.15385 16.2571 4.15385 16.3846C4.15385 16.512 4.25717 16.6154 4.38462 16.6154H9.92308C10.0505 16.6154 10.1538 16.512 10.1538 16.3846C10.1538 16.2571 10.0505 16.1538 9.92308 16.1538H4.38462Z" fill="#979797"/><circle cx="17.0769" cy="12" r="2.76923" fill="#858F97"/><path d="M15.6248 11.3891V12.8914H15.9278V11.1086H15.2308V11.3891H15.6248Z" fill="white"/><path d="M17.4904 12.8889V12.5987H16.7416L17.0667 12.3231C17.3401 12.0914 17.4781 11.9036 17.4781 11.6549C17.4781 11.294 17.2391 11.0769 16.8549 11.0769C16.4732 11.0769 16.222 11.3305 16.2195 11.7207H16.5323C16.5347 11.4915 16.6579 11.3549 16.8549 11.3549C17.0446 11.3549 17.1554 11.4695 17.1554 11.672C17.1554 11.8427 17.0741 11.9597 16.8303 12.1646L16.2417 12.6572V12.8914L17.4904 12.8889Z" fill="white"/><path d="M18.2335 12.0085C18.4847 12.0085 18.6029 12.1402 18.6029 12.3207C18.6029 12.5182 18.4724 12.645 18.2753 12.645C18.0832 12.645 17.9551 12.528 17.9551 12.3231H17.6448C17.6448 12.7084 17.9182 12.9231 18.2704 12.9231C18.6349 12.9231 18.9231 12.6914 18.9231 12.3256C18.9231 12.011 18.7088 11.811 18.4329 11.7573L18.8714 11.3574V11.1086H17.7285V11.3842H18.4773L18.0142 11.8061V12.0085H18.2335Z" fill="white"/></svg>` let cvvfilled = `<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path opacity="0.3" fill-rule="evenodd" clip-rule="evenodd" d="M5 6C3.89543 6 3 6.89543 3 8V8.37275H21V8C21 6.89543 20.1046 6 19 6H5ZM21 11.0728H3V16.2727C3 17.3773 3.89543 18.2727 5 18.2727H19C20.1046 18.2727 21 17.3773 21 16.2727V11.0728ZM4.15385 15.4616C4.15385 15.3341 4.25717 15.2308 4.38462 15.2308H7.15385C7.2813 15.2308 7.38462 15.3341 7.38462 15.4616C7.38462 15.589 7.2813 15.6923 7.15385 15.6923H4.38462C4.25717 15.6923 4.15385 15.589 4.15385 15.4616ZM4.38462 16.1538C4.25717 16.1538 4.15385 16.2571 4.15385 16.3846C4.15385 16.512 4.25717 16.6154 4.38462 16.6154H9.92308C10.0505 16.6154 10.1538 16.512 10.1538 16.3846C10.1538 16.2571 10.0505 16.1538 9.92308 16.1538H4.38462Z" fill="#979797"/><circle cx="17.0769" cy="12" r="2.76923" fill="#006DF9"/><path d="M15.6248 11.3891V12.8914H15.9278V11.1086H15.2308V11.3891H15.6248Z" fill="white"/><path d="M17.4904 12.8889V12.5987H16.7416L17.0667 12.3231C17.3401 12.0914 17.4781 11.9036 17.4781 11.6549C17.4781 11.294 17.2391 11.0769 16.8549 11.0769C16.4732 11.0769 16.2219 11.3305 16.2195 11.7207H16.5323C16.5347 11.4915 16.6579 11.3549 16.8549 11.3549C17.0446 11.3549 17.1554 11.4695 17.1554 11.672C17.1554 11.8427 17.0741 11.9597 16.8303 12.1646L16.2417 12.6572V12.8914L17.4904 12.8889Z" fill="white"/><path d="M18.2334 12.0085C18.4847 12.0085 18.6029 12.1402 18.6029 12.3207C18.6029 12.5182 18.4724 12.645 18.2753 12.645C18.0832 12.645 17.9551 12.528 17.9551 12.3231H17.6448C17.6448 12.7084 17.9182 12.9231 18.2704 12.9231C18.6349 12.9231 18.9231 12.6914 18.9231 12.3256C18.9231 12.011 18.7088 11.811 18.4329 11.7573L18.8714 11.3574V11.1086H17.7285V11.3842H18.4773L18.0142 11.8061V12.0085H18.2334Z" fill="white"/></svg>` let error = `<?xml version="1.0" encoding="utf-8"?><svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 115.19 123.38" style="enable-background:new 0 0 115.19 123.38" xml:space="preserve"><style type="text/css">.st0{fill-rule:evenodd;clip-rule:evenodd;stroke:#000000;stroke-width:0.5;stroke-miterlimit:2.6131;}</style><g><path class="st0" d="M93.13,79.5c12.05,0,21.82,9.77,21.82,21.82c0,12.05-9.77,21.82-21.82,21.82c-12.05,0-21.82-9.77-21.82-21.82 C71.31,89.27,81.08,79.5,93.13,79.5L93.13,79.5z M8.08,0.25h95.28c2.17,0,4.11,0.89,5.53,2.3c1.42,1.42,2.3,3.39,2.3,5.53v70.01 c-2.46-1.91-5.24-3.44-8.25-4.48V9.98c0-0.43-0.16-0.79-0.46-1.05c-0.26-0.26-0.66-0.46-1.05-0.46H9.94 c-0.43,0-0.79,0.16-1.05,0.46C8.63,9.19,8.43,9.58,8.43,9.98v70.02h0.03l31.97-30.61c1.28-1.18,3.29-1.05,4.44,0.23 c0.03,0.03,0.03,0.07,0.07,0.07l26.88,31.8c-4.73,5.18-7.62,12.08-7.62,19.65c0,3.29,0.55,6.45,1.55,9.4H8.08 c-2.17,0-4.11-0.89-5.53-2.3s-2.3-3.39-2.3-5.53V8.08c0-2.17,0.89-4.11,2.3-5.53S5.94,0.25,8.08,0.25L8.08,0.25z M73.98,79.35 l3.71-22.79c0.3-1.71,1.91-2.9,3.62-2.6c0.66,0.1,1.25,0.43,1.71,0.86l17.1,17.97c-2.18-0.52-4.44-0.79-6.78-0.79 C85.91,71.99,79.13,74.77,73.98,79.35L73.98,79.35z M81.98,18.19c3.13,0,5.99,1.28,8.03,3.32c2.07,2.07,3.32,4.9,3.32,8.03 c0,3.13-1.28,5.99-3.32,8.03c-2.07,2.07-4.9,3.32-8.03,3.32c-3.13,0-5.99-1.28-8.03-3.32c-2.07-2.07-3.32-4.9-3.32-8.03 c0-3.13,1.28-5.99,3.32-8.03C76.02,19.44,78.86,18.19,81.98,18.19L81.98,18.19z M85.82,88.05l19.96,21.6 c1.58-2.39,2.5-5.25,2.5-8.33c0-8.36-6.78-15.14-15.14-15.14C90.48,86.17,87.99,86.85,85.82,88.05L85.82,88.05z M100.44,114.58 l-19.96-21.6c-1.58,2.39-2.5,5.25-2.5,8.33c0,8.36,6.78,15.14,15.14,15.14C95.78,116.46,98.27,115.78,100.44,114.58L100.44,114.58z"/></g></svg>` let lock = `<svg xmlns="http://www.w3.org/2000/svg" width="8" height="11" viewBox="0 0 8 11" fill="none"><path d="M1 10.5566C0.725 10.5566 0.489666 10.4588 0.294 10.2631C0.0983332 10.0675 0.000333333 9.83197 0 9.55664V4.55664C0 4.28164 0.0979999 4.04631 0.294 3.85064C0.49 3.65497 0.725333 3.55697 1 3.55664H1.5V2.55664C1.5 1.86497 1.74383 1.27547 2.2315 0.788141C2.71917 0.300807 3.30867 0.056974 4 0.0566406C4.69167 0.0566406 5.28133 0.300474 5.769 0.788141C6.25666 1.27581 6.50033 1.86531 6.5 2.55664V3.55664H7C7.275 3.55664 7.5105 3.65464 7.7065 3.85064C7.9025 4.04664 8.00033 4.28197 8 4.55664V9.55664C8 9.83164 7.90216 10.0671 7.7065 10.2631C7.51083 10.4591 7.27533 10.557 7 10.5566H1ZM1 9.55664H7V4.55664H1V9.55664ZM4 8.05664C4.275 8.05664 4.5105 7.95881 4.7065 7.76314C4.9025 7.56747 5.00033 7.33197 5 7.05664C5 6.78164 4.90217 6.54631 4.7065 6.35064C4.51083 6.15497 4.27533 6.05697 4 6.05664C3.725 6.05664 3.48967 6.15464 3.294 6.35064C3.09833 6.54664 3.00033 6.78197 3 7.05664C3 7.33164 3.098 7.56714 3.294 7.76314C3.49 7.95914 3.72533 8.05698 4 8.05664ZM2.5 3.55664H5.5V2.55664C5.5 2.13997 5.35417 1.78581 5.0625 1.49414C4.77083 1.20247 4.41667 1.05664 4 1.05664C3.58333 1.05664 3.22917 1.20247 2.9375 1.49414C2.64583 1.78581 2.5 2.13997 2.5 2.55664V3.55664Z" fill="#434343"/></svg>` let waitcard = `<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" clip-rule="evenodd" d="M4 5.18182C2.89543 5.18182 2 6.07726 2 7.18183V8.18182H22V7.18182C22 6.07725 21.1046 5.18182 20 5.18182H4ZM22 10.6818H2V16.8182C2 17.9228 2.89543 18.8182 4 18.8182H20C21.1046 18.8182 22 17.9228 22 16.8182V10.6818ZM3.625 13.1818C3.625 12.9747 3.79289 12.8068 4 12.8068H12C12.2071 12.8068 12.375 12.9747 12.375 13.1818C12.375 13.3889 12.2071 13.5568 12 13.5568H4C3.79289 13.5568 3.625 13.3889 3.625 13.1818ZM4 14.8068C3.79289 14.8068 3.625 14.9747 3.625 15.1818C3.625 15.3889 3.79289 15.5568 4 15.5568H8C8.20711 15.5568 8.375 15.3889 8.375 15.1818C8.375 14.9747 8.20711 14.8068 8 14.8068H4Z" fill="#979797"/></svg>` let camera = `<svg viewBox="0 0 18 16" xmlns="http://www.w3.org/2000/svg"><path d="M4.79203 2.09772H4.83575L4.86544 2.06563L6.37742 0.431055H11.29L12.802 2.06563L12.8316 2.09772H12.8754H15.5004C15.932 2.09772 16.299 2.25023 16.6067 2.55802C16.9145 2.8658 17.067 3.23279 17.067 3.66439V13.6644C17.067 14.096 16.9145 14.463 16.6067 14.7708C16.299 15.0785 15.932 15.2311 15.5004 15.2311H2.16703C1.73543 15.2311 1.36845 15.0785 1.06066 14.7708C0.752875 14.463 0.600366 14.096 0.600366 13.6644V3.66439C0.600366 3.23279 0.752875 2.8658 1.06066 2.55802C1.36845 2.25023 1.73543 2.09772 2.16703 2.09772H4.79203ZM2.06703 13.6644V13.7644H2.16703H15.5004H15.6004V13.6644V3.66439V3.56439H15.5004H12.1695L10.6784 1.93032L10.6487 1.89772H10.6045H7.06287H7.01874L6.989 1.93032L5.49791 3.56439H2.16703H2.06703V3.66439V13.6644ZM11.4192 11.2499C10.709 11.9601 9.84915 12.3144 8.8337 12.3144C7.81825 12.3144 6.95836 11.9601 6.24816 11.2499C5.53796 10.5397 5.1837 9.67984 5.1837 8.66439C5.1837 7.64894 5.53796 6.78905 6.24816 6.07885C6.95836 5.36865 7.81825 5.01439 8.8337 5.01439C9.84915 5.01439 10.709 5.36865 11.4192 6.07885C12.1294 6.78905 12.4837 7.64894 12.4837 8.66439C12.4837 9.67984 12.1294 10.5397 11.4192 11.2499ZM7.28382 10.2143C7.70585 10.6363 8.22456 10.8477 8.8337 10.8477C9.44284 10.8477 9.96155 10.6363 10.3836 10.2143C10.8056 9.79223 11.017 9.27353 11.017 8.66439C11.017 8.05525 10.8056 7.53654 10.3836 7.11451C9.96155 6.69248 9.44284 6.48105 8.8337 6.48105C8.22456 6.48105 7.70585 6.69248 7.28382 7.11451C6.86179 7.53654 6.65037 8.05525 6.65037 8.66439C6.65037 9.27353 6.86179 9.79223 7.28382 10.2143Z" stroke="white" stroke-width="0.2"/></svg>` let addwithcircle = `<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M12.7269 7.95376H7.96335V12.7152C7.96335 13.2416 7.53248 13.6663 7.01185 13.6663C6.48522 13.6663 6.06034 13.2357 6.06034 12.7152V7.95376H1.28484C0.75822 7.95376 0.333332 7.52308 0.333332 7.00267C0.333332 6.47627 0.764204 6.05157 1.28484 6.05157H6.04837V1.28411C6.04837 0.757712 6.47924 0.333008 6.99988 0.333008C7.5265 0.333008 7.95139 0.763694 7.95139 1.28411V6.04558H12.7149C13.2415 6.04558 13.6664 6.47627 13.6664 6.99668C13.6784 7.52906 13.2475 7.95376 12.7269 7.95376Z" fill="#006AA8"/></svg>` let checkboxclicked = `<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 18 18"><path d="M15.9982 0H2.00179C0.904036 0 0 0.904036 0 2.00179V15.9982C0 17.104 0.904036 18 2.00179 18H15.9982C17.096 18 18 17.104 18 15.9982V2.00179C18 0.904036 17.104 0 15.9982 0ZM7.70852 13.2861C7.32108 13.6735 6.69148 13.6735 6.29596 13.2861L2.70404 9.69417C2.31659 9.30673 2.31659 8.67713 2.70404 8.28161C3.09148 7.89417 3.72108 7.89417 4.11659 8.28161L6.99821 11.1632L13.8834 4.2861C14.2709 3.89865 14.9004 3.89865 15.296 4.2861C15.6834 4.67354 15.6834 5.30314 15.296 5.69865L7.70852 13.2861Z"/></svg>` let checkboxnotclicked = `<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 18 18"><path d="M14.9973 15.9982H3.00269C2.45381 15.9982 2.00179 15.5462 2.00179 14.9973V3.00269C2.00179 2.45381 2.45381 2.00179 3.00269 2.00179H15.0054C15.5543 2.00179 16.0063 2.45381 16.0063 3.00269V15.0054C15.9982 15.5462 15.5462 15.9982 14.9973 15.9982ZM15.9982 0H2.00179C0.904036 0 0 0.904036 0 2.00179V15.9982C0 17.104 0.904036 18 2.00179 18H15.9982C17.096 18 18 17.104 18 15.9982V2.00179C18 0.904036 17.104 0 15.9982 0Z"/></svg>` let defaultTick = `<svg width="14" height="15" viewBox="0 0 14 15" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M7 0.5C3.13901 0.5 0 3.63901 0 7.5C0 11.361 3.13901 14.5 7 14.5C10.861 14.5 14 11.361 14 7.5C14 3.63901 10.861 0.5 7 0.5ZM5.09776 10.4946L2.57399 7.97713C2.29148 7.69462 2.29148 7.24888 2.57399 6.99776C2.8565 6.71525 3.27085 6.71525 3.55336 6.99776L5.56861 9.013L10.3839 4.19776C10.6664 3.91525 11.087 3.91525 11.3632 4.19776C11.6457 4.48027 11.6457 4.9009 11.3632 5.17713L6.04574 10.4946C5.82601 10.7771 5.37399 10.7771 5.09776 10.4946Z" fill="#8DBD00"/></svg>` let google_pay = `<svg width="752" height="400" viewBox="0 0 752 400" fill="none" xmlns="http://www.w3.org/2000/svg"> <g clip-path="url(#clip0_1_67)"> <path d="M551.379 0H200.022C90.2234 0 0.387924 90 0.387924 200C0.387924 310 90.2234 400 200.022 400H551.379C661.178 400 751.013 310 751.013 200C751.013 90 661.178 0 551.379 0Z" fill="white"/> <path d="M551.379 16.2C576.034 16.2 599.99 21.1 622.548 30.7C644.408 40 663.973 53.3 680.941 70.2C697.811 87.1 711.086 106.8 720.369 128.7C729.952 151.3 734.843 175.3 734.843 200C734.843 224.7 729.952 248.7 720.369 271.3C711.086 293.2 697.811 312.8 680.941 329.8C664.072 346.7 644.408 360 622.548 369.3C599.99 378.9 576.034 383.8 551.379 383.8H200.022C175.367 383.8 151.411 378.9 128.853 369.3C106.993 360 87.4285 346.7 70.4596 329.8C53.5905 312.9 40.3148 293.2 31.0318 271.3C21.4493 248.7 16.5583 224.7 16.5583 200C16.5583 175.3 21.4493 151.3 31.0318 128.7C40.3148 106.8 53.5905 87.2 70.4596 70.2C87.3287 53.3 106.993 40 128.853 30.7C151.411 21.1 175.367 16.2 200.022 16.2H551.379ZM551.379 0H200.022C90.2234 0 0.387924 90 0.387924 200C0.387924 310 90.2234 400 200.022 400H551.379C661.178 400 751.013 310 751.013 200C751.013 90 661.178 0 551.379 0Z" fill="#3C4043"/> <path d="M358.332 214.2V274.7H339.167V125.3H389.974C402.851 125.3 413.831 129.6 422.814 138.2C431.997 146.8 436.589 157.3 436.589 169.7C436.589 182.4 431.997 192.9 422.814 201.4C413.931 209.9 402.951 214.1 389.974 214.1H358.332V214.2ZM358.332 143.7V195.8H390.374C397.96 195.8 404.348 193.2 409.339 188.1C414.43 183 417.025 176.8 417.025 169.8C417.025 162.9 414.43 156.8 409.339 151.7C404.348 146.4 398.06 143.8 390.374 143.8H358.332V143.7Z" fill="#3C4043"/> <path d="M486.697 169.1C500.871 169.1 512.051 172.9 520.236 180.5C528.421 188.1 532.513 198.5 532.513 211.7V274.7H514.247V260.5H513.448C505.563 272.2 494.982 278 481.806 278C470.527 278 461.144 274.7 453.558 268C445.972 261.3 442.179 253 442.179 243C442.179 232.4 446.171 224 454.157 217.8C462.142 211.5 472.823 208.4 486.098 208.4C497.477 208.4 506.86 210.5 514.147 214.7V210.3C514.147 203.6 511.552 198 506.261 193.3C500.971 188.6 494.782 186.3 487.695 186.3C477.015 186.3 468.531 190.8 462.342 199.9L445.473 189.3C454.756 175.8 468.531 169.1 486.697 169.1ZM461.943 243.3C461.943 248.3 464.039 252.5 468.331 255.8C472.523 259.1 477.514 260.8 483.204 260.8C491.289 260.8 498.476 257.8 504.764 251.8C511.053 245.8 514.247 238.8 514.247 230.7C508.258 226 499.973 223.6 489.292 223.6C481.507 223.6 475.019 225.5 469.828 229.2C464.538 233.1 461.943 237.8 461.943 243.3Z" fill="#3C4043"/> <path d="M636.723 172.4L572.84 319.6H553.076L576.832 268.1L534.709 172.4H555.571L585.916 245.8H586.315L615.861 172.4H636.723Z" fill="#3C4043"/> <path d="M282.102 202C282.102 195.74 281.543 189.75 280.505 183.99H200.172V216.99L246.437 217C244.561 227.98 238.522 237.34 229.269 243.58V264.99H256.808C272.889 250.08 282.102 228.04 282.102 202Z" fill="#4285F4"/> <path d="M229.279 243.58C221.613 248.76 211.741 251.79 200.192 251.79C177.883 251.79 158.957 236.73 152.18 216.43H123.772V238.51C137.846 266.49 166.773 285.69 200.192 285.69C223.29 285.69 242.694 278.08 256.818 264.98L229.279 243.58Z" fill="#34A853"/> <path d="M149.505 200.05C149.505 194.35 150.453 188.84 152.18 183.66V161.58H123.772C117.953 173.15 114.679 186.21 114.679 200.05C114.679 213.89 117.963 226.95 123.772 238.52L152.18 216.44C150.453 211.26 149.505 205.75 149.505 200.05Z" fill="#FABB05"/> <path d="M200.192 148.3C212.799 148.3 224.088 152.65 233.002 161.15L257.407 136.72C242.584 122.89 223.26 114.4 200.192 114.4C166.783 114.4 137.846 133.6 123.772 161.58L152.18 183.66C158.957 163.36 177.883 148.3 200.192 148.3Z" fill="#E94235"/> </g> <defs> <clipPath id="clip0_1_67"> <rect width="752" height="400" fill="white"/> </clipPath> </defs> </svg>` let applePayList = `<svg id="apple_pay_saved" viewBox="0 0 32 22" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M29.1343 0.783203H2.86575C2.75634 0.783203 2.64674 0.783203 2.53754 0.783839C2.44522 0.784495 2.35312 0.785517 2.26101 0.788024C2.06015 0.793443 1.85756 0.805263 1.6592 0.840822C1.45768 0.876998 1.27015 0.936005 1.0872 1.02891C0.907346 1.12014 0.742688 1.23947 0.599993 1.38186C0.457237 1.52425 0.337606 1.68821 0.246161 1.8678C0.152996 2.05028 0.0937985 2.23739 0.0577814 2.43855C0.0219401 2.63646 0.0100098 2.83849 0.00459659 3.03863C0.00212198 3.1305 0.0010606 3.22237 0.000459349 3.31421C-0.000178636 3.42338 3.40259e-05 3.53246 3.40259e-05 3.64182V18.3585C3.40259e-05 18.4679 -0.000178636 18.5768 0.000459349 18.6862C0.0010606 18.778 0.00212198 18.8699 0.00459659 18.9617C0.0100098 19.1617 0.0219401 19.3637 0.0577814 19.5616C0.0937985 19.7628 0.152996 19.9499 0.246161 20.1324C0.337606 20.3119 0.457237 20.4761 0.599993 20.6183C0.742688 20.7609 0.907346 20.8802 1.0872 20.9712C1.27015 21.0644 1.45768 21.1234 1.6592 21.1596C1.85756 21.1949 2.06015 21.2069 2.26101 21.2123C2.35312 21.2144 2.44522 21.2157 2.53754 21.2161C2.64674 21.2169 2.75634 21.2169 2.86575 21.2169H29.1343C29.2435 21.2169 29.3531 21.2169 29.4623 21.2161C29.5544 21.2157 29.6465 21.2144 29.739 21.2123C29.9395 21.2069 30.142 21.1949 30.3409 21.1596C30.5421 21.1234 30.7297 21.0644 30.9126 20.9712C31.0927 20.8802 31.2569 20.7609 31.3999 20.6183C31.5424 20.4761 31.662 20.3119 31.7537 20.1324C31.8471 19.9499 31.9062 19.7628 31.942 19.5616C31.9779 19.3637 31.9895 19.1617 31.995 18.9617C31.9975 18.8699 31.9987 18.778 31.9991 18.6862C32 18.5768 32 18.4679 32 18.3585V3.64182C32 3.53246 32 3.42338 31.9991 3.31421C31.9987 3.22237 31.9975 3.1305 31.995 3.03863C31.9895 2.83849 31.9779 2.63646 31.942 2.43855C31.9062 2.23739 31.8471 2.05028 31.7537 1.8678C31.662 1.68821 31.5424 1.52425 31.3999 1.38186C31.2569 1.23947 31.0927 1.12014 30.9126 1.02891C30.7297 0.936005 30.5421 0.876998 30.3409 0.840822C30.142 0.805263 29.9395 0.793443 29.739 0.788024C29.6465 0.785517 29.5544 0.784495 29.4623 0.783839C29.3531 0.783203 29.2435 0.783203 29.1343 0.783203Z" fill="black"/><path d="M29.1343 1.46387L29.4574 1.46448C29.545 1.4651 29.6325 1.46605 29.7205 1.46844C29.8737 1.47256 30.0528 1.48084 30.2197 1.51069C30.3649 1.53676 30.4866 1.57641 30.6034 1.63572C30.7187 1.69417 30.8244 1.77076 30.9166 1.86265C31.0092 1.95515 31.0861 2.06071 31.1455 2.17701C31.2046 2.29261 31.2441 2.41344 31.2701 2.55926C31.3 2.72398 31.3082 2.90313 31.3124 3.0568C31.3148 3.14353 31.3159 3.23027 31.3164 3.31907C31.3172 3.42646 31.3172 3.53379 31.3172 3.64139V18.3581C31.3172 18.4657 31.3172 18.5728 31.3163 18.6825C31.3159 18.7692 31.3148 18.856 31.3124 18.9429C31.3082 19.0963 31.3 19.2754 31.2697 19.442C31.2441 19.5858 31.2047 19.7067 31.1452 19.8229C31.086 19.9389 31.0092 20.0443 30.917 20.1362C30.8242 20.2288 30.7189 20.3052 30.6022 20.3642C30.4863 20.4232 30.3648 20.4628 30.2211 20.4886C30.0508 20.5189 29.8641 20.5272 29.7236 20.531C29.6352 20.533 29.5471 20.5342 29.457 20.5346C29.3496 20.5354 29.2417 20.5354 29.1343 20.5354H2.86576C2.86433 20.5354 2.86293 20.5354 2.86148 20.5354C2.75527 20.5354 2.64884 20.5354 2.54069 20.5346C2.45252 20.5342 2.36453 20.533 2.27947 20.5311C2.13571 20.5272 1.94897 20.5189 1.78002 20.4888C1.63509 20.4628 1.51358 20.4232 1.39611 20.3634C1.28052 20.3049 1.17529 20.2286 1.08247 20.1359C0.99037 20.0442 0.913831 19.9391 0.854653 19.8229C0.795417 19.7068 0.755785 19.5856 0.729726 19.4401C0.699604 19.2737 0.691329 19.0954 0.687194 18.943C0.684833 18.8558 0.683847 18.7685 0.683287 18.6818L0.682861 18.4257L0.682881 18.3581V3.64139L0.682861 3.57379L0.683267 3.31826C0.683847 3.231 0.684833 3.14376 0.687194 3.05658C0.691329 2.90403 0.699604 2.72562 0.729976 2.55789C0.755804 2.41367 0.795417 2.29246 0.854963 2.17581C0.913677 2.06052 0.990351 1.95527 1.08294 1.86294C1.17516 1.77092 1.28073 1.69442 1.39706 1.63541C1.51327 1.57639 1.63501 1.53676 1.77994 1.51075C1.94694 1.48082 2.12618 1.47256 2.27968 1.46842C2.36718 1.46605 2.45468 1.4651 2.54153 1.4645L2.86576 1.46387H29.1343Z" fill="white"/><path d="M8.73583 7.65557C9.00982 7.31374 9.19575 6.85476 9.14672 6.38574C8.74563 6.40564 8.25618 6.64968 7.97281 6.99178C7.71838 7.28473 7.49318 7.76292 7.55189 8.21228C8.00213 8.25124 8.45196 7.98781 8.73583 7.65557Z" fill="black"/><path d="M9.14155 8.30045C8.4877 8.26161 7.93176 8.6706 7.6195 8.6706C7.30708 8.6706 6.82892 8.32003 6.31175 8.32948C5.63863 8.33934 5.01404 8.71896 4.67246 9.32273C3.96988 10.5306 4.48705 12.3222 5.17027 13.3059C5.50206 13.7926 5.90192 14.3285 6.4288 14.3092C6.92661 14.2897 7.12173 13.9877 7.72684 13.9877C8.3315 13.9877 8.50726 14.3092 9.03423 14.2995C9.5807 14.2897 9.92234 13.8126 10.2541 13.3254C10.6347 12.7706 10.7906 12.2349 10.8004 12.2055C10.7906 12.1958 9.74661 11.7963 9.73693 10.5985C9.72707 9.5956 10.5565 9.11854 10.5956 9.08896C10.1272 8.39795 9.39529 8.32003 9.14155 8.30045Z" fill="black"/><path d="M14.8348 6.94238C16.256 6.94238 17.2456 7.91949 17.2456 9.34209C17.2456 10.7698 16.2356 11.752 14.7992 11.752H13.2257V14.2478H12.0889V6.94238H14.8348V6.94238ZM13.2257 10.8001H14.5302C15.52 10.8001 16.0833 10.2686 16.0833 9.34717C16.0833 8.42582 15.52 7.89928 14.5353 7.89928H13.2257V10.8001Z" fill="black"/><path d="M17.5426 12.7346C17.5426 11.803 18.2583 11.231 19.5273 11.1601L20.989 11.074V10.664C20.989 10.0716 20.588 9.71725 19.9181 9.71725C19.2835 9.71725 18.8876 10.0209 18.7913 10.4969H17.7558C17.8167 9.53493 18.6389 8.82617 19.9586 8.82617C21.2529 8.82617 22.0802 9.50964 22.0802 10.5779V14.2483H21.0295V13.3725H21.0042C20.6947 13.9648 20.0195 14.3394 19.3191 14.3394C18.2735 14.3394 17.5426 13.6914 17.5426 12.7346ZM20.989 12.2537V11.8335L19.6743 11.9144C19.0196 11.96 18.6491 12.2486 18.6491 12.7042C18.6491 13.1699 19.0348 13.4737 19.6236 13.4737C20.39 13.4737 20.989 12.9472 20.989 12.2537Z" fill="black"/><path d="M23.0722 16.2071V15.3211C23.1533 15.3413 23.336 15.3413 23.4274 15.3413C23.9349 15.3413 24.209 15.1287 24.3765 14.582C24.3765 14.5718 24.473 14.258 24.473 14.2529L22.5443 8.92188H23.7319L25.0821 13.2556H25.1023L26.4526 8.92188H27.6098L25.6098 14.5262C25.1532 15.8173 24.6253 16.2324 23.5188 16.2324C23.4274 16.2324 23.1533 16.2223 23.0722 16.2071Z" fill="black"/></svg>` let samsungPay = `<svg xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns="http://www.w3.org/2000/svg" xmlns:svg="http://www.w3.org/2000/svg" version="1.1" id="svg2" width="500.00534" height="141.69067" viewBox="0 0 500.00534 141.69067" sodipodi:docname="Samsung Pay_button_basic_pos_RGB.ai"> <defs id="defs6"> <clipPath clipPathUnits="userSpaceOnUse" id="clipPath16"> <path d="M 0,106.268 H 369.504 V 0 H 0 Z" id="path14"/> </clipPath> </defs> <sodipodi:namedview id="namedview4" pagecolor="#ffffff" bordercolor="#000000" borderopacity="0.25" inkscape:showpageshadow="2" inkscape:pageopacity="0.0" inkscape:pagecheckerboard="0" inkscape:deskcolor="#d1d1d1"/> <g id="g8" inkscape:groupmode="layer" inkscape:label="Samsung Pay_button_basic_pos_RGB" transform="matrix(1.3333333,0,0,-1.3333333,0,141.69067)"> <g id="g10"> <g id="g12" clip-path="url(#clipPath16)"> <g id="g18" transform="translate(9.0629,23.2361)"> <path d="m0 0v59.795c0 7.828 6.346 14.174 14.173 14.174h330.032c7.828 0 14.173-6.346 14.173-14.174V0c0-7.828-6.345-14.173-14.173-14.173H14.173C6.346-14.173 0-7.828 0 0" style="fill: #00000000;fill-opacity:1;fill-rule:nonzero;stroke:none" id="path20"/> </g> <g id="g22" transform="translate(250.1372,61.3994)"> <path d="m 0,0 v -9.745 h 3.768 c 2.898,0 4.926,2.174 4.926,4.891 C 8.694,-2.138 6.666,0 3.768,0 Z M -4.926,4.564 H 4.13 c 5.47,0 9.527,-4.202 9.527,-9.418 0,-5.253 -4.057,-9.455 -9.563,-9.455 H 0 v -7.571 h -4.926 z" style="fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:none" id="path24"/> </g> <g id="g26" transform="translate(282.6645,50.1699)"> <path d="m 0,0 c 0,3.622 -2.681,6.521 -6.339,6.521 -3.623,0 -6.412,-2.863 -6.412,-6.521 0,-3.695 2.789,-6.594 6.412,-6.594 C -2.681,-6.594 0,-3.659 0,0 m -17.568,-0.073 c 0,7.028 5.143,11.049 10.505,11.049 2.789,0 5.251,-1.123 6.809,-2.97 v 2.535 H 4.637 V -10.65 h -4.891 v 2.753 c -1.558,-1.993 -4.093,-3.188 -6.882,-3.188 -5.108,0 -10.432,4.057 -10.432,11.012" style="fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:none" id="path28"/> </g> <g id="g30" transform="translate(297.9477,40.5703)"> <path d="m 0,0 -8.693,20.141 h 5.215 L 2.428,5.868 8.006,20.141 h 5.143 L 0.508,-10.831 h -4.963 z" style="fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:none" id="path32"/> </g> <g id="g34" transform="translate(196.9545,66.9512)"> <path d="M 0,0 0.372,-21.534 H 0.221 L -6.083,0 h -10.183 v -27.15 h 6.747 l -0.379,22.277 h 0.151 l 6.772,-22.277 h 9.769 l 0,27.15 z" style="fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:none" id="path36"/> </g> <g id="g38" transform="translate(67.8142,66.9512)"> <path d="m 0,0 -5.086,-27.432 h 7.415 l 3.752,24.89 0.154,0.003 3.656,-24.893 h 7.37 L 12.205,0 Z" style="fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:none" id="path40"/> </g> <g id="g42" transform="translate(109.2656,66.9512)"> <path d="M 0,0 -3.384,-20.977 H -3.539 L -6.918,0 h -11.19 l -0.605,-27.432 h 6.867 l 0.171,24.66 h 0.152 l 4.582,-24.66 H 0.02 l 4.585,24.658 0.151,0.002 0.172,-24.66 H 11.79 L 11.185,0 Z" style="fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:none" id="path44"/> </g> <g id="g46" transform="translate(51.1826,47.2572)"> <path d="m 0,0 c 0.269,-0.664 0.183,-1.515 0.054,-2.029 -0.223,-0.914 -0.844,-1.847 -2.672,-1.847 -1.716,0 -2.757,0.994 -2.757,2.488 l -0.006,2.659 h -7.357 l -0.002,-2.115 c 0,-6.12 4.815,-7.968 9.97,-7.968 4.964,0 9.045,1.693 9.697,6.272 0.335,2.368 0.088,3.919 -0.029,4.497 -1.158,5.745 -11.566,7.458 -12.343,10.67 -0.13,0.557 -0.099,1.135 -0.029,1.442 0.194,0.881 0.79,1.842 2.506,1.842 1.607,0 2.548,-0.991 2.548,-2.485 v -1.7 h 6.846 v 1.932 c 0,5.975 -5.367,6.91 -9.25,6.91 -4.876,0 -8.864,-1.616 -9.591,-6.09 -0.199,-1.224 -0.226,-2.318 0.063,-3.7 C -11.162,5.171 -1.413,3.55 0,0" style="fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:none" id="path48"/> </g> <g id="g50" transform="translate(140.3747,47.3093)"> <path d="m 0,0 c 0.262,-0.659 0.181,-1.497 0.052,-2.009 -0.221,-0.903 -0.835,-1.824 -2.646,-1.824 -1.699,0 -2.731,0.98 -2.731,2.463 l -0.004,2.63 h -7.285 l -0.002,-2.095 c 0,-6.059 4.77,-7.887 9.874,-7.887 4.914,0 8.954,1.675 9.6,6.21 0.329,2.343 0.088,3.878 -0.03,4.453 C 5.679,7.63 -4.625,9.325 -5.39,12.505 c -0.134,0.549 -0.1,1.12 -0.034,1.424 0.194,0.872 0.785,1.824 2.481,1.824 1.595,0 2.525,-0.977 2.525,-2.46 v -1.68 h 6.779 v 1.91 c 0,5.916 -5.316,6.84 -9.16,6.84 -4.824,0 -8.774,-1.596 -9.492,-6.027 -0.198,-1.212 -0.225,-2.296 0.063,-3.662 C -11.054,5.119 -1.399,3.517 0,0" style="fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:none" id="path52"/> </g> <g id="g54" transform="translate(163.4048,43.6249)"> <path d="M 0,0 C 1.907,0 2.494,1.314 2.63,1.989 2.688,2.284 2.697,2.684 2.695,3.036 V 23.331 H 9.638 V 3.661 C 9.647,3.156 9.596,2.124 9.568,1.856 9.09,-3.264 5.043,-4.923 0,-4.923 c -5.045,0 -9.092,1.659 -9.573,6.779 -0.025,0.268 -0.077,1.3 -0.063,1.805 v 19.67 h 6.938 V 3.036 C -2.704,2.684 -2.691,2.284 -2.632,1.989 -2.499,1.314 -1.91,0 0,0" style="fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:none" id="path56"/> </g> <g id="g58" transform="translate(220.6237,43.9102)"> <path d="M 0,0 C 1.986,0 2.679,1.257 2.804,1.991 2.86,2.3 2.874,2.684 2.869,3.032 V 7.016 H 0.056 v 3.999 H 9.774 V 3.661 C 9.769,3.144 9.758,2.767 9.675,1.856 9.221,-3.142 4.889,-4.925 0.027,-4.925 c -4.864,0 -9.191,1.783 -9.65,6.781 -0.079,0.911 -0.092,1.288 -0.094,1.805 l 0.002,11.542 c 0,0.487 0.058,1.347 0.115,1.805 0.612,5.129 4.763,6.779 9.629,6.779 4.865,0 9.124,-1.634 9.63,-6.779 0.088,-0.873 0.058,-1.805 0.063,-1.805 V 14.288 H 2.804 v 1.538 c 0.002,-0.003 -0.005,0.65 -0.086,1.045 -0.124,0.605 -0.646,1.991 -2.743,1.991 -1.995,0 -2.582,-1.314 -2.733,-1.991 C -2.837,16.51 -2.869,16.02 -2.869,15.573 V 3.031 C -2.871,2.684 -2.858,2.3 -2.806,1.991 -2.677,1.257 -1.984,0 0,0" style="fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:none" id="path60"/> </g> <g id="g60" transform="translate(318.9477,40.5703)"> <path d="m19.888 13.312-11.872 11.872q-.304.304-.72.304t-.72-.304l-1.776-1.584q-.304-.304-.304-.72t.304-.72l9.28-9.28-9.28-9.6q-.304-.304-.304-.72t.304-.72L6.576 0q.304-.304.72-.304t.72.304l11.872 11.872q.304.304.304.72t-.304.72z" style="fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:none" id="path32"/> </g></g> </g> </g> </svg>` let becsDebit = `<svg xmlns="http://www.w3.org/2000/svg" width="124" height="124" viewBox="0 0 20 21" fill="none"><path d="M9.99966 6.71422C10.3406 6.71422 10.6677 6.57876 10.9088 6.33765C11.1499 6.09653 11.2854 5.7695 11.2854 5.42851C11.2854 5.08751 11.1499 4.76049 10.9088 4.51937C10.6677 4.27825 10.3406 4.14279 9.99966 4.14279C9.65866 4.14279 9.33164 4.27825 9.09052 4.51937C8.8494 4.76049 8.71394 5.08751 8.71394 5.42851C8.71394 5.7695 8.8494 6.09653 9.09052 6.33765C9.33164 6.57876 9.65866 6.71422 9.99966 6.71422ZM10.7625 0.967079C10.5415 0.804186 10.2742 0.716309 9.99966 0.716309C9.72512 0.716309 9.45779 0.804186 9.2368 0.967079L1.09394 6.97136C0.0962268 7.70765 0.616513 9.29165 1.8568 9.29165H2.28537V15.4991C1.77757 15.7107 1.34379 16.0679 1.03871 16.5256C0.733627 16.9834 0.570915 17.5212 0.571084 18.0714V19.3571C0.571084 19.7119 0.859084 19.9999 1.21394 19.9999H18.7854C18.9559 19.9999 19.1194 19.9322 19.2399 19.8116C19.3605 19.6911 19.4282 19.5276 19.4282 19.3571V18.0714C19.4282 17.5214 19.2654 16.9837 18.9604 16.5261C18.6553 16.0685 18.2216 15.7115 17.7139 15.4999V9.29165H18.1417C19.3828 9.29165 19.9031 7.70765 18.9045 6.97136L10.7625 0.967079ZM3.57108 15.2857V9.29165H5.71394V15.2857H3.57108ZM16.4282 9.29165V15.2857H14.2854V9.29165H16.4282ZM12.9997 9.29165V15.2857H10.6425V9.29165H12.9997ZM9.3568 9.29165V15.2857H6.99966V9.29165H9.3568ZM1.8568 8.00594L9.99966 2.00165L18.1417 8.00594H1.8568ZM1.8568 18.0714C1.8568 17.2434 2.5288 16.5714 3.3568 16.5714H16.6425C17.4705 16.5714 18.1425 17.2434 18.1425 18.0714V18.7142H1.8568V18.0714Z" fill="black"/></svg>` let cartesBancaires = `<svg class="PaymentLogo PaymentElementAccordionGraphicFormCardField__logo" width="34" height="24" viewBox="0 0 34 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M30 0H4C1.79086 0 0 1.79086 0 4v16c0 2.2091 1.79086 4 4 4h26c2.2091 0 4-1.7909 4-4V4c0-2.20914-1.7909-4-4-4Z" fill="url(#a-payment-logo-CartesBancaires-)"></path><path fill-rule="evenodd" clip-rule="evenodd" d="M10.817 6c4.0605 0 6.6394 2.21163 6.8078 5.6391h-6.5936v.7076h6.5946C17.4651 15.7736 14.9082 18 10.817 18 6.7321 18 4 15.7475 4 12c0-3.63257 2.6275-6 6.817-6Zm15.8831 6.3467c.6194 0 1.1092.0549 1.469.1647.3598.11.69.3034.9906.5803.2733.2505.4806.5384.6218.8635.1458.3429.2185.6923.2185 1.0483 0 .3561-.0727.7054-.2185 1.0483-.1412.3252-.3485.6131-.6218.8637-.3006.2768-.6308.4701-.9906.5801-.3598.1098-.8496.1648-1.469.1648h-8.325v-5.3137h8.325Zm0-6.00714c.6194 0 1.1092.05476 1.469.16429.3598.10958.69.30253.9906.57871.2733.24979.4806.53695.6218.86126.1458.34193.2185.69055.2185 1.04548 0 .3551-.0727.70355-.2185 1.0455-.1412.3244-.3485.6114-.6218.8613-.3006.2762-.6308.4691-.9906.5786-.3598.1096-.8496.1644-1.469.1644h-8.325V6.33956h8.325Z" fill="#FFFFFE"></path><defs><linearGradient id="a-payment-logo-CartesBancaires-" x1="4.9e-7" y1="17.9792" x2="28.3269" y2="-2.01619" gradientUnits="userSpaceOnUse"><stop stop-color="#00A26C"></stop><stop offset=".486821" stop-color="#007DB5"></stop><stop offset="1" stop-color="#003877"></stop></linearGradient></defs></svg>` type uri = { uri: string, local: bool, } open ReactNative open Style @react.component let make = ( ~name, ~width=20., ~height=16., ~fill="#ffffff", ~defaultView: option<React.element>=?, ~style=viewStyle(), ~fallbackIcon: option<string>=?, ) => { defaultView->ignore let (isLoaded, setIsLoaded) = React.useState(_ => false) let (iconName, setIconName) = React.useState(_ => name->String.replaceRegExp(%re("/ /g"), "")->String.toLowerCase ) React.useEffect1(() => { setIconName(_ => name->String.replaceRegExp(%re("/ /g"), "")->String.toLowerCase) None }, [name]) let getAssetUrl = GlobalHooks.useGetAssetUrlWithVersion() let uri = React.useMemo1(() => { let assetUrl = `${getAssetUrl()}/images/error.svg` let localName = switch iconName { | "card" => card | "cardv1" => cardv1 | "close" => close | "cvvempty" => cvvempty | "cvvfilled" => cvvfilled | "error" => error | "lock" => lock | "waitcard" => waitcard | "camera" => camera | "addwithcircle" => addwithcircle | "checkboxclicked" => checkboxclicked | "checkboxnotclicked" => checkboxnotclicked | "defaulttick" => defaultTick | "googlepay" => google_pay | "applepay" => applePayList | "samsung_pay" => samsungPay | "becsdebit" => becsDebit | "cartesbancaires" => cartesBancaires | _ => "" } localName == "" ? { uri: assetUrl->String.replace("error", iconName), local: false, } : {uri: localName, local: true} }, [iconName]) <View style={array([viewStyle(~height=height->dp, ~width=width->dp, ()), style])}> {uri.local ? <ReactNativeSvg.SvgCss onError={() => { setIsLoaded(_ => true) setIconName(_ => fallbackIcon->Option.getOr("error")) }} onLoad={() => { setIsLoaded(_ => true) }} xml=uri.uri width height fill /> : <ReactNativeSvg.SvgUri onError={() => { setIsLoaded(_ => true) setIconName(_ => fallbackIcon->Option.getOr("error")) }} onLoad={() => { setIsLoaded(_ => true) }} uri=uri.uri width height fill />} {isLoaded || uri.local ? React.null : <ActivityIndicator style={viewStyle(~height=height->dp, ~width=width->dp, ())} color=fill />} </View> }
29,456
10,645
hyperswitch-client-core
src/headless/Headless.res
.res
open SdkTypes open HeadlessUtils open HeadlessNative let reRegisterCallback = ref(() => ()) let registerHeadless = headless => { let headlessModule = initialise(headless) let getDefaultPaymentSession = error => { headlessModule.getPaymentSession( error->Utils.getJsonObjectFromRecord, error->Utils.getJsonObjectFromRecord, []->Utils.getJsonObjectFromRecord, _response => { headlessModule.exitHeadless(error->HyperModule.stringifiedResStatus) }, ) } let confirmCall = (body, nativeProp) => confirmAPICall(nativeProp, body) ->Promise.then(res => { let confirmRes = res ->Option.getOr(JSON.Encode.null) ->Utils.getDictFromJson ->PaymentConfirmTypes.itemToObjMapper headlessModule.exitHeadless(confirmRes.error->HyperModule.stringifiedResStatus) Promise.resolve() }) ->ignore let confirmGPay = ( var, statesJson: option<CountryStateDataHookTypes.states>, data, nativeProp, ) => { let paymentData = var->PaymentConfirmTypes.itemToObjMapperJava switch paymentData.error { | "" => let json = paymentData.paymentMethodData->JSON.parseExn let obj = json ->Utils.getDictFromJson ->GooglePayTypeNew.itemToObjMapper(statesJson->Option.getOr(Dict.make())) let payment_method_data = [ ( "wallet", [ ( data.payment_method_type->Option.getOr(""), obj.paymentMethodData->Utils.getJsonObjectFromRecord, ), ] ->Dict.fromArray ->JSON.Encode.object, ), ( "billing", switch obj.paymentMethodData.info { | Some(info) => switch info.billing_address { | Some(address) => address->Utils.getJsonObjectFromRecord | None => JSON.Encode.null } | None => JSON.Encode.null }, ), ] ->Dict.fromArray ->JSON.Encode.object [ ("client_secret", nativeProp.clientSecret->JSON.Encode.string), ("payment_method", "wallet"->JSON.Encode.string), ("payment_method_type", data.payment_method_type->Option.getOr("")->JSON.Encode.string), ("payment_method_data", payment_method_data), ("setup_future_usage", "off_session"->JSON.Encode.string), ("payment_type", "new_mandate"->JSON.Encode.string), ( "customer_acceptance", [ ("acceptance_type", "online"->JSON.Encode.string), ("accepted_at", Date.now()->Date.fromTime->Date.toISOString->JSON.Encode.string), ( "online", [ ( "user_agent", nativeProp.hyperParams.userAgent->Option.getOr("")->JSON.Encode.string, ), ] ->Dict.fromArray ->JSON.Encode.object, ), ] ->Dict.fromArray ->JSON.Encode.object, ), ] ->Dict.fromArray ->JSON.Encode.object ->JSON.stringify ->confirmCall(nativeProp) | "Cancel" => reRegisterCallback.contents() // headlessModule.exitHeadless( // PaymentConfirmTypes.defaultCancelError->HyperModule.stringifiedResStatus, // ) | err => headlessModule.exitHeadless( {message: err, status: "failed"}->HyperModule.stringifiedResStatus, ) } } let confirmApplePay = (var, statesJson, data, nativeProp) => { switch var ->Dict.get("status") ->Option.getOr(JSON.Encode.null) ->JSON.Decode.string ->Option.getOr("") { | "Cancelled" => reRegisterCallback.contents() // headlessModule.exitHeadless( // PaymentConfirmTypes.defaultCancelError->HyperModule.stringifiedResStatus, // ) | "Failed" => headlessModule.exitHeadless( {message: "failed", status: "failed"}->HyperModule.stringifiedResStatus, ) | "Error" => headlessModule.exitHeadless( {message: "failed", status: "failed"}->HyperModule.stringifiedResStatus, ) | _ => let payment_data = var->Dict.get("payment_data")->Option.getOr(JSON.Encode.null) let payment_method = var->Dict.get("payment_method")->Option.getOr(JSON.Encode.null) let transaction_identifier = var->Dict.get("transaction_identifier")->Option.getOr(JSON.Encode.null) if ( transaction_identifier->Utils.getStringFromJson( "Simulated Identifier", ) == "Simulated Identifier" ) { headlessModule.exitHeadless( {message: "Simulated Identifier", status: "failed"}->HyperModule.stringifiedResStatus, ) } else { let paymentData = [ ("payment_data", payment_data), ("payment_method", payment_method), ("transaction_identifier", transaction_identifier), ] ->Dict.fromArray ->JSON.Encode.object let payment_method_data = [ ( "wallet", [(data.payment_method_type->Option.getOr(""), paymentData)] ->Dict.fromArray ->JSON.Encode.object, ), ( "billing", switch var->GooglePayTypeNew.getBillingContact( "billing_contact", statesJson->Option.getOr(Dict.make()), ) { | Some(billing) => billing->Utils.getJsonObjectFromRecord | None => JSON.Encode.null }, ), ] ->Dict.fromArray ->JSON.Encode.object [ ("client_secret", nativeProp.clientSecret->JSON.Encode.string), ("payment_method", "wallet"->JSON.Encode.string), ("payment_method_type", data.payment_method_type->Option.getOr("")->JSON.Encode.string), ("payment_method_data", payment_method_data), ("setup_future_usage", "off_session"->JSON.Encode.string), ("payment_type", "new_mandate"->JSON.Encode.string), ( "customer_acceptance", [ ("acceptance_type", "online"->JSON.Encode.string), ("accepted_at", Date.now()->Date.fromTime->Date.toISOString->JSON.Encode.string), ( "online", [ ( "user_agent", nativeProp.hyperParams.userAgent->Option.getOr("")->JSON.Encode.string, ), ] ->Dict.fromArray ->JSON.Encode.object, ), ] ->Dict.fromArray ->JSON.Encode.object, ), ] ->Dict.fromArray ->JSON.Encode.object ->JSON.stringify ->confirmCall(nativeProp) } } } let processRequest = ( nativeProp, data, response, sessions: option<array<SessionsType.sessions>>, ) => { switch data { | SAVEDLISTCARD(data) => let body = [ ("client_secret", nativeProp.clientSecret->JSON.Encode.string), ("payment_method", "card"->JSON.Encode.string), ("payment_token", data.payment_token->Option.getOr("")->JSON.Encode.string), ( "card_cvc", switch response->Utils.getDictFromJson->Dict.get("cvc") { | Some(cvc) => cvc | None => JSON.Encode.null }, ), ] ->Dict.fromArray ->JSON.Encode.object confirmCall(body->JSON.stringify, nativeProp) | SAVEDLISTWALLET(data) => let session = switch sessions { | Some(sessionData) => sessionData ->Array.find(item => item.wallet_name == data.walletType->Option.getOr("")->walletNameToTypeMapper ) ->Option.getOr(SessionsType.defaultToken) | None => SessionsType.defaultToken } switch data.walletType->Option.getOr("")->walletNameToTypeMapper { | GOOGLE_PAY => HyperModule.launchGPay( GooglePayTypeNew.getGpayTokenStringified( ~obj=session, ~appEnv=nativeProp.env, ~requiredFields=[], ), //walletType.required_field, var => { RequiredFieldsTypes.importStatesAndCountries( "./../utility/reusableCodeFromWeb/StatesAndCountry.json", ) ->Promise.then(res => { let states = res->S3ApiHook.decodeJsonTocountryStateData confirmGPay(var, Some(states.states), data, nativeProp) Promise.resolve() }) ->Promise.catch(_ => { confirmGPay(var, None, data, nativeProp) Promise.resolve() }) ->ignore }, ) | APPLE_PAY => let timerId = setTimeout(() => { logWrapper( ~logType=DEBUG, ~eventName=APPLE_PAY_PRESENT_FAIL_FROM_NATIVE, ~url="", ~customLogUrl=nativeProp.customLogUrl, ~env=nativeProp.env, ~category=API, ~statusCode="", ~apiLogType=None, ~data=JSON.Encode.null, ~publishableKey=nativeProp.publishableKey, ~paymentId="", ~paymentMethod=None, ~paymentExperience=None, ~timestamp=0., ~latency=0., ~version=nativeProp.hyperParams.sdkVersion, (), ) headlessModule.exitHeadless(getDefaultError->HyperModule.stringifiedResStatus) }, 5000) HyperModule.launchApplePay( [ ("session_token_data", session.session_token_data), ("payment_request_data", session.payment_request_data), ] ->Dict.fromArray ->JSON.Encode.object ->JSON.stringify, var => { RequiredFieldsTypes.importStatesAndCountries( "./../utility/reusableCodeFromWeb/StatesAndCountry.json", ) ->Promise.then(res => { let states = res->S3ApiHook.decodeJsonTocountryStateData confirmApplePay(var, Some(states.states), data, nativeProp) Promise.resolve() }) ->Promise.catch(_ => { confirmApplePay(var, None, data, nativeProp) Promise.resolve() }) ->ignore }, _ => { logWrapper( ~logType=DEBUG, ~eventName=APPLE_PAY_BRIDGE_SUCCESS, ~url="", ~customLogUrl=nativeProp.customLogUrl, ~env=nativeProp.env, ~category=API, ~statusCode="", ~apiLogType=None, ~data=JSON.Encode.null, ~publishableKey=nativeProp.publishableKey, ~paymentId="", ~paymentMethod=None, ~paymentExperience=None, ~timestamp=0., ~latency=0., ~version=nativeProp.hyperParams.sdkVersion, (), ) }, _ => { clearTimeout(timerId) }, ) | _ => () } | NONE => headlessModule.exitHeadless(getDefaultError->HyperModule.stringifiedResStatus) } } let getPaymentSession = (nativeProp, spmData, sessions: option<array<SessionsType.sessions>>) => { if spmData->Array.length > 0 { let defaultSpmData = switch spmData ->Array.find(x => switch x { | SAVEDLISTCARD(savedCard) => savedCard.isDefaultPaymentMethod->Option.getOr(false) | SAVEDLISTWALLET(savedWallet) => savedWallet.isDefaultPaymentMethod->Option.getOr(false) | NONE => false } ) ->Option.getOr(NONE) { | NONE => getDefaultError->Utils.getJsonObjectFromRecord | x => x->Utils.getJsonObjectFromRecord } let lastUsedSpmData = switch spmData ->Array.reduce(None, (a: option<SdkTypes.savedDataType>, b: SdkTypes.savedDataType) => { let lastUsedAtA = switch a { | Some(a) => switch a { | SAVEDLISTCARD(savedCard) => savedCard.lastUsedAt | SAVEDLISTWALLET(savedWallet) => savedWallet.lastUsedAt | NONE => None } | None => None } let lastUsedAtB = switch b { | SAVEDLISTCARD(savedCard) => savedCard.lastUsedAt | SAVEDLISTWALLET(savedWallet) => savedWallet.lastUsedAt | NONE => None } switch (lastUsedAtA, lastUsedAtB) { | (None, Some(_)) => Some(b) | (Some(_), None) => a | (Some(dateA), Some(dateB)) => if ( compare( Date.fromString(dateA)->Js.Date.getTime, Date.fromString(dateB)->Js.Date.getTime, ) < 0 ) { Some(b) } else { a } | (None, None) => a } }) ->Option.getOr(NONE) { | NONE => getDefaultError->Utils.getJsonObjectFromRecord | x => x->Utils.getJsonObjectFromRecord } reRegisterCallback.contents = () => { headlessModule.getPaymentSession( defaultSpmData, lastUsedSpmData, spmData->Utils.getJsonObjectFromRecord, response => { switch response->Utils.getDictFromJson->Utils.getOptionString("paymentToken") { | Some(token) => switch spmData->Array.find(x => switch x { | SAVEDLISTCARD(savedCard) => switch savedCard.payment_token { | Some(payment_token) => payment_token == token | None => false } | SAVEDLISTWALLET(savedWallet) => switch savedWallet.payment_token { | Some(payment_token) => payment_token == token | None => false } | NONE => false } ) { | Some(data) => processRequest(nativeProp, data, response, sessions) | None => headlessModule.exitHeadless(getDefaultError->HyperModule.stringifiedResStatus) } | None => headlessModule.exitHeadless(getDefaultError->HyperModule.stringifiedResStatus) } }, ) } reRegisterCallback.contents() } else { getDefaultPaymentSession(getDefaultError) } } let getNativePropCallback = response => { let nativeProp = nativeJsonToRecord(response, 0) let isPublishableKeyValid = GlobalVars.isValidPK(nativeProp.env, nativeProp.publishableKey) let isClientSecretValid = RegExp.test( `.+_secret_[A-Za-z0-9]+`->Js.Re.fromString, nativeProp.clientSecret, ) if isPublishableKeyValid && isClientSecretValid { let timestamp = Date.now() let paymentId = String.split(nativeProp.clientSecret, "_secret_") ->Array.get(0) ->Option.getOr("") logWrapper( ~logType=INFO, ~eventName=PAYMENT_SESSION_INITIATED, ~url="", ~customLogUrl=nativeProp.customLogUrl, ~env=nativeProp.env, ~category=API, ~statusCode="", ~apiLogType=None, ~data=JSON.Encode.null, ~publishableKey=nativeProp.publishableKey, ~paymentId, ~paymentMethod=None, ~paymentExperience=None, ~timestamp, ~latency=0., ~version=nativeProp.hyperParams.sdkVersion, (), ) savedPaymentMethodAPICall(nativeProp) ->Promise.then(customerSavedPMData => { switch customerSavedPMData { | Some(obj) => let spmData = obj->PaymentMethodListType.jsonToSavedPMObj let sessionSpmData = spmData->Array.filter(data => { switch data { | SAVEDLISTWALLET(val) => let walletType = val.walletType->Option.getOr("")->SdkTypes.walletNameToTypeMapper switch (walletType, ReactNative.Platform.os) { | (GOOGLE_PAY, #android) | (APPLE_PAY, #ios) => true | _ => false } | _ => false } }) let walletSpmData = spmData->Array.filter(data => { switch data { | SAVEDLISTWALLET(val) => let walletType = val.walletType->Option.getOr("")->SdkTypes.walletNameToTypeMapper switch (walletType, ReactNative.Platform.os) { | (GOOGLE_PAY, _) | (APPLE_PAY, _) => false | _ => true } | _ => false } }) let cardSpmData = spmData->Array.filter(data => { switch data { | SAVEDLISTCARD(_) => true | _ => false } }) if sessionSpmData->Array.length > 0 { sessionAPICall(nativeProp) ->Promise.then(session => { if session->ErrorUtils.isError { if session->ErrorUtils.getErrorCode == "\"IR_16\"" { ErrorUtils.errorWarning.usedCL ->errorOnApiCalls ->getDefaultPaymentSession } else if session->ErrorUtils.getErrorCode == "\"IR_09\"" { ErrorUtils.errorWarning.invalidCL ->errorOnApiCalls ->getDefaultPaymentSession } } else if session != JSON.Encode.null { switch session->Utils.getDictFromJson->SessionsType.itemToObjMapper { | Some(sessions) => let walletNameArray = sessions->Array.map(wallet => wallet.wallet_name) let filteredSessionSpmData = sessionSpmData->Array.filter( data => switch data { | SAVEDLISTWALLET(data) => walletNameArray->Array.includes( data.walletType->Option.getOr("")->walletNameToTypeMapper, ) | _ => false }, ) let filteredSpmData = filteredSessionSpmData->Array.concat(walletSpmData->Array.concat(cardSpmData)) getPaymentSession(nativeProp, filteredSpmData, Some(sessions)) | None => getPaymentSession(nativeProp, cardSpmData, None) } } else { getPaymentSession(nativeProp, walletSpmData->Array.concat(cardSpmData), None) } Promise.resolve() }) ->ignore } else { getPaymentSession(nativeProp, walletSpmData->Array.concat(cardSpmData), None) } | None => customerSavedPMData->getErrorFromResponse->getDefaultPaymentSession } Promise.resolve() }) ->ignore } else if !isPublishableKeyValid { errorOnApiCalls(INVALID_PK(Error, Static("")))->getDefaultPaymentSession } else if !isClientSecretValid { errorOnApiCalls(INVALID_CL(Error, Static("")))->getDefaultPaymentSession } } headlessModule.initialisePaymentSession(getNativePropCallback) }
4,139
10,646
hyperswitch-client-core
src/headless/HeadlessUtils.res
.res
open SdkTypes let sendLogs = (logFile, customLogUrl, env: GlobalVars.envType) => { let uri = switch customLogUrl { | Some(url) => url | None => switch env { | PROD => "https://api.hyperswitch.io/logs/sdk" | _ => "https://sandbox.hyperswitch.io/logs/sdk" } } if WebKit.platform != #next { let data = logFile->LoggerUtils.logFileToObj->JSON.stringify CommonHooks.fetchApi(~uri, ~method_=Post, ~bodyStr=data, ~headers=Dict.make(), ~mode=NoCORS, ()) ->Promise.then(res => res->Fetch.Response.json) ->Promise.catch(_ => { Promise.resolve(JSON.Encode.null) }) ->ignore } } let logWrapper = ( ~logType: LoggerTypes.logType, ~eventName: LoggerTypes.eventName, ~url: string, ~statusCode: string, ~apiLogType, ~category, ~data: JSON.t, ~paymentMethod: option<string>, ~paymentExperience: option<string>, ~publishableKey: string, ~paymentId: string, ~timestamp, ~latency, ~env, ~customLogUrl, ~version, (), ) => { let (value, internalMetadata) = switch apiLogType { | None => ([], []) | Some(AllPaymentHooks.Request) => ([("url", url->JSON.Encode.string)], []) | Some(AllPaymentHooks.Response) => ( [("url", url->JSON.Encode.string), ("statusCode", statusCode->JSON.Encode.string)], [("response", data)], ) | Some(AllPaymentHooks.NoResponse) => ( [ ("url", url->JSON.Encode.string), ("statusCode", "504"->JSON.Encode.string), ("response", data), ], [("response", data)], ) | Some(AllPaymentHooks.Err) => ( [ ("url", url->JSON.Encode.string), ("statusCode", statusCode->JSON.Encode.string), ("response", data), ], [("response", data)], ) } let logFile: LoggerTypes.logFile = { logType, timestamp: timestamp->Float.toString, sessionId: "", version, codePushVersion: LoggerUtils.getClientCoreVersionNoFromRef(), clientCoreVersion: LoggerUtils.getClientCoreVersionNoFromRef(), component: MOBILE, value: value->Dict.fromArray->JSON.Encode.object->JSON.stringify, internalMetadata: internalMetadata->Dict.fromArray->JSON.Encode.object->JSON.stringify, category, paymentId, merchantId: publishableKey, platform: ReactNative.Platform.os->JSON.stringifyAny->Option.getOr("headless"), userAgent: "userAgent", eventName, firstEvent: true, source: Headless->sdkStateToStrMapper, paymentMethod: paymentMethod->Option.getOr(""), ?paymentExperience, latency: latency->Float.toString, } sendLogs(logFile, customLogUrl, env) } let getBaseUrl = nativeProp => { switch nativeProp.customBackendUrl { | Some(url) => url | None => switch nativeProp.env { | PROD => "https://api.hyperswitch.io" | SANDBOX => "https://sandbox.hyperswitch.io" | INTEG => "https://integ-api.hyperswitch.io" } } } let savedPaymentMethodAPICall = nativeProp => { let paymentId = String.split(nativeProp.clientSecret, "_secret_")->Array.get(0)->Option.getOr("") let uri = `${getBaseUrl( nativeProp, )}/customers/payment_methods?client_secret=${nativeProp.clientSecret}` let initTimestamp = Date.now() logWrapper( ~logType=INFO, ~eventName=CUSTOMER_PAYMENT_METHODS_CALL_INIT, ~url=uri, ~customLogUrl=nativeProp.customLogUrl, ~env=nativeProp.env, ~category=API, ~statusCode="", ~apiLogType=Some(Request), ~data=JSON.Encode.null, ~publishableKey=nativeProp.publishableKey, ~paymentId, ~paymentMethod=None, ~paymentExperience=None, ~timestamp=initTimestamp, ~latency=0., ~version=nativeProp.hyperParams.sdkVersion, (), ) CommonHooks.fetchApi( ~uri, ~method_=Get, ~headers=Utils.getHeader(nativeProp.publishableKey, nativeProp.hyperParams.appId), (), ) ->Promise.then(data => { let respTimestamp = Date.now() let statusCode = data->Fetch.Response.status->string_of_int if statusCode->String.charAt(0) === "2" { data ->Fetch.Response.json ->Promise.then(data => { logWrapper( ~logType=INFO, ~eventName=CUSTOMER_PAYMENT_METHODS_CALL, ~url=uri, ~customLogUrl=nativeProp.customLogUrl, ~env=nativeProp.env, ~category=API, ~statusCode, ~apiLogType=Some(Response), ~data=JSON.Encode.null, ~publishableKey=nativeProp.publishableKey, ~paymentId, ~paymentMethod=None, ~paymentExperience=None, ~timestamp=respTimestamp, ~latency={respTimestamp -. initTimestamp}, ~version=nativeProp.hyperParams.sdkVersion, (), ) Some(data)->Promise.resolve }) } else { data ->Fetch.Response.json ->Promise.then(error => { let value = [ ("url", uri->JSON.Encode.string), ("statusCode", statusCode->JSON.Encode.string), ("response", error), ] ->Dict.fromArray ->JSON.Encode.object logWrapper( ~logType=ERROR, ~eventName=CUSTOMER_PAYMENT_METHODS_CALL, ~url=uri, ~customLogUrl=nativeProp.customLogUrl, ~env=nativeProp.env, ~category=API, ~statusCode, ~apiLogType=Some(Err), ~data=value, ~publishableKey=nativeProp.publishableKey, ~paymentId, ~paymentMethod=None, ~paymentExperience=None, ~timestamp=respTimestamp, ~latency={respTimestamp -. initTimestamp}, ~version=nativeProp.hyperParams.sdkVersion, (), ) Some(error)->Promise.resolve }) } }) ->Promise.catch(err => { let respTimestamp = Date.now() logWrapper( ~logType=ERROR, ~eventName=CUSTOMER_PAYMENT_METHODS_CALL, ~url=uri, ~customLogUrl=nativeProp.customLogUrl, ~env=nativeProp.env, ~category=API, ~statusCode="504", ~apiLogType=Some(NoResponse), ~data=err->Utils.getError(`Headless Error API call failed: ${uri}`), ~publishableKey=nativeProp.publishableKey, ~paymentId, ~paymentMethod=None, ~paymentExperience=None, ~timestamp=respTimestamp, ~latency={respTimestamp -. initTimestamp}, ~version=nativeProp.hyperParams.sdkVersion, (), ) None->Promise.resolve }) } let sessionAPICall = nativeProp => { let paymentId = String.split(nativeProp.clientSecret, "_secret_")->Array.get(0)->Option.getOr("") let headers = Utils.getHeader(nativeProp.publishableKey, nativeProp.hyperParams.appId) let uri = `${getBaseUrl(nativeProp)}/payments/session_tokens` let body = [ ("payment_id", paymentId->JSON.Encode.string), ("client_secret", nativeProp.clientSecret->JSON.Encode.string), ("wallets", []->JSON.Encode.array), ] ->Dict.fromArray ->JSON.Encode.object ->JSON.stringify let initTimestamp = Date.now() logWrapper( ~logType=INFO, ~eventName=CUSTOMER_PAYMENT_METHODS_CALL_INIT, ~url=uri, ~customLogUrl=nativeProp.customLogUrl, ~env=nativeProp.env, ~category=API, ~statusCode="", ~apiLogType=Some(Request), ~data=JSON.Encode.null, ~publishableKey=nativeProp.publishableKey, ~paymentId, ~paymentMethod=None, ~paymentExperience=None, ~timestamp=initTimestamp, ~latency=0., ~version=nativeProp.hyperParams.sdkVersion, (), ) CommonHooks.fetchApi(~uri, ~method_=Post, ~headers, ~bodyStr=body, ()) ->Promise.then(data => { let respTimestamp = Date.now() let statusCode = data->Fetch.Response.status->string_of_int if statusCode->String.charAt(0) === "2" { logWrapper( ~logType=INFO, ~eventName=CUSTOMER_PAYMENT_METHODS_CALL, ~url=uri, ~customLogUrl=nativeProp.customLogUrl, ~env=nativeProp.env, ~category=API, ~statusCode, ~apiLogType=Some(Response), ~data=JSON.Encode.null, ~publishableKey=nativeProp.publishableKey, ~paymentId, ~paymentMethod=None, ~paymentExperience=None, ~timestamp=respTimestamp, ~latency={respTimestamp -. initTimestamp}, ~version=nativeProp.hyperParams.sdkVersion, (), ) data->Fetch.Response.json } else { data ->Fetch.Response.json ->Promise.then(error => { let value = [ ("url", uri->JSON.Encode.string), ("statusCode", statusCode->JSON.Encode.string), ("response", error), ] ->Dict.fromArray ->JSON.Encode.object logWrapper( ~logType=ERROR, ~eventName=CUSTOMER_PAYMENT_METHODS_CALL, ~url=uri, ~customLogUrl=nativeProp.customLogUrl, ~env=nativeProp.env, ~category=API, ~statusCode, ~apiLogType=Some(Err), ~data=value, ~publishableKey=nativeProp.publishableKey, ~paymentId, ~paymentMethod=None, ~paymentExperience=None, ~timestamp=respTimestamp, ~latency={respTimestamp -. initTimestamp}, ~version=nativeProp.hyperParams.sdkVersion, (), ) Promise.resolve(error) }) } }) ->Promise.catch(err => { let respTimestamp = Date.now() logWrapper( ~logType=ERROR, ~eventName=CUSTOMER_PAYMENT_METHODS_CALL, ~url=uri, ~customLogUrl=nativeProp.customLogUrl, ~env=nativeProp.env, ~category=API, ~statusCode="504", ~apiLogType=Some(NoResponse), ~data=err->Utils.getError(`Headless Error API call failed: ${uri}`), ~publishableKey=nativeProp.publishableKey, ~paymentId, ~paymentMethod=None, ~paymentExperience=None, ~timestamp=respTimestamp, ~latency={respTimestamp -. initTimestamp}, ~version=nativeProp.hyperParams.sdkVersion, (), ) Promise.resolve(JSON.Encode.null) }) } let confirmAPICall = (nativeProp, body) => { let paymentId = String.split(nativeProp.clientSecret, "_secret_")->Array.get(0)->Option.getOr("") let uri = `${getBaseUrl(nativeProp)}/payments/${paymentId}/confirm` let headers = Utils.getHeader(nativeProp.publishableKey, nativeProp.hyperParams.appId) let initTimestamp = Date.now() logWrapper( ~logType=INFO, ~eventName=CONFIRM_CALL_INIT, ~url=uri, ~customLogUrl=nativeProp.customLogUrl, ~env=nativeProp.env, ~category=API, ~statusCode="", ~apiLogType=Some(Request), ~data=JSON.Encode.null, ~publishableKey=nativeProp.publishableKey, ~paymentId, ~paymentMethod=None, ~paymentExperience=None, ~timestamp=initTimestamp, ~latency=0., ~version=nativeProp.hyperParams.sdkVersion, (), ) CommonHooks.fetchApi(~uri, ~method_=Post, ~headers, ~bodyStr=body, ()) ->Promise.then(data => { let respTimestamp = Date.now() let statusCode = data->Fetch.Response.status->string_of_int if statusCode->String.charAt(0) === "2" { logWrapper( ~logType=INFO, ~eventName=CONFIRM_CALL, ~url=uri, ~customLogUrl=nativeProp.customLogUrl, ~env=nativeProp.env, ~category=API, ~statusCode, ~apiLogType=Some(Response), ~data=JSON.Encode.null, ~publishableKey=nativeProp.publishableKey, ~paymentId, ~paymentMethod=None, ~paymentExperience=None, ~timestamp=respTimestamp, ~latency={respTimestamp -. initTimestamp}, ~version=nativeProp.hyperParams.sdkVersion, (), ) data->Fetch.Response.json } else { data ->Fetch.Response.json ->Promise.then(error => { let value = [ ("url", uri->JSON.Encode.string), ("statusCode", statusCode->JSON.Encode.string), ("response", error), ] ->Dict.fromArray ->JSON.Encode.object logWrapper( ~logType=ERROR, ~eventName=CONFIRM_CALL, ~url=uri, ~customLogUrl=nativeProp.customLogUrl, ~env=nativeProp.env, ~category=API, ~statusCode, ~apiLogType=Some(Err), ~data=value, ~publishableKey=nativeProp.publishableKey, ~paymentId, ~paymentMethod=None, ~paymentExperience=None, ~timestamp=respTimestamp, ~latency={respTimestamp -. initTimestamp}, ~version=nativeProp.hyperParams.sdkVersion, (), ) Promise.resolve(error) }) } }) ->Promise.then(jsonResponse => { Promise.resolve(Some(jsonResponse)) }) ->Promise.catch(err => { let data = err->Utils.getError(`Headless Error API call failed: ${uri}`) let respTimestamp = Date.now() logWrapper( ~logType=ERROR, ~eventName=CONFIRM_CALL, ~url=uri, ~customLogUrl=nativeProp.customLogUrl, ~env=nativeProp.env, ~category=API, ~statusCode="504", ~apiLogType=Some(NoResponse), ~data, ~publishableKey=nativeProp.publishableKey, ~paymentId, ~paymentMethod=None, ~paymentExperience=None, ~timestamp=respTimestamp, ~latency={respTimestamp -. initTimestamp}, ~version=nativeProp.hyperParams.sdkVersion, (), ) Promise.resolve(None) }) } let errorOnApiCalls = (inputKey: ErrorUtils.errorKey, ~dynamicStr="") => { let (type_, str) = switch inputKey { | INVALID_PK(var) => var | INVALID_EK(var) => var | DEPRECATED_LOADSTRIPE(var) => var | REQUIRED_PARAMETER(var) => var | UNKNOWN_KEY(var) => var | UNKNOWN_VALUE(var) => var | TYPE_BOOL_ERROR(var) => var | TYPE_STRING_ERROR(var) => var | INVALID_FORMAT(var) => var | USED_CL(var) => var | INVALID_CL(var) => var | NO_DATA(var) => var } switch (type_, str) { | (Error, Static(string)) => let error: PaymentConfirmTypes.error = { message: string, code: "no_data", type_: "no_data", status: "failed", } error | (Warning, Static(string)) => { message: string, code: "no_data", type_: "no_data", status: "failed", } | (Error, Dynamic(fn)) => { message: fn(dynamicStr), code: "no_data", type_: "no_data", status: "failed", } | (Warning, Dynamic(fn)) => { message: fn(dynamicStr), code: "no_data", type_: "no_data", status: "failed", } } } let getDefaultError = errorOnApiCalls(ErrorUtils.errorWarning.noData) let getErrorFromResponse = data => { switch data { | Some(data) => let dict = data->Utils.getDictFromJson let errorDict = Dict.get(dict, "error") ->Option.getOr(JSON.Encode.null) ->JSON.Decode.object ->Option.getOr(Dict.make()) let error: PaymentConfirmTypes.error = { message: Utils.getString( errorDict, "message", Utils.getString( dict, "error_message", Utils.getString(dict, "error", getDefaultError.message->Option.getOr("")), ), ), code: Utils.getString( errorDict, "code", Utils.getString(dict, "error_code", getDefaultError.code->Option.getOr("")), ), type_: Utils.getString( errorDict, "type", Utils.getString(dict, "type", getDefaultError.type_->Option.getOr("")), ), status: Utils.getString(dict, "status", getDefaultError.status->Option.getOr("")), } error | None => getDefaultError } }
3,905
10,647
hyperswitch-client-core
src/headless/HeadlessNative.res
.res
open ReactNative type headlessModule = { initialisePaymentSession: (JSON.t => unit) => unit, getPaymentSession: (JSON.t, JSON.t, JSON.t, JSON.t => unit) => unit, exitHeadless: string => unit, } let getFunctionFromModule = (dict: Dict.t<'a>, key: string, default: 'b): 'b => { switch dict->Dict.get(key) { | Some(fn) => Obj.magic(fn) | None => default } } @react.component let dummy = () => { React.null } let initialise = headless => { AppRegistry.registerComponent("dummy", _ => dummy) AppRegistry.registerHeadlessTask("dummy", () => { _data => { Promise.resolve() } }) let hyperSwitchHeadlessDict = Dict.get(ReactNative.NativeModules.nativeModules, headless) ->Option.flatMap(JSON.Decode.object) ->Option.getOr(Dict.make()) { initialisePaymentSession: getFunctionFromModule( hyperSwitchHeadlessDict, "initialisePaymentSession", _ => (), ), getPaymentSession: getFunctionFromModule(hyperSwitchHeadlessDict, "getPaymentSession", ( _, _, _, _, ) => ()), exitHeadless: getFunctionFromModule(hyperSwitchHeadlessDict, "exitHeadless", _ => ()), } }
310
10,648
hyperswitch-client-core
src/components/modules/SamsungPayModule.res
.res
open ExternalThreeDsTypes type module_ = { checkSamsungPayValidity: (string, statusType => unit) => unit, presentSamsungPayPaymentSheet: ( (statusType, option<SamsungPayType.addressCollectedFromSpay>) => unit ) => unit, isAvailable: bool, } @val external require: string => module_ = "require" let (checkSamsungPayValidity, presentSamsungPayPaymentSheet, isAvailable) = switch try { require("react-native-hyperswitch-samsung-pay")->Some } catch { | _ => None } { | Some(mod) => (mod.checkSamsungPayValidity, mod.presentSamsungPayPaymentSheet, mod.isAvailable) | None => ((_, _) => (), _ => (), false) }
163
10,649
hyperswitch-client-core
src/components/modules/ScanCardModule.res
.res
type scanCardData = { pan: string, expiryMonth: string, expiryYear: string, } type scanCardReturnType = { status: string, data: scanCardData, } type scanCardReturnStatus = Succeeded(scanCardData) | Failed | Cancelled | None type module_ = {launchScanCard: (scanCardReturnType => unit) => unit, isAvailable: bool} @val external require: string => module_ = "require" let (launchScanCardMod, isAvailable) = switch try { require("react-native-hyperswitch-scancard")->Some } catch { | _ => None } { | Some(mod) => (mod.launchScanCard, mod.isAvailable) | None => (_ => (), false) } let dictToScanCardReturnType = (scanCardReturnType: scanCardReturnType) => { switch scanCardReturnType.status { | "Succeeded" => Succeeded({ pan: scanCardReturnType.data.pan, expiryMonth: scanCardReturnType.data.expiryMonth, expiryYear: scanCardReturnType.data.expiryYear, }) | "Cancelled" => Cancelled | "Failed" => Failed | _ => None } } let launchScanCard = (callback: scanCardReturnStatus => unit) => { try { launchScanCardMod(data => callback(data->dictToScanCardReturnType)) } catch { | _ => () } }
308
10,650
hyperswitch-client-core
src/components/modules/KountModule.res
.res
type module_ = {launchKount: (string, Dict.t<JSON.t> => unit) => unit} @val external require: string => module_ = "require" let launchKountMod = switch try { require("react-native-hyperswitch-kount")->Some } catch { | _ => None } { | Some(mod) => mod.launchKount | None => (_, _) => () } let launchKountIfAvailable = (requestObj: string, callback) => { try { let str = requestObj->String.split("_secret_")->Array.get(0)->Option.getOr("") launchKountMod(`{"merchantId":"merchantID","sessionId":"${str}"}`, callback) } catch { | _ => () } }
163
10,651
hyperswitch-client-core
src/components/modules/KlarnaModule.res
.res
type params = { @dead authorized: bool, approved: bool, authToken: option<string>, errorMessage: option<string>, } type event = {nativeEvent: params} type element = { initialize: (string, option<string>) => unit, load: unit => unit, authorize: unit => unit, } type moduleProps = { key: string, category: string, ref: ReactNative.Ref.t<element>, onInitialized: unit => unit, onLoaded: unit => unit, onAuthorized: event => unit, children: React.element, } type module_ = {default: React.component<moduleProps>} @val external require: string => module_ = "require" let klarnaReactPaymentView = try { require("react-native-klarna-inapp-sdk/index")->Some } catch { | _ => None } @react.component let make = ( ~reference, ~paymentMethod, ~onInitialized, ~onLoaded, ~onAuthorized, ~children=React.null, ) => { switch klarnaReactPaymentView { | Some(mod) => React.createElement( mod.default, { key: paymentMethod, category: paymentMethod, ref: reference->ReactNative.Ref.value, onInitialized, onLoaded, onAuthorized, children, }, ) | None => React.null } }
304
10,652
hyperswitch-client-core
src/components/modules/ErrorBoundary.res
.res
let defaultFallback = (fallbackArg: Sentry.fallbackArg, level, rootTag) => { <FallBackScreen error=fallbackArg level rootTag /> } @react.component let make = (~children, ~renderFallback=defaultFallback, ~level, ~rootTag) => { <Sentry.ErrorBoundary fallback={e => renderFallback(e, level, rootTag)}> children </Sentry.ErrorBoundary> }
89
10,653
hyperswitch-client-core
src/components/modules/ReactModule.res
.res
@module("react") external useEffect: (unit => option<unit => unit>) => unit = "useEffect"
24
10,654
hyperswitch-client-core
src/components/modules/HyperModule.res
.res
type hyperModule = { sendMessageToNative: string => unit, launchApplePay: (string, Dict.t<JSON.t> => unit) => unit, startApplePay: (string, Dict.t<JSON.t> => unit) => unit, presentApplePay: (string, Dict.t<JSON.t> => unit) => unit, launchGPay: (string, Dict.t<JSON.t> => unit) => unit, exitPaymentsheet: (int, string, bool) => unit, exitPaymentMethodManagement: (int, string, bool) => unit, exitWidget: (string, string) => unit, exitCardForm: string => unit, launchWidgetPaymentSheet: (string, Dict.t<JSON.t> => unit) => unit, onAddPaymentMethod: string => unit, exitWidgetPaymentsheet: (int, string, bool) => unit, } let getFunctionFromModule = (dict: Dict.t<'a>, key: string, default) => { switch dict->Dict.get(key) { | Some(fn) => Obj.magic(fn) | None => default } } let hyperModuleDict = Dict.get(ReactNative.NativeModules.nativeModules, "HyperModule") ->Option.flatMap(JSON.Decode.object) ->Option.getOr(Dict.make()) let hyperModule = { sendMessageToNative: getFunctionFromModule(hyperModuleDict, "sendMessageToNative", _ => ()), launchApplePay: getFunctionFromModule(hyperModuleDict, "launchApplePay", (_, _) => ()), startApplePay: getFunctionFromModule(hyperModuleDict, "startApplePay", (_, _) => ()), presentApplePay: getFunctionFromModule(hyperModuleDict, "presentApplePay", (_, _) => ()), launchGPay: getFunctionFromModule(hyperModuleDict, "launchGPay", (_, _) => ()), exitPaymentsheet: getFunctionFromModule(hyperModuleDict, "exitPaymentsheet", (_, _, _) => ()), exitPaymentMethodManagement: getFunctionFromModule( hyperModuleDict, "exitPaymentMethodManagement", (_, _, _) => (), ), exitWidget: getFunctionFromModule(hyperModuleDict, "exitWidget", (_, _) => ()), exitCardForm: getFunctionFromModule(hyperModuleDict, "exitCardForm", _ => ()), launchWidgetPaymentSheet: getFunctionFromModule(hyperModuleDict, "launchWidgetPaymentSheet", ( _, _, ) => ()), onAddPaymentMethod: getFunctionFromModule(hyperModuleDict, "onAddPaymentMethod", _ => ()), exitWidgetPaymentsheet: getFunctionFromModule(hyperModuleDict, "exitWidgetPaymentsheet", ( _, _, _, ) => ()), } let sendMessageToNative = str => { hyperModule.sendMessageToNative(str) } let stringifiedResStatus = (apiResStatus: PaymentConfirmTypes.error) => { [ ("type", apiResStatus.type_->Option.getOr("")->JSON.Encode.string), ("code", apiResStatus.code->Option.getOr("")->JSON.Encode.string), ( "message", apiResStatus.message ->Option.getOr("An unknown error has occurred please retry") ->JSON.Encode.string, ), ("status", apiResStatus.status->Option.getOr("failed")->JSON.Encode.string), ] ->Dict.fromArray ->JSON.Encode.object ->JSON.stringify } type useExitPaymentsheetReturnType = { exit: (PaymentConfirmTypes.error, bool) => unit, simplyExit: (PaymentConfirmTypes.error, int, bool) => unit, } let useExitPaymentsheet = () => { // let (ref, _) = React.useContext(ReactNativeWrapperContext.reactNativeWrapperContext) let logger = LoggerHook.useLoggerHook() let (nativeProp, _) = React.useContext(NativePropContext.nativePropContext) // let (allApiData, _) = React.useContext(AllApiDataContext.allApiDataContext) let {exitPaymentSheet} = WebKit.useWebKit() let exit = (apiResStatus: PaymentConfirmTypes.error, reset) => { logger( ~logType=INFO, ~value=nativeProp.hyperParams.appId->Option.getOr(""), ~category=USER_EVENT, ~eventName=SDK_CLOSED, (), ) //setSdkState(SdkTypes.NoView) // switch ref { // | None => () // | Some(fun) => fun(JSON.Encode.null) // } ReactNative.Platform.os == #web ? // BrowserHook.href( // BrowserHook.location, // `${allApiData.redirect_url->Option.getOr("")}?status=${apiResStatus.status->Option.getOr( // "failed", // )}&payment_intent_client_secret=${nativeProp.clientSecret}&amount=6541`, // ) exitPaymentSheet(apiResStatus->stringifiedResStatus) : switch nativeProp.sdkState { | WidgetPaymentSheet => hyperModule.exitWidgetPaymentsheet( nativeProp.rootTag, apiResStatus->stringifiedResStatus, reset, ) | PaymentMethodsManagement => hyperModule.exitPaymentMethodManagement( nativeProp.rootTag, apiResStatus->stringifiedResStatus, reset, ) | _ => hyperModule.exitPaymentsheet( nativeProp.rootTag, apiResStatus->stringifiedResStatus, reset, ) } } let simplyExit = (apiResStatus, rootTag, reset) => { ReactNative.Platform.os == #web ? // BrowserHook.href( // BrowserHook.location, // `${allApiData.redirect_url->Option.getOr( // "", // )}?status=${"failed"}&payment_intent_client_secret=clientSecret&amount=6541`, // ) exitPaymentSheet(apiResStatus->stringifiedResStatus) : nativeProp.sdkState == WidgetPaymentSheet ? hyperModule.exitWidgetPaymentsheet(rootTag, apiResStatus->stringifiedResStatus, reset) : hyperModule.exitPaymentsheet(rootTag, apiResStatus->stringifiedResStatus, reset) } {exit, simplyExit} } let useExitCard = () => { exitMode => { hyperModule.exitCardForm(exitMode->stringifiedResStatus) } } let useExitWidget = () => { (exitMode, widgetType: string) => { hyperModule.exitWidget(exitMode->stringifiedResStatus, widgetType) } } let launchApplePay = (requestObj: string, callback, startCallback, presentCallback) => { hyperModule.startApplePay("", startCallback) hyperModule.presentApplePay("", presentCallback) hyperModule.launchApplePay(requestObj, callback) } let launchGPay = (requestObj: string, callback) => { hyperModule.launchGPay(requestObj, callback) } let launchWidgetPaymentSheet = (requestObj: string, callback) => { hyperModule.launchWidgetPaymentSheet(requestObj, callback) }
1,531
10,655
hyperswitch-client-core
src/components/modules/PaypalModule.res
.res
type module_ = {launchPayPal: (string, Dict.t<JSON.t> => unit) => unit} @val external require: string => module_ = "require" let payPalModule = try { require("react-native-hyperswitch-paypal")->Some } catch { | _ => None } let launchPayPalMod = switch payPalModule { | Some(mod) => mod.launchPayPal | None => (_, _) => () } let launchPayPal = (requestObj: string, callback) => { try { launchPayPalMod(requestObj, callback) } catch { | _ => () } }
136
10,656
hyperswitch-client-core
src/components/modules/Sentry.res
.res
type integration = unit type instrumentation = unit type sentryInitArg = { dsn: string, environment: string, integrations?: array<integration>, tracesSampleRate: float, tracePropagationTargets?: array<string>, replaysSessionSampleRate?: float, replaysOnErrorSampleRate?: float, deactivateStacktraceMerging?: bool, } type newBrowserTracingArg = {routingInstrumentation: instrumentation} @new @scope("sentryReactNative") external newBrowserTracing: newBrowserTracingArg => integration = "BrowserTracing" @new @scope("sentryReactNative") external newSentryReplay: unit => integration = "Replay" type fallbackArg = { error: Exn.t, componentStack: array<string>, resetError: unit => unit, } type props = {fallback: fallbackArg => React.element, children: React.element} type module_ = { init: sentryInitArg => unit, \"BrowserTracing": newBrowserTracingArg => integration, reactRouterV6Instrumentation: ((unit => option<unit => unit>) => unit) => instrumentation, \"Replay": unit => integration, \"ErrorBoundary": option<React.component<props>>, wrap: React.element => React.element, } @val external require: string => module_ = "require" let sentryReactNative = switch try { require("@sentry/react-native")->Some } catch { | _ => None } { | Some(mod) => mod | None => { init: _ => (), \"BrowserTracing": _ => (), reactRouterV6Instrumentation: _ => (), \"Replay": () => (), \"ErrorBoundary": None, wrap: component => component, } } module ErrorBoundary = { @react.component let make: (~fallback: fallbackArg => React.element, ~children: React.element) => React.element = ( ~fallback, ~children, ) => { switch sentryReactNative.\"ErrorBoundary" { | Some(component) => React.createElement( component, { fallback, children, }, ) | None => children } } } let initiateSentry = (~dsn: option<string>, ~environment: string) => { try { let integrations = ReactNative.Platform.os === #web ? [ newBrowserTracing({ routingInstrumentation: sentryReactNative.reactRouterV6Instrumentation( ReactModule.useEffect, ), }), newSentryReplay(), ] : [] switch dsn { | Some(dsn) => sentryReactNative.init({ dsn, environment, integrations, tracesSampleRate: 1.0, }) | None => () } } catch { | _ => () } }
615
10,657
hyperswitch-client-core
src/components/modules/Netcetera3dsModule.res
.res
open ExternalThreeDsTypes type module_ = { initialiseNetceteraSDK: (string, string, statusType => unit) => unit, generateAReqParams: (string, string, (statusType, aReqParams) => unit) => unit, recieveChallengeParamsFromRN: ( string, string, string, string, statusType => unit, option<string>, ) => unit, generateChallenge: (statusType => unit) => unit, isAvailable: bool, } @val external require: string => module_ = "require" let ( initialiseNetceteraSDK, generateAReqParams, recieveChallengeParamsFromRN, generateChallenge, isAvailable, ) = switch try { require("react-native-hyperswitch-netcetera-3ds")->Some } catch { | _ => None } { | Some(mod) => ( mod.initialiseNetceteraSDK, mod.generateAReqParams, mod.recieveChallengeParamsFromRN, mod.generateChallenge, mod.isAvailable, ) | None => ((_, _, _) => (), (_, _, _) => (), (_, _, _, _, _, _) => (), _ => (), false) }
264
10,658
hyperswitch-client-core
src/components/modules/ApplePayButtonView/ApplePayButtonView.res
.res
open ReactNative type props = { buttonType?: SdkTypes.applePayButtonType, buttonStyle?: SdkTypes.applePayButtonStyle, cornerRadius?: float, style?: Style.t, } @module("./ApplePayButtonViewImpl") external make: React.component<props> = "make"
65
10,659
hyperswitch-client-core
src/components/modules/ApplePayButtonView/ApplePayButtonViewImpl.web.res
.res
open ReactNative @react.component let make = (~cornerRadius: float, ~style: Style.t) => { let styleDict = style ->JSON.stringifyAny ->Option.getOr("") ->Js.Json.parseExn ->Utils.getDictFromJson let height = styleDict ->Utils.getOptionFloat("height") ->Option.getOr(100.) ->Float.toString <View nativeID="apple-wallet-button-container" style> <style> {React.string( ` apple-pay-button { --apple-pay-button-width: ${styleDict->Utils.getString("width", "100%")}; --apple-pay-button-height: ${height}px; --apple-pay-button-border-radius: ${cornerRadius->Float.toString}px; display: inline-block !important; } `, )} </style> <CustomLoader style={ReactNative.Style.viewStyle( ~position=#absolute, ~zIndex=-1, ~borderRadius=cornerRadius, (), )} /> <apple-pay-button /> </View> }
243
10,660
hyperswitch-client-core
src/components/modules/ApplePayButtonView/ApplePayButtonViewImpl.android.res
.res
type props let make: React.component<props> = _ => React.null
17
10,661
hyperswitch-client-core
src/components/modules/ApplePayButtonView/ApplePayButtonViewImpl.ios.res
.res
open ReactNative type props = { buttonType?: SdkTypes.applePayButtonType, buttonStyle?: SdkTypes.applePayButtonStyle, cornerRadius?: float, style?: Style.t, } let make: React.component<props> = NativeModules.requireNativeComponent("ApplePayView")
63
10,662
hyperswitch-client-core
src/components/modules/GooglePayButtonView/GooglePayButtonViewImpl.android.res
.res
type props = { buttonType?: SdkTypes.googlePayButtonType, borderRadius?: float, buttonStyle?: ReactNative.Appearance.t, style?: ReactNative.Style.t, allowedPaymentMethods?: string, } let make: React.component<props> = ReactNative.NativeModules.requireNativeComponent( "GooglePayButton", )
69
10,663
hyperswitch-client-core
src/components/modules/GooglePayButtonView/GooglePayButtonViewImpl.web.res
.res
open ReactNative @react.component let make = (~borderRadius: float, ~style: Style.t) => { <View nativeID="google-wallet-button-container" style={style}> <style> {React.string(` .gpay-card-info-container.black, .gpay-card-info-animation-container.black { background-color: #000 !important; } `)} </style> <CustomLoader style={ReactNative.Style.viewStyle(~position=#absolute, ~zIndex=-1, ~borderRadius, ())} /> </View> }
125
10,664
hyperswitch-client-core
src/components/modules/GooglePayButtonView/GooglePayButtonView.res
.res
type props = { buttonType?: SdkTypes.googlePayButtonType, borderRadius?: float, buttonStyle?: ReactNative.Appearance.t, style?: ReactNative.Style.t, allowedPaymentMethods?: string, } @module("./GooglePayButtonViewImpl") external make: React.component<props> = "make"
66
10,665
hyperswitch-client-core
src/components/modules/GooglePayButtonView/GooglePayButtonViewImpl.ios.res
.res
type props = { buttonType?: SdkTypes.googlePayButtonType, borderRadius?: float, buttonStyle?: ReactNative.Appearance.t, style?: ReactNative.Style.t, allowedPaymentMethods?: string, } let make: React.component<props> = _ => React.null
59
10,666
hyperswitch-client-core
src/components/modules/Plaid/PlaidImpl.android.res
.res
/** Checks if native modules for sdk have been imported as optional dependency */ let isAvailable = Dict.get(ReactNative.NativeModules.nativeModules, "PlaidAndroid") ->Option.flatMap(JSON.Decode.object) ->Option.isSome
49
10,667
hyperswitch-client-core
src/components/modules/Plaid/PlaidImpl.ios.res
.res
/** Checks if native modules for sdk have been imported as optional dependency */ let isAvailable = Dict.get(ReactNative.NativeModules.nativeModules, "RNLinksdk") ->Option.flatMap(JSON.Decode.object) ->Option.isSome
49
10,668
hyperswitch-client-core
src/components/modules/Plaid/PlaidImpl.web.res
.res
/** Checks if native modules for sdk have been imported as optional dependency. Not available in web via plaid-link-sdk. */ let isAvailable = false
31
10,669
hyperswitch-client-core
src/components/modules/Plaid/Plaid.res
.res
open PlaidTypes type module_ = { create: linkTokenConfiguration => unit, @as("open") open_: linkOpenProps => promise<unit>, dismissLink: unit => unit, } @module("./PlaidImpl") external isAvailable: bool = "isAvailable" @val external require: string => module_ = "require" /** Plaid Link React Native SDK */ let (create, open_, dismissLink) = switch try { isAvailable ? require("react-native-plaid-link-sdk")->Some : None } catch { | _ => // "'Plaid-link-sdk' not found. If you are sure the module exists, try restarting Metro. You may also want to run `yarn` or `npm install`.", None } { | Some(mod) => (mod.create, mod.open_, mod.dismissLink) | None => (_ => (), _ => Promise.resolve(), _ => ()) }
194
10,670
hyperswitch-client-core
src/components/elements/ModalHeader.res
.res
open ReactNative open Style @react.component let make = (~onModalClose) => { let (nativeProp, _) = React.useContext(NativePropContext.nativePropContext) let {iconColor} = ThemebasedStyle.useThemeBasedStyle() let (paymentScreenType, _) = React.useContext(PaymentScreenContext.paymentScreenTypeContext) let (allApiData, _) = React.useContext(AllApiDataContext.allApiDataContext) let (localStrings, _) = React.useContext(LocaleStringDataContext.localeDataContext) let isLoadingScreenActive = switch (allApiData.savedPaymentMethods, localStrings) { | (Loading, _) | (_, Loading) => true | _ => false } <View style={viewStyle( ~display=#flex, ~flexGrow=?{ReactNative.Platform.os !== #web ? Some(1.) : None}, ~flexDirection=#row, ~alignItems=#center, ~justifyContent=#"space-between", (), )}> {if isLoadingScreenActive { <View /> } else { switch switch paymentScreenType { | PaymentScreenContext.PAYMENTSHEET => nativeProp.configuration.paymentSheetHeaderText | PaymentScreenContext.SAVEDCARDSCREEN => nativeProp.configuration.savedPaymentScreenHeaderText } { | Some(var) => <View style={viewStyle(~maxWidth=60.->pct, ())}> <TextWrapper text={var} textType={HeadingBold} /> </View> | _ => <View /> } }} <View style={viewStyle( ~flexDirection=#row, ~flexWrap=#wrap, ~alignItems=#center, ~maxWidth=40.->pct, (), )}> {isLoadingScreenActive ? React.null : <> {nativeProp.env === GlobalVars.PROD ? React.null : <View style={viewStyle( ~backgroundColor="#ffdd93", ~marginHorizontal=5.->dp, ~padding=5.->dp, ~borderRadius=5., (), )}> <TextWrapper textType={ModalTextBold} text="Test Mode" overrideStyle=Some(textStyle(~color="black", ())) /> </View>} <CustomTouchableOpacity onPress={_ => onModalClose()}> <Icon name="close" width=16. height=16. fill=iconColor /> </CustomTouchableOpacity> </>} </View> </View> }
555
10,671
hyperswitch-client-core
src/components/elements/CardElement.res
.res
open Validation type cardFormType = {isZipAvailable: bool} type viewType = PaymentSheet | CardForm(cardFormType) @react.component let make = ( ~setIsAllValid, ~viewType=PaymentSheet, ~reset: bool, ~keyToTrigerButtonClickError=0, ~cardNetworks=?, ) => { let isZipAvailable = switch viewType { | CardForm(cardFormType) => cardFormType.isZipAvailable | _ => false } let isCardBrandSupported = ( ~cardBrand, ~cardNetworks: option<array<PaymentMethodListType.card_networks>>, ) => { switch (cardNetworks, cardBrand) { | (_, "") | (None, _) => true | (Some(cardNetwork), cardBrand) => { let lowerCardBrand = cardBrand->String.toLowerCase cardNetwork->Array.some(network => network.card_network->String.toLowerCase == lowerCardBrand ) } } } // let (cardNumber, setCardNumber) = React.useState(_ => "") // let (expireDate, setExpireDate) = React.useState(_ => "") // let (cvv, setCvv) = React.useState(_ => "") // let (zip, setZip) = React.useState(_ => "") // let (isCardNumberValid, setIsCardNumberValid) = React.useState(_ => None) // let (isExpireDataValid, setIsExpireDataValid) = React.useState(_ => None) // let (isCvvValid, setIsCvvValid) = React.useState(_ => None) // let (isZipValid, setIsZipValid) = React.useState(_ => None) let (cardData, setCardData) = React.useContext(CardDataContext.cardDataContext) let isAllValid = React.useMemo1(() => { switch ( cardData.isCardNumberValid, cardData.isCvvValid, cardData.isExpireDataValid, cardData.isCardBrandSupported, !isZipAvailable || switch cardData.isZipValid { | Some(zipValid) => zipValid | None => false }, ) { | (Some(cardValid), Some(cvvValid), Some(expValid), Some(isCardBrandSupported), zipValid) => cardValid && cvvValid && expValid && isCardBrandSupported && zipValid | _ => false } }, [cardData]) React.useEffect1(() => { setIsAllValid(_ => isAllValid) None }, [isAllValid]) React.useEffect1(() => { if reset { setCardData(_ => CardDataContext.dafaultVal) } None }, [reset]) let onChangeCardNumber = ( text, expireRef: React.ref<Nullable.t<ReactNative.TextInput.element>>, ) => { let enabledCardSchemes = PaymentUtils.getCardNetworks(cardNetworks->Option.getOr(None)) let validCardBrand = getFirstValidCardScheme(~cardNumber=text, ~enabledCardSchemes) let cardBrand = validCardBrand === "" ? getCardBrand(text) : validCardBrand let num = formatCardNumber(text, cardType(cardBrand)) let isthisValid = cardValid(num, cardBrand) let isSupported = switch cardNetworks { | Some(networks) => isCardBrandSupported(~cardBrand, ~cardNetworks=networks) | None => true } let shouldShiftFocusToNextField = isCardNumberEqualsMax(num, cardBrand) let isCardBrandChanged = cardData.cardBrand !== cardBrand && cardData.cardBrand != "" setCardData(prev => { ...prev, cardNumber: num, isCardNumberValid: Some(isthisValid), isCardBrandSupported: Some(isSupported), cardBrand, expireDate: isCardBrandChanged ? "" : prev.expireDate, cvv: isCardBrandChanged ? "" : prev.cvv, isCvvValid: isCardBrandChanged ? None : prev.isCvvValid, isExpireDataValid: isCardBrandChanged ? None : prev.isExpireDataValid, }) // Adding support for 19 digit card hence disabling ref if isthisValid && shouldShiftFocusToNextField { switch expireRef.current->Nullable.toOption { | None => () | Some(ref) => ref->ReactNative.TextInputElement.focus } } } let onChangeCardExpire = (text, cvvRef: React.ref<Nullable.t<ReactNative.TextInput.element>>) => { let dateExpire = formatCardExpiryNumber(text) let isthisValid = checkCardExpiry(dateExpire) if isthisValid { switch cvvRef.current->Nullable.toOption { | None => () | Some(ref) => ref->ReactNative.TextInputElement.focus } } setCardData(prev => {...prev, expireDate: dateExpire, isExpireDataValid: Some(isthisValid)}) } let onChangeCvv = (text, cvvOrZipRef: React.ref<Nullable.t<ReactNative.TextInput.element>>) => { let cvvData = formatCVCNumber(text, getCardBrand(cardData.cardNumber)) let isValidCvv = checkCardCVC(cvvData, getCardBrand(cardData.cardNumber)) let shouldShiftFocusToNextField = checkMaxCardCvv(cvvData, getCardBrand(cardData.cardNumber)) if isValidCvv && shouldShiftFocusToNextField { switch cvvOrZipRef.current->Nullable.toOption { | None => () | Some(ref) => isZipAvailable ? ref->ReactNative.TextInputElement.focus : ref->ReactNative.TextInputElement.blur } } setCardData(prev => {...prev, cvv: cvvData, isCvvValid: Some(isValidCvv)}) } let onChangeZip = (text, zipRef: React.ref<Nullable.t<ReactNative.TextInput.element>>) => { let isthisValid = Validation.isValidZip(~zipCode=text, ~country="United States") if isthisValid { switch zipRef.current->Nullable.toOption { | None => () | Some(ref) => ref->ReactNative.TextInputElement.blur } } setCardData(prev => {...prev, zip: text, isZipValid: Some(isthisValid)}) } let onScanCard = ( pan, expiry, expireRef: React.ref<Nullable.t<ReactNative.TextInput.element>>, cvvRef: React.ref<Nullable.t<ReactNative.TextInput.element>>, ) => { let cardBrand = getCardBrand(pan) let cardNumber = formatCardNumber(pan, cardType(cardBrand)) let isCardValid = cardValid(cardNumber, cardBrand) let expireDate = formatCardExpiryNumber(expiry) let isExpiryValid = checkCardExpiry(expireDate) let isExpireDataValid = expireDate->Js.String2.length > 0 ? Some(isExpiryValid) : None setCardData(prev => { ...prev, cardNumber, isCardNumberValid: Some(isCardValid), expireDate, isExpireDataValid, cardBrand, }) switch (isCardValid, isExpiryValid) { | (true, true) => switch cvvRef.current->Nullable.toOption { | None => () | Some(ref) => ref->ReactNative.TextInputElement.focus } | (true, false) => switch expireRef.current->Nullable.toOption { | None => () | Some(ref) => ref->ReactNative.TextInputElement.focus } | _ => () } } { switch viewType { | PaymentSheet => <PaymentSheetUi cardNumber=cardData.cardNumber cvv=cardData.cvv expireDate=cardData.expireDate onChangeCardNumber onChangeCardExpire onChangeCvv onScanCard isCardNumberValid=cardData.isCardNumberValid isExpireDataValid=cardData.isExpireDataValid isCardBrandSupported=cardData.isCardBrandSupported isCvvValid=cardData.isCvvValid keyToTrigerButtonClickError cardNetworks /> | CardForm(_) => <CardFormUi cardNumber=cardData.cardNumber cvv=cardData.cvv expireDate=cardData.expireDate onChangeCardNumber onChangeCardExpire onChangeCvv onChangeZip isCardNumberValid=cardData.isCardNumberValid isExpireDataValid=cardData.isExpireDataValid isCvvValid=cardData.isCvvValid isZipValid=cardData.isZipValid isZipAvailable zip=cardData.zip /> } } }
1,954
10,672
hyperswitch-client-core
src/components/elements/PaymentSheetUi.res
.res
open ReactNative open Style open Validation @react.component let make = ( ~cardNumber, ~cvv, ~expireDate, ~onChangeCardNumber, ~onChangeCardExpire, ~onChangeCvv, ~isCardNumberValid, ~isExpireDataValid, ~isCardBrandSupported, ~isCvvValid, ~onScanCard, ~keyToTrigerButtonClickError, ~cardNetworks, ) => { let (nativeProp, _) = React.useContext(NativePropContext.nativePropContext) let isCardNumberValid = isCardNumberValid->Option.getOr(true) let isExpireDateValid = isExpireDataValid->Option.getOr(true) let isCardBrandSupported = isCardBrandSupported->Option.getOr(true) let isCvvValid = isCvvValid->Option.getOr(true) let isMaxCardLength = cardNumber->clearSpaces->String.length == maxCardLength(getCardBrand(cardNumber)) let (cardNumberIsFocus, setCardNumberIsFocus) = React.useState(_ => false) let (expireDateIsFocus, setExpireDateIsFocus) = React.useState(_ => false) let (cvvIsFocus, setCvvIsFocus) = React.useState(_ => false) let isCardNumberValid = { cardNumberIsFocus ? isCardNumberValid || !isMaxCardLength : isCardNumberValid } let isCardBrandSupported = { cardNumberIsFocus ? isCardBrandSupported || !isMaxCardLength : isCardBrandSupported } let isExpireDateValid = { expireDateIsFocus ? isExpireDateValid || expireDate->String.length < 7 : isExpireDateValid } let isCvvValid = { cvvIsFocus ? isCvvValid || !cvcNumberInRange(cvv, getCardBrand(cardNumber)) : isCvvValid } let { primaryColor, component, dangerColor, borderRadius, borderWidth, } = ThemebasedStyle.useThemeBasedStyle() let localeObject = GetLocale.useGetLocalObj() let cardRef = React.useRef(Nullable.null) let expireRef = React.useRef(Nullable.null) let cvvRef = React.useRef(Nullable.null) let cardBrand = getCardBrand(cardNumber) let showAlert = AlertHook.useAlerts() let logger = LoggerHook.useLoggerHook() let nullRef = React.useRef(Nullable.null) let errorMsgText = if !isCardNumberValid { Some(localeObject.inValidCardErrorText) } else if !isCardBrandSupported { Some(localeObject.unsupportedCardErrorText) } else if !isExpireDateValid { Some(localeObject.inValidExpiryErrorText) } else if !isCvvValid { Some(localeObject.inValidCVCErrorText) } else { None } let scanCardCallback = (scanCardReturnType: ScanCardModule.scanCardReturnStatus) => { switch scanCardReturnType { | Succeeded(data) => { onScanCard(data.pan, `${data.expiryMonth} / ${data.expiryYear}`, expireRef, cvvRef) logger(~logType=INFO, ~value="Succeeded", ~category=USER_EVENT, ~eventName=SCAN_CARD, ()) } | Cancelled => logger(~logType=WARNING, ~value="Cancelled", ~category=USER_EVENT, ~eventName=SCAN_CARD, ()) | Failed => { showAlert(~errorType="warning", ~message="Failed to scan card") logger(~logType=ERROR, ~value="Failed", ~category=USER_EVENT, ~eventName=SCAN_CARD, ()) } | _ => showAlert(~errorType="warning", ~message="Failed to scan card") } } React.useEffect1(() => { keyToTrigerButtonClickError != 0 ? { onChangeCardNumber(cardNumber, nullRef) onChangeCardExpire(expireDate, nullRef) onChangeCvv(cvv, nullRef) } : () None }, [keyToTrigerButtonClickError]) let getScanCardComponent = (isScanCardAvailable, cardNumber, cardNetworks) => { CustomInput.CustomIcon( <View style={array([viewStyle(~flexDirection=#row, ~alignItems=#center, ())])}> <CardSchemeComponent cardNumber cardNetworks /> <UIUtils.RenderIf condition={isScanCardAvailable && cardNumber === ""}> {<> <View style={viewStyle( ~backgroundColor=component.borderColor, ~marginLeft=10.->dp, ~marginRight=10.->dp, ~height=80.->pct, ~width=1.->dp, (), )} /> <CustomTouchableOpacity style={viewStyle( ~height=100.->pct, ~width=27.5->dp, ~display=#flex, ~alignItems=#"flex-start", ~justifyContent=#center, (), )} onPress={_pressEvent => { ScanCardModule.launchScanCard(scanCardCallback) logger( ~logType=INFO, ~value="Launch", ~category=USER_EVENT, ~eventName=SCAN_CARD, (), ) }}> <Icon name={"CAMERA"} height=25. width=25. fill=primaryColor /> </CustomTouchableOpacity> </>} </UIUtils.RenderIf> </View>, ) } <ErrorBoundary level=FallBackScreen.Screen rootTag=nativeProp.rootTag> <View style={viewStyle(~width=100.->pct, ~borderRadius, ())}> <View style={viewStyle(~width=100.->pct, ())}> <CustomInput name={TestUtils.cardNumberInputTestId} reference={None} // previously Some(cardRef->toInputRef) state=cardNumber setState={text => onChangeCardNumber(text, expireRef)} placeholder=nativeProp.configuration.placeholder.cardNumber keyboardType=#"number-pad" isValid=isCardNumberValid maxLength=Some(23) borderTopLeftRadius=borderRadius borderTopRightRadius=borderRadius borderBottomWidth=borderWidth borderLeftWidth=borderWidth borderRightWidth=borderWidth borderTopWidth=borderWidth borderBottomLeftRadius=0. borderBottomRightRadius=0. textColor={isCardNumberValid ? component.color : dangerColor} enableCrossIcon=false iconRight={getScanCardComponent(ScanCardModule.isAvailable, cardNumber, cardNetworks)} onFocus={() => { setCardNumberIsFocus(_ => true) onChangeCardNumber(cardNumber, nullRef) }} onBlur={() => { setCardNumberIsFocus(_ => false) }} onKeyPress={(ev: TextInput.KeyPressEvent.t) => { if ev.nativeEvent.key == "Backspace" && cardNumber == "" { switch cardRef.current->Nullable.toOption { | None => () | Some(ref) => ref->TextInputElement.blur } } }} animateLabel=localeObject.cardNumberLabel /> </View> <View style={viewStyle( ~width=100.->pct, ~flexDirection=localeObject.localeDirection === "rtl" ? #"row-reverse" : #row, (), )}> <View style={viewStyle(~width=50.->pct, ())}> <CustomInput name={TestUtils.expiryInputTestId} reference={Some(expireRef)} state=expireDate setState={text => onChangeCardExpire(text, cvvRef)} placeholder=nativeProp.configuration.placeholder.expiryDate keyboardType=#"number-pad" enableCrossIcon=false isValid=isExpireDateValid borderTopWidth=0.25 borderRightWidth=borderWidth borderTopLeftRadius=0. borderTopRightRadius=0. borderBottomRightRadius=0. borderBottomLeftRadius=borderRadius borderBottomWidth=borderWidth borderLeftWidth=borderWidth textColor={isExpireDateValid ? component.color : dangerColor} onFocus={() => { setExpireDateIsFocus(_ => true) onChangeCardExpire(expireDate, nullRef) }} onBlur={() => { setExpireDateIsFocus(_ => false) }} onKeyPress={(ev: TextInput.KeyPressEvent.t) => { if ev.nativeEvent.key == "Backspace" && expireDate == "" { switch cardRef.current->Nullable.toOption { | None => () | Some(ref) => ref->TextInputElement.focus } } }} animateLabel=localeObject.validThruText /> </View> <View style={viewStyle(~width=50.->pct, ())}> <CustomInput name={TestUtils.cvcInputTestId} reference={Some(cvvRef)} borderTopWidth=0.25 borderLeftWidth=0.5 borderTopLeftRadius=0. borderTopRightRadius=0. borderBottomLeftRadius=0. borderBottomRightRadius=borderRadius borderBottomWidth=borderWidth borderRightWidth=borderWidth secureTextEntry=true state=cvv isValid=isCvvValid setState={text => onChangeCvv(text, cvvRef)} placeholder=nativeProp.configuration.placeholder.cvv keyboardType=#"number-pad" enableCrossIcon=false onFocus={() => { setCvvIsFocus(_ => true) onChangeCvv(cvv, nullRef) }} onBlur={() => { setCvvIsFocus(_ => false) }} textColor={isCvvValid ? component.color : dangerColor} iconRight=CustomIcon({ checkCardCVC(cvv, cardBrand) ? <Icon name="cvvfilled" height=35. width=35. fill="black" /> : <Icon name="cvvempty" height=35. width=35. fill="black" /> }) onKeyPress={(ev: TextInput.KeyPressEvent.t) => { if ev.nativeEvent.key == "Backspace" && cvv == "" { switch expireRef.current->Nullable.toOption { | None => () | Some(ref) => ref->TextInputElement.focus } } }} animateLabel=localeObject.cvcTextLabel /> </View> </View> </View> {errorMsgText->Option.isSome ? <ErrorText text=errorMsgText /> : React.null} </ErrorBoundary> }
2,335
10,673
hyperswitch-client-core
src/components/elements/TubeSpinner.res
.res
open ReactNative open Style open ReactNativeSvg @react.component let make = (~loaderColor=?, ~size=?) => { let {iconColor} = ThemebasedStyle.useThemeBasedStyle() let iconColor = switch loaderColor { | Some(color) => color | None => iconColor } let size = switch size { | Some(size) => size | None => 180. } let rotateSpin = React.useRef(Animated.Value.create(0.)).current let angleSpinValue = Animated.Interpolation.interpolate( rotateSpin, { inputRange: [0., 1.], outputRange: ["0deg", "360deg"]->Animated.Interpolation.fromStringArray, }, ) React.useEffect1(() => { Animated.loop( Animated.timing( rotateSpin, { toValue: -1.->Animated.Value.Timing.fromRawValue, isInteraction: true, useNativeDriver: false, delay: 0., duration: 800., easing: Easing.linear, }, ), )->Animated.start() None }, [rotateSpin]) <View> <Animated.View style={viewStyle(~transform=[rotate(~rotate=angleSpinValue->Animated.StyleProp.angle)], ())}> <Svg width=size height=size viewBox="0 0 200 200"> <Defs> <RadialGradient id="a12" cx="0.66" fx="0.66" cy="0.3125" fy="0.3125" gradientTransform="scale(1.5)"> <Stop offset="0" stopColor={iconColor} /> <Stop offset="0.3" stopColor={iconColor} stopOpacity="0.9" /> <Stop offset="0.6" stopColor={iconColor} stopOpacity="0.6" /> <Stop offset="0.8" stopColor={iconColor} stopOpacity="0.3" /> <Stop offset="1" stopColor={iconColor} stopOpacity="0" /> </RadialGradient> </Defs> <Circle cx="100" cy="100" r="70" fill="none" stroke="url(#a12)" strokeWidth="15" strokeLinecap="round" strokeDasharray="200 1000" strokeDashoffset="0" origin="100, 100" /> <Circle cx="100" cy="100" r="70" fill="none" opacity="0.2" stroke={iconColor} strokeWidth="15" strokeLinecap="round" /> </Svg> </Animated.View> </View> }
635
10,674
hyperswitch-client-core
src/components/elements/HyperSwitchBranding.res
.res
open ReactNative open Style @react.component let make = () => { let (nativeProp, _) = React.useContext(NativePropContext.nativePropContext) <UIUtils.RenderIf condition={!nativeProp.hyperParams.disableBranding}> <Space /> <View style={viewStyle(~alignItems=#center, ())}> <View style={viewStyle( ~flexDirection=#row, ~display={#flex}, ~alignItems=#center, ~justifyContent=#center, (), )}> <TextWrapper textType={Heading}> {"powered by "->React.string} </TextWrapper> <TextWrapper textType={HeadingBold}> {"Hyperswitch"->React.string} </TextWrapper> </View> // <Icon // name={switch themeType { // | Light(_) => "hyperswitch" // | Dark(_) => "hyperswitchdark" // }} // width=180. // height=20. // /> <Space height=10. /> </View> </UIUtils.RenderIf> }
247
10,675
hyperswitch-client-core
src/components/elements/CardFormUi.res
.res
open ReactNative open Style open Validation @react.component let make = ( ~cardNumber, ~cvv, ~expireDate, ~isZipAvailable=false, ~zip, ~onChangeCardNumber, ~onChangeCardExpire, ~onChangeCvv, ~onChangeZip, ~isCardNumberValid, ~isExpireDataValid, ~isCvvValid, ~isZipValid, ) => { let (nativeProp, _) = React.useContext(NativePropContext.nativePropContext) let (buttomFlex, _) = React.useState(_ => Animated.Value.create(1.)) let isCardNumberValid = isCardNumberValid->Option.getOr(true) let isExpireDataValid = isExpireDataValid->Option.getOr(true) let isCvvValid = isCvvValid->Option.getOr(true) let isZipValid = isZipValid->Option.getOr(true) let isMaxCardLength = cardNumber->clearSpaces->String.length == maxCardLength(getCardBrand(cardNumber)) let (cardNumberIsFocus, setCardNumberIsFocus) = React.useState(_ => false) let isCardNumberValid = { cardNumberIsFocus ? isCardNumberValid || !isMaxCardLength : isCardNumberValid } let localeObject = GetLocale.useGetLocalObj() let {bgColor, component, dangerColor} = ThemebasedStyle.useThemeBasedStyle() let (cardNumInputFlex, _) = React.useState(_ => Animated.Value.create(1.)) let (expireInputFlex, _) = React.useState(_ => Animated.Value.create(1.)) let (cvvInputFlex, _) = React.useState(_ => Animated.Value.create(1.)) let (zipInputFlex, _) = React.useState(_ => Animated.Value.create(1.)) let cardRef = React.useRef(Nullable.null) let expireRef = React.useRef(Nullable.null) let cvvRef = React.useRef(Nullable.null) let zipRef = React.useRef(Nullable.null) let cardBrand = getCardBrand(cardNumber) let (loading, _) = React.useContext(LoadingContext.loadingContext) let animateFlex = (~flexval, ~value) => { Animated.timing( flexval, { toValue: {value->Animated.Value.Timing.fromRawValue}, isInteraction: true, useNativeDriver: false, delay: 0., }, )->Animated.start() } <ErrorBoundary level=FallBackScreen.Widget rootTag=nativeProp.rootTag> <View style={viewStyle( ~flex=1., ~alignItems=#center, ~justifyContent=#center, ~flexDirection=localeObject.localeDirection === "rtl" ? #"row-reverse" : #row, (), )}> <View style={array([ viewStyle( ~borderRadius=5., ~overflow=#hidden, ~paddingHorizontal=5.->dp, ~flex=1., ~alignItems=#center, ~justifyContent=#center, ~flexDirection=localeObject.localeDirection === "rtl" ? #"row-reverse" : #row, (), ), bgColor, ])}> {String.length(cardNumber) !== 0 ? String.length(cvv) == 0 ? <Icon name={cardBrand === "" ? "waitcard" : cardBrand} height=35. width=35. fill="black" /> : checkCardCVC(cvv, cardBrand) ? <Icon name="cvvfilled" height=35. width=35. fill="black" /> : <Icon name="cvvempty" height=35. width=35. fill="black" /> : <Icon name={"waitcard"} height=35. width=35. fill="black" />} // <Icon name={isCardNumberValid ? "cvvimage" : "error-card"} height=45. width=45. /> <Animated.View style={viewStyle(~flex={cardNumInputFlex->Animated.StyleProp.float}, ())}> <CustomInput fontSize=13. enableShadow=false reference={Some(cardRef)} state={cardNumberIsFocus ? cardNumber : cardNumber->String.sliceToEnd(~start=-4)} setState={text => onChangeCardNumber(text, expireRef)} placeholder={cardNumberIsFocus ? "1234 1234 1234 1234" : "1234 1234 1234 1234"->String.sliceToEnd(~start=-4) ++ "..."} keyboardType=#"number-pad" enableCrossIcon=false textColor={isCardNumberValid ? component.color : dangerColor} borderTopWidth=0. borderBottomWidth=0. borderRightWidth=0. borderLeftWidth=0. borderTopLeftRadius=0. borderTopRightRadius=0. borderBottomRightRadius=0. borderBottomLeftRadius=0. onFocus={() => { setCardNumberIsFocus(_ => true) animateFlex(~flexval=cvvInputFlex, ~value=0.1) animateFlex(~flexval=zipInputFlex, ~value=0.1) animateFlex(~flexval=expireInputFlex, ~value=0.5) }} onBlur={() => { setCardNumberIsFocus(_ => false) animateFlex(~flexval=cvvInputFlex, ~value=1.0) animateFlex(~flexval=expireInputFlex, ~value=1.0) animateFlex(~flexval=zipInputFlex, ~value=1.0) }} onKeyPress={(ev: TextInput.KeyPressEvent.t) => { if ev.nativeEvent.key == "Backspace" && cardNumber == "" { switch cardRef.current->Nullable.toOption { | None => () | Some(ref) => { ref->TextInputElement.blur animateFlex(~flexval=cvvInputFlex, ~value=1.0) animateFlex(~flexval=expireInputFlex, ~value=1.0) animateFlex(~flexval=zipInputFlex, ~value=1.0) } } } }} /> </Animated.View> <Animated.View style={viewStyle(~flex={expireInputFlex->Animated.StyleProp.float}, ())}> <CustomInput enableShadow=false fontSize=12. reference={Some(expireRef)} state=expireDate setState={text => onChangeCardExpire(text, cvvRef)} placeholder="MM / YY" keyboardType=#"number-pad" enableCrossIcon=false borderTopWidth=0. borderBottomWidth=0. textColor={isExpireDataValid ? component.color : dangerColor} borderRightWidth=0. borderLeftWidth=0. borderTopLeftRadius=0. borderTopRightRadius=0. borderBottomRightRadius=0. borderBottomLeftRadius=0. onFocus={() => { animateFlex(~flexval=cvvInputFlex, ~value=1.0) animateFlex(~flexval=expireInputFlex, ~value=1.0) animateFlex(~flexval=zipInputFlex, ~value=1.0) }} onBlur={() => {()}} onKeyPress={(ev: TextInput.KeyPressEvent.t) => { if ev.nativeEvent.key == "Backspace" && expireDate == "" { switch cardRef.current->Nullable.toOption { | None => () | Some(ref) => ref->TextInputElement.focus } } }} /> </Animated.View> <Animated.View style={viewStyle(~flex={cvvInputFlex->Animated.StyleProp.float}, ())}> <CustomInput fontSize=13. enableShadow=false reference={Some(cvvRef)} state=cvv setState={text => isZipAvailable ? onChangeCvv(text, zipRef) : onChangeCvv(text, cvvRef)} borderTopWidth=0. borderBottomWidth=0. borderRightWidth=0. borderLeftWidth=0. borderTopLeftRadius=0. borderTopRightRadius=0. textColor={isCvvValid ? component.color : dangerColor} borderBottomRightRadius=0. borderBottomLeftRadius=0. secureTextEntry=true placeholder="CVV" keyboardType=#"number-pad" enableCrossIcon=false onFocus={() => { animateFlex(~flexval=cvvInputFlex, ~value=1.0) animateFlex(~flexval=expireInputFlex, ~value=1.0) animateFlex(~flexval=zipInputFlex, ~value=1.0) }} onBlur={() => {()}} onKeyPress={(ev: TextInput.KeyPressEvent.t) => { if ev.nativeEvent.key == "Backspace" && cvv == "" { switch expireRef.current->Nullable.toOption { | None => () | Some(ref) => ref->TextInputElement.focus } } }} /> </Animated.View> {isZipAvailable ? <Animated.View style={viewStyle(~flex={zipInputFlex->Animated.StyleProp.float}, ())}> <CustomInput enableShadow=false fontSize=13. reference={Some(zipRef)} state=zip setState={text => onChangeZip(text, zipRef)} textColor={isZipValid ? component.color : dangerColor} keyboardType=#"number-pad" borderTopWidth=0. borderBottomWidth=0. borderRightWidth=0. borderLeftWidth=0. borderTopLeftRadius=0. borderTopRightRadius=0. borderBottomRightRadius=0. borderBottomLeftRadius=0. placeholder="ZIP" enableCrossIcon=false onFocus={() => { animateFlex(~flexval=cvvInputFlex, ~value=1.0) animateFlex(~flexval=expireInputFlex, ~value=1.0) animateFlex(~flexval=zipInputFlex, ~value=1.0) }} onBlur={() => {()}} onKeyPress={(ev: TextInput.KeyPressEvent.t) => { if ev.nativeEvent.key == "Backspace" && zip == "" { switch cvvRef.current->Nullable.toOption { | None => () | Some(ref) => ref->TextInputElement.focus } } }} /> </Animated.View> : React.null} <LoadingOverlay /> {switch loading { | PaymentSuccess => <View style={viewStyle(~width=100.->pct, ~position=#absolute, ~opacity=0.7, ())}> <Animated.View style={viewStyle( ~backgroundColor="mediumseagreen", ~flex=1., ~alignItems=#center, ~justifyContent=#center, ~flexDirection=#row, ~height=100.->pct, (), )}> <Animated.View style={viewStyle( ~flex={buttomFlex->Animated.StyleProp.float}, ~height=100.->dp, (), )} /> <Icon name="completepayment" width=40. height=20. /> </Animated.View> </View> | _ => React.null }} </View> </View> </ErrorBoundary> }
2,485
10,676
hyperswitch-client-core
src/components/elements/ScrollableCustomTopBar.res
.res
open ReactNative open Style module BottomTabList = { @react.component let make = ( ~item: PMListModifier.hoc, ~index: int, ~indexInFocus: int, ~setIndexToScrollParentFlatList, ) => { let isFocused = index == indexInFocus let routeName = item.name let isLoading = routeName == "loading" let { iconColor, component, primaryColor, borderRadius, bgColor, borderWidth, shadowColor, shadowIntensity, } = ThemebasedStyle.useThemeBasedStyle() let getShadowStyle = ShadowHook.useGetShadowStyle(~shadowIntensity, ~shadowColor, ()) <View style={viewStyle( ~flex=1., ~alignItems=#center, ~justifyContent=#center, ~marginRight=13.->dp, (), )}> <CustomTouchableOpacity onPress={_ => setIndexToScrollParentFlatList(index)} accessibilityRole=#button accessibilityState={Accessibility.state(~selected=isFocused, ())} accessibilityLabel=routeName testID=routeName activeOpacity=1. style={array([ bgColor, getShadowStyle, viewStyle( // ~backgroundColor={isFocused ? component.background : "transparent"}, ~backgroundColor={component.background}, ~borderWidth=isFocused ? borderWidth +. 1.5 : borderWidth, ~borderColor=isFocused ? primaryColor : component.borderColor, ~minWidth=115.->dp, ~padding=10.->dp, ~borderRadius, (), ), // bgColor, ])}> {isLoading ? <CustomLoader height="18" width="18" /> : <Icon name=routeName width=18. height=18. fill={isFocused ? primaryColor : iconColor} />} <Space height=5. /> {isLoading ? <CustomLoader height="18" width="40" /> : <TextWrapper text=routeName textType={switch isFocused { | true => CardTextBold | _ => CardText }} />} </CustomTouchableOpacity> </View> } } @react.component let make = ( ~hocComponentArr: array<PMListModifier.hoc>=[], ~indexInFocus, ~setIndexToScrollParentFlatList, ~height=75.->dp, ) => { let flatlistRef = React.useRef(Nullable.null) let logger = LoggerHook.useLoggerHook() let scrollToItem = () => { switch flatlistRef.current->Nullable.toOption { | Some(ref) => { let flatlistParam: FlatList.scrollToIndexParams = { animated: true, viewPosition: 0.5, index: {indexInFocus}, } ref->FlatList.scrollToIndex(flatlistParam) switch hocComponentArr[indexInFocus] { | Some(focusedComponent) => logger( ~logType=INFO, ~value=focusedComponent.name, ~category=USER_EVENT, ~paymentMethod=focusedComponent.name, ~eventName=PAYMENT_METHOD_CHANGED, (), ) | None => () } } | None => () } () } React.useEffect1(() => { if hocComponentArr->Array.length > 0 { scrollToItem() } None }, [indexInFocus]) <> <Space height=15. /> <View style={viewStyle(~height, ~paddingHorizontal=10.->dp, ())}> <FlatList ref={flatlistRef->ReactNative.Ref.value} keyboardShouldPersistTaps={#handled} data=hocComponentArr style={viewStyle(~flex=1., ~width=100.->pct, ())} showsHorizontalScrollIndicator=false keyExtractor={(_, i) => i->Int.toString} horizontal=true renderItem={({item, index}) => <BottomTabList key={index->Int.toString} item index indexInFocus setIndexToScrollParentFlatList />} /> </View> </> }
928
10,677
hyperswitch-client-core
src/components/elements/Klarna.res
.res
open ReactNative @react.component let make = ( ~launchKlarna: option<PaymentMethodListType.payment_method_types_pay_later>, ~return_url, ~klarnaSessionTokens: string, ~processRequest: (PaymentMethodListType.payment_method_types_pay_later, string) => unit, ) => { let (_paymentViewLoaded, setpaymentViewLoaded) = React.useState(_ => false) let (_token, _) = React.useState(_ => None) let paymentMethods = ["pay_later"] //["pay_now", "pay_later", "pay_over_time", "pay_in_parts"] let refs: React.ref<Nullable.t<KlarnaModule.element>> = React.useRef(Nullable.null) let handleSuccessFailure = AllPaymentHooks.useHandleSuccessFailure() React.useEffect1(() => { switch refs.current->Nullable.toOption { | None => () | Some(ref) => ref.initialize(klarnaSessionTokens, return_url) } None }, [refs]) let onInitialized = () => { switch refs.current->Nullable.toOption { | None => () | Some(ref) => ref.load() } } let onLoaded = () => { setpaymentViewLoaded(_ => true) } let buyButtonPressed = _ => { switch refs.current->Nullable.toOption { | None => () | Some(ref) => ref.authorize() } () } React.useEffect1(() => { if launchKlarna->Option.isSome { buyButtonPressed() } None }, [launchKlarna]) let onAuthorized = (event: KlarnaModule.event) => { let params = event.nativeEvent if (WebKit.platform == #ios || params.approved) && params.authToken !== None { switch launchKlarna { | Some(prop) => processRequest(prop, params.authToken->Option.getOr("")) | _ => handleSuccessFailure( ~apiResStatus={status: "failed", message: "", code: "", type_: ""}, ~closeSDK=false, (), ) } } else { switch params.errorMessage { | None => handleSuccessFailure(~apiResStatus={status: "failed", message: "", code: "", type_: ""}, ()) | Some(err) => handleSuccessFailure(~apiResStatus={status: err, message: "", code: "", type_: ""}, ()) } } } <ScrollView keyboardShouldPersistTaps=#handled pointerEvents=#none style={Style.viewStyle(~height=220.->Style.dp, ~borderRadius=15., ())}> {React.array( Array.map(paymentMethods, paymentMethod => { <KlarnaModule paymentMethod reference={refs} onInitialized onLoaded onAuthorized /> }), )} </ScrollView> }
621
10,678
hyperswitch-client-core
src/components/elements/FallBackScreen.res
.res
open ReactNative open Style type level = Top | Screen | Widget @react.component let make = (~error: Sentry.fallbackArg, ~level: level, ~rootTag) => { let {simplyExit} = HyperModule.useExitPaymentsheet() switch level { | Top => <SafeAreaView style={viewStyle(~flex=1., ~alignItems=#center, ~justifyContent=#"flex-end", ())}> <View style={viewStyle( ~width=100.->pct, ~alignItems=#center, ~backgroundColor="white", ~padding=20.->dp, (), )}> <View style={viewStyle(~alignItems=#"flex-end", ~width=100.->pct, ())}> <CustomTouchableOpacity onPress={_ => simplyExit(PaymentConfirmTypes.defaultCancelError, rootTag, false)}> <Icon name="close" fill="black" height=20. width=20. /> </CustomTouchableOpacity> </View> <View style={viewStyle(~flexDirection=#row, ~padding=20.->dp, ())}> <Icon name="errorIcon" fill="black" height=60. width=60. /> <View style={viewStyle(~flex=1., ~alignItems=#center, ~justifyContent=#center, ())}> <TextWrapper textType={ErrorTextBold}> {"Oops, something went wrong!"->React.string} </TextWrapper> <TextWrapper textType={ErrorText}> {"We'll be back with you shortly :)"->React.string} </TextWrapper> </View> </View> <Space /> <CustomTouchableOpacity onPress={_ => error.resetError()}> <Icon name="refresh" fill="black" height=32. width=32. /> </CustomTouchableOpacity> <Space /> </View> </SafeAreaView> | Screen => <View style={viewStyle( ~alignItems=#center, ~justifyContent=#center, ~width=100.->pct, ~padding=20.->dp, (), )}> <View style={viewStyle(~flexDirection=#row, ~backgroundColor="white", ())}> <Icon name="errorIcon" fill="black" height=60. width=60. /> <View style={viewStyle(~flex=1., ~alignItems=#center, ~justifyContent=#center, ())}> <TextWrapper textType={ErrorTextBold}> {"Oops, something went wrong!"->React.string} </TextWrapper> <TextWrapper textType={ErrorText}> {"Try another payment method :)"->React.string} </TextWrapper> </View> </View> </View> | Widget => <View style={viewStyle( ~flex=1., ~backgroundColor="white", ~alignItems=#center, ~justifyContent=#center, ~paddingHorizontal=40.->dp, (), )}> <View style={viewStyle(~flexDirection=#row, ~backgroundColor="white", ())}> <Icon name="errorIcon" fill="black" height=32. width=32. /> <View style={viewStyle(~flex=1., ~alignItems=#center, ~justifyContent=#center, ())}> <TextWrapper textType={ErrorTextBold}> {"Oops, something went wrong!"->React.string} </TextWrapper> </View> </View> </View> } }
782
10,679
hyperswitch-client-core
src/components/elements/RedirectionText.res
.res
open ReactNative open Style @react.component let make = () => { let {component} = ThemebasedStyle.useThemeBasedStyle() let localeObject = GetLocale.useGetLocalObj() <View style={viewStyle(~flexDirection=#row, ())}> <Icon name="redirection" width=40. height=35. fill=component.color /> <Space width=10. /> <View style={viewStyle(~width=90.->pct, ())}> <TextWrapper text=localeObject.redirectText textType=ModalText /> </View> </View> }
135
10,680
hyperswitch-client-core
src/components/elements/ButtonElement.res
.res
open ReactNative open Style open PaymentMethodListType type item = { linearGradientColorTuple: option<ThemebasedStyle.buttonColorConfig>, name: string, iconName: string, iconNameRight: option<string>, } @react.component let make = ( ~walletType: PaymentMethodListType.payment_method_types_wallet, ~sessionObject, ~confirm=false, ) => { let (allApiData, _) = React.useContext(AllApiDataContext.allApiDataContext) let (_, setLoading) = React.useContext(LoadingContext.loadingContext) let showAlert = AlertHook.useAlerts() let handleSuccessFailure = AllPaymentHooks.useHandleSuccessFailure() let (buttomFlex, _) = React.useState(_ => Animated.Value.create(1.)) let (nativeProp, _) = React.useContext(NativePropContext.nativePropContext) let savedPaymentMethodsData = switch allApiData.savedPaymentMethods { | Some(data) => data | _ => AllApiDataContext.dafaultsavePMObj } let logger = LoggerHook.useLoggerHook() let { paypalButonColor, googlePayButtonColor, applePayButtonColor, buttonBorderRadius, primaryButtonHeight, samsungPayButtonColor, } = ThemebasedStyle.useThemeBasedStyle() let fetchAndRedirect = AllPaymentHooks.useRedirectHook() // let (show, setShow) = React.useState(_ => true) let animateFlex = (~flexval, ~value, ~endCallback=() => (), ()) => { Animated.timing( flexval, { toValue: {value->Animated.Value.Timing.fromRawValue}, isInteraction: true, useNativeDriver: false, delay: 0., }, )->Animated.start(~endCallback=_ => {endCallback()}, ()) } let processRequest = ( ~payment_method_data, ~walletTypeAlt=?, ~email=?, ~shipping=None, ~billing=None, (), ) => { let walletType = switch walletTypeAlt { | Some(wallet) => wallet | None => walletType } let errorCallback = (~errorMessage, ~closeSDK, ()) => { logger( ~logType=INFO, ~value="", ~category=USER_EVENT, ~eventName=PAYMENT_FAILED, ~paymentMethod={walletType.payment_method_type}, ~paymentExperience=?walletType.payment_experience ->Array.get(0) ->Option.map(paymentExperience => getPaymentExperienceType(paymentExperience.payment_experience_type_decode) ), (), ) if !closeSDK { setLoading(FillingDetails) } handleSuccessFailure(~apiResStatus=errorMessage, ~closeSDK, ()) } let responseCallback = (~paymentStatus: LoadingContext.sdkPaymentState, ~status) => { logger( ~logType=INFO, ~value="", ~category=USER_EVENT, ~eventName=PAYMENT_DATA_FILLED, ~paymentMethod={walletType.payment_method_type}, ~paymentExperience=?walletType.payment_experience ->Array.get(0) ->Option.map(paymentExperience => getPaymentExperienceType(paymentExperience.payment_experience_type_decode) ), (), ) logger( ~logType=INFO, ~value="", ~category=USER_EVENT, ~eventName=PAYMENT_ATTEMPT, ~paymentMethod=walletType.payment_method_type, ~paymentExperience=?walletType.payment_experience ->Array.get(0) ->Option.map(paymentExperience => getPaymentExperienceType(paymentExperience.payment_experience_type_decode) ), (), ) switch paymentStatus { | PaymentSuccess => { logger( ~logType=INFO, ~value="", ~category=USER_EVENT, ~eventName=PAYMENT_SUCCESS, ~paymentMethod={walletType.payment_method_type}, ~paymentExperience=?walletType.payment_experience ->Array.get(0) ->Option.map(paymentExperience => getPaymentExperienceType(paymentExperience.payment_experience_type_decode) ), (), ) setLoading(PaymentSuccess) animateFlex( ~flexval=buttomFlex, ~value=0.01, ~endCallback=() => { setTimeout(() => { handleSuccessFailure(~apiResStatus=status, ()) }, 600)->ignore }, (), ) } | _ => handleSuccessFailure(~apiResStatus=status, ()) } } let body: redirectType = { client_secret: nativeProp.clientSecret, return_url: ?Utils.getReturnUrl(~appId=nativeProp.hyperParams.appId, ~appURL=allApiData.additionalPMLData.redirect_url), ?email, // customer_id: ?switch nativeProp.configuration.customer { // | Some(customer) => customer.id // | None => None // }, payment_method: walletType.payment_method, payment_method_type: walletType.payment_method_type, payment_experience: ?( walletType.payment_experience ->Array.get(0) ->Option.map(paymentExperience => paymentExperience.payment_experience_type) ), connector: ?( walletType.payment_experience ->Array.get(0) ->Option.map(paymentExperience => paymentExperience.eligible_connectors) ), payment_method_data, billing: ?billing->Option.orElse(nativeProp.configuration.defaultBillingDetails), shipping: ?shipping->Option.orElse(nativeProp.configuration.shippingDetails), payment_type: ?allApiData.additionalPMLData.paymentType, customer_acceptance: ?( if ( allApiData.additionalPMLData.mandateType->PaymentUtils.checkIfMandate && !savedPaymentMethodsData.isGuestCustomer ) { Some({ acceptance_type: "online", accepted_at: Date.now()->Date.fromTime->Date.toISOString, online: { user_agent: ?nativeProp.hyperParams.userAgent, }, }) } else { None } ), browser_info: { user_agent: ?nativeProp.hyperParams.userAgent, device_model: ?nativeProp.hyperParams.device_model, os_type: ?nativeProp.hyperParams.os_type, os_version: ?nativeProp.hyperParams.os_version, }, } fetchAndRedirect( ~body=body->JSON.stringifyAny->Option.getOr(""), ~publishableKey=nativeProp.publishableKey, ~clientSecret=nativeProp.clientSecret, ~errorCallback, ~responseCallback, ~paymentMethod=walletType.payment_method_type, ~paymentExperience=?walletType.payment_experience ->Array.get(0) ->Option.map(paymentExperience => getPaymentExperienceType(paymentExperience.payment_experience_type_decode) ), (), ) } let confirmPayPal = var => { let paymentData = var->PaymentConfirmTypes.itemToObjMapperJava switch paymentData.error { | "" => let json = paymentData.paymentMethodData->JSON.Encode.string let paymentData = [("token", json)]->Dict.fromArray->JSON.Encode.object let payment_method_data = [ ( walletType.payment_method, [(walletType.payment_method_type ++ "_sdk", paymentData)] ->Dict.fromArray ->JSON.Encode.object, ), ] ->Dict.fromArray ->JSON.Encode.object processRequest(~payment_method_data, ()) | "User has canceled" => setLoading(FillingDetails) showAlert(~errorType="warning", ~message="Payment was Cancelled") | err => showAlert(~errorType="error", ~message=err) } } let (countryStateData, _) = React.useContext(CountryStateDataContext.countryStateDataContext) let confirmGPay = var => { let paymentData = var->PaymentConfirmTypes.itemToObjMapperJava switch paymentData.error { | "" => let json = paymentData.paymentMethodData->JSON.parseExn let obj = json ->Utils.getDictFromJson ->GooglePayTypeNew.itemToObjMapper( switch countryStateData { | FetchData(data) | Localdata(data) => data.states | _ => Dict.make() }, ) let billingAddress = switch obj.paymentMethodData.info { | Some(info) => info.billing_address | None => None } let shippingAddress = obj.shippingDetails let payment_method_data = GooglePayTypeNew.getPaymentMethodData( walletType.required_field, ~shippingAddress, ~billingAddress, ~email=obj.email, ) payment_method_data->Dict.set( walletType.payment_method, [(walletType.payment_method_type, obj.paymentMethodData->Utils.getJsonObjectFromRecord)] ->Dict.fromArray ->JSON.Encode.object, ) processRequest( ~payment_method_data=payment_method_data->JSON.Encode.object, ~email=?obj.email, ~shipping=shippingAddress, ~billing=billingAddress, (), ) | "Cancel" => setLoading(FillingDetails) showAlert(~errorType="warning", ~message="Payment was Cancelled") | err => setLoading(FillingDetails) showAlert(~errorType="error", ~message=err) } } let confirmSamsungPay = ( status, addressFromSPay: option<SamsungPayType.addressCollectedFromSpay>, ) => { if status->ThreeDsUtils.isStatusSuccess { let response = status.message ->JSON.parseExn ->JSON.Decode.object ->Option.getOr(Dict.make()) let billingAddress = addressFromSPay->SamsungPayType.getAddressObj(SamsungPayType.BILLING_ADDRESS) let shippingAddress = addressFromSPay->SamsungPayType.getAddressObj(SamsungPayType.SHIPPING_ADDRESS) let obj = SamsungPayType.itemToObjMapper(response) let payment_method_data = GooglePayTypeNew.getPaymentMethodData( walletType.required_field, ~shippingAddress, ~billingAddress, ) payment_method_data->Dict.set( walletType.payment_method, [(walletType.payment_method_type, obj->Utils.getJsonObjectFromRecord)] ->Dict.fromArray ->JSON.Encode.object, ) processRequest( ~payment_method_data=payment_method_data->JSON.Encode.object, ~shipping=shippingAddress, ~billing=billingAddress, ~email=?billingAddress ->GooglePayTypeNew.getEmailAddress ->Option.orElse(shippingAddress->GooglePayTypeNew.getEmailAddress), (), ) } else { setLoading(FillingDetails) showAlert( ~errorType="warning", ~message=`Samsung Pay Error, Please try again ${status.message}`, ) } logger( ~logType=INFO, ~value=`SPAY result from native ${status.status->JSON.stringifyAny->Option.getOr("")}`, ~category=USER_EVENT, ~eventName=SAMSUNG_PAY, (), ) } let confirmApplePay = (var: dict<JSON.t>) => { logger( ~logType=DEBUG, ~value=walletType.payment_method_type, ~category=USER_EVENT, ~paymentMethod=walletType.payment_method_type, ~eventName=APPLE_PAY_CALLBACK_FROM_NATIVE, ~paymentExperience=?walletType.payment_experience ->Array.get(0) ->Option.map(paymentExperience => getPaymentExperienceType(paymentExperience.payment_experience_type_decode) ), (), ) switch var ->Dict.get("status") ->Option.getOr(JSON.Encode.null) ->JSON.Decode.string ->Option.getOr("") { | "Cancelled" => setLoading(FillingDetails) showAlert(~errorType="warning", ~message="Cancelled") | "Failed" => setLoading(FillingDetails) showAlert(~errorType="error", ~message="Failed") | "Error" => setLoading(FillingDetails) showAlert(~errorType="warning", ~message="Error") | _ => { let transaction_identifier = var->Dict.get("transaction_identifier")->Option.getOr(JSON.Encode.null) if ( transaction_identifier->Utils.getStringFromJson( "Simulated Identifier", ) == "Simulated Identifier" ) { setTimeout(() => { setLoading(FillingDetails) showAlert( ~errorType="warning", ~message="Apple Pay is not supported in Simulated Environment", ) }, 2000)->ignore } else { let payment_data = var->Dict.get("payment_data")->Option.getOr(JSON.Encode.null) let payment_method = var->Dict.get("payment_method")->Option.getOr(JSON.Encode.null) let billingAddress = var->GooglePayTypeNew.getBillingContact( "billing_contact", switch countryStateData { | FetchData(data) | Localdata(data) => data.states | _ => Dict.make() }, ) let shippingAddress = var->GooglePayTypeNew.getBillingContact( "shipping_contact", switch countryStateData { | FetchData(data) | Localdata(data) => data.states | _ => Dict.make() }, ) let paymentData = [ ("payment_data", payment_data), ("payment_method", payment_method), ("transaction_identifier", transaction_identifier), ] ->Dict.fromArray ->JSON.Encode.object let payment_method_data = GooglePayTypeNew.getPaymentMethodData( walletType.required_field, ~shippingAddress, ~billingAddress, ) payment_method_data->Dict.set( walletType.payment_method, [(walletType.payment_method_type, paymentData)] ->Dict.fromArray ->JSON.Encode.object, ) processRequest( ~payment_method_data=payment_method_data->JSON.Encode.object, ~shipping=shippingAddress, ~billing=billingAddress, ~email=?billingAddress ->GooglePayTypeNew.getEmailAddress ->Option.orElse(shippingAddress->GooglePayTypeNew.getEmailAddress), (), ) } } } } React.useEffect1(() => { switch walletType.payment_method_type_wallet { | APPLE_PAY => Window.registerEventListener("applePayData", confirmApplePay) | GOOGLE_PAY => Window.registerEventListener("googlePayData", confirmGPay) | _ => () } None }, [walletType.payment_method_type_wallet]) let pressHandler = () => { setLoading(ProcessingPayments(None)) logger( ~logType=INFO, ~value=walletType.payment_method_type, ~category=USER_EVENT, ~paymentMethod=walletType.payment_method_type, ~eventName=PAYMENT_METHOD_CHANGED, ~paymentExperience=?walletType.payment_experience ->Array.get(0) ->Option.map(paymentExperience => getPaymentExperienceType(paymentExperience.payment_experience_type_decode) ), (), ) setTimeout(_ => { if ( walletType.payment_experience ->Array.find(exp => exp.payment_experience_type_decode == INVOKE_SDK_CLIENT) ->Option.isSome ) { switch walletType.payment_method_type_wallet { | GOOGLE_PAY => HyperModule.launchGPay( GooglePayTypeNew.getGpayTokenStringified( ~obj=sessionObject, ~appEnv=nativeProp.env, ~requiredFields=walletType.required_field, ), confirmGPay, ) | PAYPAL => if ( sessionObject.session_token !== "" && WebKit.platform == #android && PaypalModule.payPalModule->Option.isSome ) { PaypalModule.launchPayPal(sessionObject.session_token, confirmPayPal) } else if ( walletType.payment_experience ->Array.find(exp => exp.payment_experience_type_decode == REDIRECT_TO_URL) ->Option.isSome ) { let redirectData = []->Dict.fromArray->JSON.Encode.object let payment_method_data = [ ( walletType.payment_method, [(walletType.payment_method_type ++ "_redirect", redirectData)] ->Dict.fromArray ->JSON.Encode.object, ), ] ->Dict.fromArray ->JSON.Encode.object let altPaymentExperience = walletType.payment_experience->Array.find(x => x.payment_experience_type_decode === REDIRECT_TO_URL ) let walletTypeAlt = { ...walletType, payment_experience: [ altPaymentExperience->Option.getOr({ payment_experience_type: "", payment_experience_type_decode: NONE, eligible_connectors: [], }), ], } // when session token for paypal is absent, switch to redirect flow processRequest(~payment_method_data, ~walletTypeAlt, ()) } | APPLE_PAY => if ( sessionObject.session_token_data == JSON.Encode.null || sessionObject.payment_request_data == JSON.Encode.null ) { setLoading(FillingDetails) showAlert(~errorType="warning", ~message="Waiting for Sessions API") } else { logger( ~logType=DEBUG, ~value=walletType.payment_method_type, ~category=USER_EVENT, ~paymentMethod=walletType.payment_method_type, ~eventName=APPLE_PAY_STARTED_FROM_JS, ~paymentExperience=?walletType.payment_experience ->Array.get(0) ->Option.map(paymentExperience => getPaymentExperienceType(paymentExperience.payment_experience_type_decode) ), (), ) let timerId = setTimeout(() => { setLoading(FillingDetails) showAlert(~errorType="warning", ~message="Apple Pay Error, Please try again") logger( ~logType=DEBUG, ~value=walletType.payment_method_type, ~category=USER_EVENT, ~paymentMethod=walletType.payment_method_type, ~eventName=APPLE_PAY_PRESENT_FAIL_FROM_NATIVE, ~paymentExperience=?walletType.payment_experience ->Array.get(0) ->Option.map( paymentExperience => getPaymentExperienceType(paymentExperience.payment_experience_type_decode), ), (), ) }, 5000) HyperModule.launchApplePay( [ ("session_token_data", sessionObject.session_token_data), ("payment_request_data", sessionObject.payment_request_data), ] ->Dict.fromArray ->JSON.Encode.object ->JSON.stringify, confirmApplePay, _ => { logger( ~logType=DEBUG, ~value=walletType.payment_method_type, ~category=USER_EVENT, ~paymentMethod=walletType.payment_method_type, ~eventName=APPLE_PAY_BRIDGE_SUCCESS, ~paymentExperience=?walletType.payment_experience ->Array.get(0) ->Option.map(paymentExperience => getPaymentExperienceType(paymentExperience.payment_experience_type_decode) ), (), ) }, _ => { clearTimeout(timerId) }, ) } | SAMSUNG_PAY => { logger( ~logType=INFO, ~value="Samsung Pay Button Clicked", ~category=USER_EVENT, ~eventName=SAMSUNG_PAY, (), ) SamsungPayModule.presentSamsungPayPaymentSheet(confirmSamsungPay) } | _ => { logger( ~logType=DEBUG, ~value=walletType.payment_method_type, ~category=USER_EVENT, ~paymentMethod=walletType.payment_method_type, ~eventName=NO_WALLET_ERROR, ~paymentExperience=?walletType.payment_experience ->Array.get(0) ->Option.map(paymentExperience => getPaymentExperienceType(paymentExperience.payment_experience_type_decode) ), (), ) setLoading(FillingDetails) showAlert(~errorType="warning", ~message="Waiting for Sessions API") } } } else if ( walletType.payment_experience ->Array.find(exp => exp.payment_experience_type_decode == REDIRECT_TO_URL) ->Option.isSome ) { let redirectData = []->Dict.fromArray->JSON.Encode.object let payment_method_data = [ ( walletType.payment_method, [(walletType.payment_method_type ++ "_redirect", redirectData)] ->Dict.fromArray ->JSON.Encode.object, ), ] ->Dict.fromArray ->JSON.Encode.object processRequest(~payment_method_data, ()) } else { logger( ~logType=DEBUG, ~value=walletType.payment_method_type, ~category=USER_EVENT, ~paymentMethod=walletType.payment_method_type, ~eventName=NO_WALLET_ERROR, ~paymentExperience=?walletType.payment_experience ->Array.get(0) ->Option.map(paymentExperience => getPaymentExperienceType(paymentExperience.payment_experience_type_decode) ), (), ) setLoading(FillingDetails) showAlert(~errorType="warning", ~message="Payment Method Unavailable") } }, 1000)->ignore } React.useEffect1(_ => { if confirm { pressHandler() } None }, [confirm]) <> <CustomButton borderRadius=buttonBorderRadius linearGradientColorTuple=?{switch walletType.payment_method_type_wallet { | PAYPAL => Some(Some(paypalButonColor)) | SAMSUNG_PAY => Some(Some(samsungPayButtonColor)) | _ => None }} leftIcon=CustomIcon(<Icon name=walletType.payment_method_type width=24. height=32. />) onPress={_ => pressHandler()} name=walletType.payment_method_type> {switch walletType.payment_method_type_wallet { | SAMSUNG_PAY => Some( <View style={viewStyle( ~display=#flex, ~flexDirection=#row, ~alignItems=#center, ~justifyContent=#center, ~width=100.->pct, ~height=100.->pct, (), )}> <Icon name=walletType.payment_method_type width=240. height=60. /> </View>, ) | APPLE_PAY => Some( <ApplePayButtonView style={viewStyle(~height=primaryButtonHeight->dp, ~width=100.->pct, ())} cornerRadius=buttonBorderRadius buttonType=nativeProp.configuration.appearance.applePay.buttonType buttonStyle=applePayButtonColor />, ) | GOOGLE_PAY => Some( <GooglePayButtonView allowedPaymentMethods={GooglePayTypeNew.getAllowedPaymentMethods( ~obj=sessionObject, ~requiredFields=walletType.required_field, )} style={viewStyle(~height=primaryButtonHeight->dp, ~width=100.->pct, ())} buttonType=nativeProp.configuration.appearance.googlePay.buttonType buttonStyle=googlePayButtonColor borderRadius={buttonBorderRadius} />, ) | PAYPAL => Some( <View style={viewStyle( ~flexDirection=#row, ~alignItems=#center, ~justifyContent=#center, (), )}> <Icon name=walletType.payment_method_type width=22. height=28. /> <Space width=10. /> <Icon name={walletType.payment_method_type ++ "2"} width=90. height=28. /> </View>, ) | _ => None }} </CustomButton> <Space height=12. /> </> }
5,036
10,681
hyperswitch-client-core
src/components/elements/LoadingOverlay.res
.res
open ReactNative open Style switch UIManager.setLayoutAnimationEnabledExperimental { | None => () | Some(setEnabled) => setEnabled(true) } @react.component let make = () => { let {bgColor, borderRadius} = ThemebasedStyle.useThemeBasedStyle() let (loading, _) = React.useContext(LoadingContext.loadingContext) let (nativeProps, _) = React.useContext(NativePropContext.nativePropContext) { switch loading { | ProcessingPayments(val) => <Portal> <View style={array([ viewStyle(~flex=1., ~opacity=val->Option.isSome ? 0.90 : 1.0, ~borderRadius, ()), val->Option.isSome ? bgColor : viewStyle(~backgroundColor="transparent", ()), ])}> {switch nativeProps.sdkState { | CardWidget | CustomWidget(_) => <View style={viewStyle(~flex=1., ~alignItems=#center, ~justifyContent=#center, ())}> // <HyperLoaderAnimation shapeSize=20. /> </View> | _ => <> // <Animated.View // style={viewStyle( // ~backgroundColor="#FFB000", // ~marginVertical=2.->dp, // ~borderRadius=10., // ~width={20.->pct}, // ~height=2.->dp, // ~transform=Animated.ValueXY.getTranslateTransform(sliderPosition), // (), // )} // /> <View style={viewStyle(~flex=1., ~justifyContent=#center, ~alignItems=#center, ())}> // <HyperLoaderAnimation /> {switch val { | Some(val) => val.showOverlay ? <PaymentSheetProcessingElement /> : React.null | None => React.null }} </View> </> }} </View> </Portal> | PaymentSuccess => switch nativeProps.sdkState { | PaymentSheet => <Portal> //<SuccessScreen /> <View style={array([viewStyle(~flex=1., ~opacity=0., ()), bgColor])}> <View style={viewStyle(~flex=1., ~justifyContent=#center, ~alignItems=#center, ())}> // <HyperLoaderAnimation /> </View> </View> </Portal> | _ => React.null } | _ => React.null } } }
536
10,682
hyperswitch-client-core
src/components/elements/CardSchemeComponent.res
.res
open ReactNative open Style module CardSchemeItem = { @react.component let make = (~onPress, ~item, ~index) => { <CustomTouchableOpacity key={index->Int.toString} onPress> <View style={viewStyle(~flexDirection=#row, ~alignItems=#center, ~paddingVertical=5.->dp, ())}> <Icon name={item} height=30. width=30. fill="black" fallbackIcon="waitcard" /> <Space /> <TextWrapper textType={CardText} text={item} /> </View> </CustomTouchableOpacity> } } module CardSchemeSelectionPopoverElement = { @react.component let make = (~eligibleCardSchemes, ~setCardBrand, ~toggleVisibility) => { let localeObject = GetLocale.useGetLocalObj() <> <TextWrapper textType={ModalTextLight} text={localeObject.selectCardBrand} /> <ScrollView keyboardShouldPersistTaps={#handled} contentContainerStyle={viewStyle(~flexGrow=0., ())}> <Space /> {eligibleCardSchemes ->Array.mapWithIndex((item, index) => <CardSchemeItem key={index->Int.toString} index={index} item onPress={_ => { setCardBrand(item) toggleVisibility() }} /> ) ->React.array} </ScrollView> </> } } @react.component let make = (~cardNumber, ~cardNetworks) => { let (cardData, setCardData) = React.useContext(CardDataContext.cardDataContext) let enabledCardSchemes = PaymentUtils.getCardNetworks(cardNetworks->Option.getOr(None)) let validCardBrand = Validation.getFirstValidCardScheme(~cardNumber, ~enabledCardSchemes) let cardBrand = validCardBrand === "" ? Validation.getCardBrand(cardNumber) : validCardBrand let (cardBrandIcon, setCardBrandIcon) = React.useState(_ => cardBrand === "" ? "waitcard" : cardBrand ) let (dropDownIconWidth, _) = React.useState(_ => Animated.Value.create(0.)) let matchedCardSchemes = cardNumber->Validation.clearSpaces->Validation.getAllMatchedCardSchemes let eligibleCardSchemes = Validation.getEligibleCoBadgedCardSchemes( ~matchedCardSchemes, ~enabledCardSchemes, ) let setCardBrand = cardBrand => { setCardBrandIcon(_ => cardBrand) setCardData(prev => { ...prev, selectedCoBadgedCardBrand: Some(cardBrand), }) } let isCardCoBadged = eligibleCardSchemes->Array.length > 1 let showCardSchemeDropDown = isCardCoBadged && cardNumber->Validation.clearSpaces->String.length >= 16 let selectedCardBrand = eligibleCardSchemes->Array.includes(cardData.selectedCoBadgedCardBrand->Option.getOr(cardBrand)) ? cardData.selectedCoBadgedCardBrand->Option.getOr(cardBrand) : cardBrand React.useEffect(() => { setCardBrandIcon(_ => selectedCardBrand === "" ? "waitcard" : selectedCardBrand) None }, (cardBrand, eligibleCardSchemes, selectedCardBrand)) React.useEffect(() => { setCardData(prev => { ...prev, selectedCoBadgedCardBrand: showCardSchemeDropDown ? Some(selectedCardBrand) : None, }) None }, (showCardSchemeDropDown, selectedCardBrand)) React.useEffect(() => { Animated.timing( dropDownIconWidth, { toValue: { (showCardSchemeDropDown ? 20. : 0.)->Animated.Value.Timing.fromRawValue }, isInteraction: true, useNativeDriver: false, delay: 0., duration: 200., easing: Easing.linear, }, )->Animated.start() None }, [showCardSchemeDropDown]) <View style={viewStyle(~paddingLeft=10.->dp, ~paddingVertical=10.->dp, ())}> <Tooltip disabled={!showCardSchemeDropDown} maxWidth=200. maxHeight=180. renderContent={toggleVisibility => <CardSchemeSelectionPopoverElement eligibleCardSchemes setCardBrand toggleVisibility />}> <View style={viewStyle( ~display=#flex, ~flexDirection=#row, ~justifyContent=#center, ~alignItems=#center, ~overflow=#hidden, (), )}> <Icon name={cardBrandIcon} height=30. width=30. fill="black" fallbackIcon="waitcard" /> <Animated.View style={viewStyle(~width=dropDownIconWidth->Animated.StyleProp.size, ())}> <UIUtils.RenderIf condition={showCardSchemeDropDown}> <View style={viewStyle(~marginLeft=8.->dp, ())}> <ChevronIcon width=12. height=12. fill="grey" /> </View> </UIUtils.RenderIf> </Animated.View> </View> </Tooltip> </View> }
1,139
10,683
hyperswitch-client-core
src/components/elements/ConfirmButton.res
.res
@react.component let make = ( ~loading: bool, ~isAllValuesValid: bool, ~handlePress: ReactNative.Event.pressEvent => unit, ~hasSomeFields=?, ~paymentMethod: string, ~paymentExperience=?, ~errorText=None, ) => { let (nativeProp, _) = React.useContext(NativePropContext.nativePropContext) let (allApiData, _) = React.useContext(AllApiDataContext.allApiDataContext) let localeObject = GetLocale.useGetLocalObj() <> {errorText->Belt.Option.isSome ? <ErrorText text={errorText} /> : React.null} {loading ? <> <CustomLoader /> <Space /> <HyperSwitchBranding /> </> : <ConfirmButtonAnimation isAllValuesValid handlePress paymentMethod ?hasSomeFields ?paymentExperience displayText={switch nativeProp.configuration.primaryButtonLabel { | Some(str) => str | None => allApiData.additionalPMLData.mandateType != NORMAL ? "Pay Now" : localeObject.payNowButton }} />} </> }
259
10,684
hyperswitch-client-core
src/components/elements/PaymentSheetProcessingElement.res
.res
open ReactNative open Style @react.component let make = () => { let {component} = ThemebasedStyle.useThemeBasedStyle() let (paymentProcessingText, setPaymentProcessingText) = React.useState(_ => ".") React.useEffect1(() => { let intervalId = setTimeout(() => { let newState = switch paymentProcessingText { | "." => ".." | ".." => "..." | "..." => "." | _ => "" } setPaymentProcessingText(_ => newState) }, 800) Some( () => { clearTimeout(intervalId) }, ) }, [paymentProcessingText]) <View style={array([ viewStyle( ~alignItems=#center, ~backgroundColor=component.background, ~justifyContent=#center, ~height=100.->pct, ~width=100.->pct, (), ), ])}> <TubeSpinner size=60. /> <Space /> <View style={viewStyle(~display=#flex, ~flexDirection=#row, ())}> <TextWrapper text={"Processing Your Payment"} textType={HeadingBold} /> <View style={viewStyle(~marginLeft=2.->dp, ~width=20.->dp, ())}> <TextWrapper text={paymentProcessingText} textType={HeadingBold} /> </View> </View> <Space height=15. /> <TextWrapper text="Please do not press back or close this screen" textType={ModalText} /> </View> }
347
10,685
hyperswitch-client-core
src/components/common/Pager.res
.res
open ReactNative open Style let deadZone = 12.0 @get external getValue: ReactNative.Animated.Value.t => float = "_value" @get external getOffset: ReactNative.Animated.Value.t => float = "_offset" type defaultTransitionSpec = { timing: (Animated.value<Animated.regular>, Animated.Value.Spring.config) => Animated.Animation.t, stiffness: float, damping: float, mass: float, overshootClamping: bool, } let defaultTransitionSpec = { timing: Animated.spring, stiffness: 1000.0, damping: 500.0, mass: 3.0, overshootClamping: true, } @react.component let make = ( ~layout: Event.ScrollEvent.dimensions, ~keyboardDismissMode: TabViewType.keyboardDismissMode=#auto, ~swipeEnabled=true, ~indexInFocus, ~routes, ~onIndexChange: int => unit, ~onSwipeStart=?, ~onSwipeEnd=?, ~children: ( ~addEnterListener: (int => unit) => unit => unit, ~jumpTo: int => unit, ~position: int, ~render: React.element => React.element, ~indexInFocus: int, ~routes: array<TabViewType.route>, ) => React.element, ~style=viewStyle(), ~animationEnabled=false, ~layoutDirection: TabViewType.localeDirection=#ltr, ) => { let panX = AnimatedValue.useAnimatedValue(0.0) let listenersRef = React.useRef([]) let navigationState: TabViewType.navigationState = {index: indexInFocus, routes} let navigationStateRef = React.useRef(navigationState) let layoutRef = React.useRef(layout) let onIndexChangeRef = React.useRef(onIndexChange) let currentIndexRef = React.useRef(indexInFocus) let pendingIndexRef = React.useRef(None) let swipeVelocityThreshold = 0.15 let swipeDistanceThreshold = layout.width /. 1.75 let jumpToIndex = React.useCallback2((index, animate) => { let offset = -.(index->Int.toFloat *. layoutRef.current.width) let {timing, stiffness, damping, mass, overshootClamping} = defaultTransitionSpec if animate { Animated.parallel( [ timing( panX, { toValue: offset->Animated.Value.Spring.fromRawValue, stiffness, damping, mass, overshootClamping, useNativeDriver: false, }, ), ], {stopTogether: false}, )->Animated.start(~endCallback=endResult => { if endResult.finished { onIndexChangeRef.current(index) pendingIndexRef.current = None } }, ()) pendingIndexRef.current = Some(index) } else { panX->Animated.Value.setValue(offset) onIndexChangeRef.current(index) pendingIndexRef.current = None } }, (animationEnabled, panX)) React.useEffectOnEveryRender(() => { navigationStateRef.current = navigationState layoutRef.current = layout onIndexChangeRef.current = onIndexChange None }) React.useEffect2(() => { let offset = -.(navigationStateRef.current.index->Int.toFloat *. layout.width) panX->Animated.Value.setValue(offset) None }, (layout.width, panX)) React.useEffect4(() => { if layout.width != 0. && currentIndexRef.current !== indexInFocus { if keyboardDismissMode == #auto { Keyboard.dismiss() } currentIndexRef.current = indexInFocus jumpToIndex(indexInFocus, animationEnabled) } None }, (jumpToIndex, keyboardDismissMode, layout.width, indexInFocus)) let isMovingHorizontally = (_, gestureState: PanResponder.gestureState) => { Math.abs(gestureState.dx) > Math.abs(gestureState.dy *. 2.0) && Math.abs(gestureState.vx) > Math.abs(gestureState.vy *. 2.0) } let canMoveScreen = (event, gestureState: PanResponder.gestureState) => { if !swipeEnabled { false } else { let diffX = if layoutDirection == #rtl { -.gestureState.dx } else { gestureState.dx } isMovingHorizontally(event, gestureState) && ((diffX >= deadZone && currentIndexRef.current > 0) || (diffX <= -.deadZone && currentIndexRef.current < routes->Array.length - 1)) } } let startGesture = (_, _) => { switch onSwipeStart { | Some(fun) => fun() | None => () } if keyboardDismissMode == #"on-drag" { Keyboard.dismiss() } panX->Animated.Value.stopAnimation() panX->Animated.Value.setOffset(panX->getValue) } let respondToGesture = (_, gestureState: PanResponder.gestureState) => { let diffX = if layoutDirection == #rtl { -.gestureState.dx } else { gestureState.dx } if ( (diffX > 0.0 && indexInFocus <= 0) || (diffX < 0.0 && indexInFocus >= routes->Array.length - 1) ) { () } else if layout.width != 0. { let position = (panX->getOffset +. diffX) /. -.layout.width let next = if position > indexInFocus->Int.toFloat { position->Math.ceil->Float.toInt } else { position->Math.floor->Float.toInt } if next !== indexInFocus { listenersRef.current->Array.forEach(listener => listener(next)) } } panX->Animated.Value.setValue(diffX) } let finishGesture = (_, gestureState: PanResponder.gestureState) => { panX->Animated.Value.flattenOffset switch onSwipeEnd { | Some(fun) => fun() | None => () } let currentIndex = switch pendingIndexRef.current { | Some(value) => value | None => currentIndexRef.current } let nextIndex = if ( Math.abs(gestureState.dx) > Math.abs(gestureState.dy) && Math.abs(gestureState.vx) > Math.abs(gestureState.vy) && (Math.abs(gestureState.dx) > swipeDistanceThreshold || Math.abs(gestureState.vx) > swipeVelocityThreshold) ) { let index = Math.round( Math.min( Math.max( 0., if layoutDirection == #rtl { currentIndex->Int.toFloat +. gestureState.dx /. Math.abs(gestureState.dx) } else { currentIndex->Int.toFloat -. gestureState.dx /. Math.abs(gestureState.dx) }, ), (routes->Array.length - 1)->Int.toFloat, ), ) currentIndexRef.current = index->Int.fromFloat Float.isFinite(index) ? index->Int.fromFloat : currentIndex } else { currentIndex } jumpToIndex(nextIndex, true) } let addEnterListener = React.useCallback1(listener => { listenersRef.current->Belt.Array.push(listener) () => { let index = listenersRef.current->Array.indexOf(listener) if index > -1 { listenersRef.current->Array.splice(~start=index, ~remove=1, ~insert=[]) } } }, []) let jumpTo = React.useCallback1(key => { let index = navigationStateRef.current.routes->Array.findIndex((route: TabViewType.route) => route.key === key ) jumpToIndex(index, false) onIndexChange(index) }, [jumpToIndex]) let panHandlers = PanResponder.create({ onMoveShouldSetPanResponder: canMoveScreen, onMoveShouldSetPanResponderCapture: canMoveScreen, onPanResponderGrant: startGesture, onPanResponderMove: respondToGesture, onPanResponderTerminate: finishGesture, onPanResponderRelease: finishGesture, onPanResponderTerminationRequest: (_, _) => true, })->PanResponder.panHandlers let maxTranslate = layout.width *. (routes->Array.length - 1)->Int.toFloat let translateX = Animated.Value.multiply( panX->Animated.Interpolation.interpolate({ inputRange: [-.maxTranslate, 0.0], outputRange: [-.maxTranslate, 0.0]->Animated.Interpolation.fromFloatArray, extrapolate: #clamp, }), if layoutDirection == #rtl { -1.->Animated.Value.create } else { 1.->Animated.Value.create }, ) let position = React.useMemo2(() => { if layout.width != 0. { Animated.Value.divide(panX, -.layout.width->Animated.Value.create) ->Animated.StyleProp.float ->Int.fromFloat } else { indexInFocus } }, (layout.width, panX)) let (height, setHeight) = React.useState(_ => 100.) let setDynamicHeight = React.useCallback1(height => { setHeight(_ => height) }, [setHeight]) children(~indexInFocus, ~routes, ~position, ~addEnterListener, ~jumpTo, ~render=children => { <Animated.View style={array([ viewStyle( ~flex=1., ~flexDirection=#row, ~alignItems=#stretch, ~transform=[Style.translateX(~translateX=translateX->Animated.StyleProp.float)], ~maxWidth=?WebKit.platform === #next ? 0.->dp->Some : None, ~width=?layout.width != 0. ? (routes->Array.length->Int.toFloat *. layout.width)->dp->Some : None, (), ), style, ])} onMoveShouldSetResponder={panHandlers->PanResponder.onMoveShouldSetResponder} onMoveShouldSetResponderCapture={panHandlers->PanResponder.onMoveShouldSetResponderCapture} onStartShouldSetResponder={panHandlers->PanResponder.onStartShouldSetResponder} onStartShouldSetResponderCapture={panHandlers->PanResponder.onStartShouldSetResponderCapture} onResponderReject={panHandlers->PanResponder.onResponderReject} onResponderGrant={panHandlers->PanResponder.onResponderGrant} onResponderRelease={panHandlers->PanResponder.onResponderRelease} onResponderMove={panHandlers->PanResponder.onResponderMove} onResponderTerminate={panHandlers->PanResponder.onResponderTerminate} onResponderStart={panHandlers->PanResponder.onResponderStart} onResponderTerminationRequest={panHandlers->PanResponder.onResponderTerminationRequest} onResponderEnd={panHandlers->PanResponder.onResponderEnd}> {React.Children.mapWithIndex(children, (child, i) => { switch routes[i] { | Some(route) => let focused = i === indexInFocus <View key={route.title ++ route.key->Int.toString} style=?{if layout.width != 0. { Some(viewStyle(~width=layout.width->dp, ~height=height->dp, ())) } else if focused { Some(StyleSheet.absoluteFill) } else { None }}> {focused || layout.width != 0. ? <TopTabScreenWraper setDynamicHeight isScreenFocus={indexInFocus == route.key}> child </TopTabScreenWraper> : React.null} </View> | None => React.null } })} </Animated.View> }) }
2,540
10,686
hyperswitch-client-core
src/components/common/SceneMap.res
.res
module SceneComponent = { @react.component let make = React.memo(( ~component: (~route: TabViewType.route, ~position: int, ~jumpTo: int => unit) => React.element, ~route: TabViewType.route, ~jumpTo: int => unit, ~position: int, ) => component(~route, ~position, ~jumpTo)) } let sceneMap = ( scenes: Map.t< int, (~route: TabViewType.route, ~position: int, ~jumpTo: int => unit) => React.element, >, ) => { (~route: TabViewType.route, ~position, ~layout as _, ~jumpTo) => { switch scenes->Map.get(route.key) { | Some(component) => <SceneComponent key={route.key->Int.toString} component route jumpTo position /> | None => React.null } } }
199
10,687
hyperswitch-client-core
src/components/common/SceneMap.js
.js
import * as React from 'react'; const SceneComponent = React.memo(({ component, ...rest }) => { return React.createElement(component, rest); } ); export function SceneMap(scenes) { return ({ route, jumpTo, position }) => ( <SceneComponent key={route.key} component={scenes[route.key]} route={route} jumpTo={jumpTo} position={position} /> ); }
97
10,688
hyperswitch-client-core
src/components/common/CustomButton.res
.res
open ReactNative open Style type buttonState = Normal | LoadingButton | Completed | Disabled type buttonType = Primary type iconType = CustomIcon(React.element) | NoIcon @react.component let make = ( ~loadingText="Loading..", ~buttonState: buttonState=Normal, ~text=?, ~name as _=?, ~buttonType: buttonType=Primary, ~leftIcon: iconType=NoIcon, ~rightIcon: iconType=NoIcon, ~onPress, ~linearGradientColorTuple=None, ~borderWidth=0., ~borderRadius=0., ~borderColor="#ffffff", ~children=None, ~testID=?, ) => { let fillAnimation = React.useRef(Animated.Value.create(0.)).current let { payNowButtonTextColor, payNowButtonShadowColor, payNowButtonShadowIntensity, component, primaryButtonHeight, } = ThemebasedStyle.useThemeBasedStyle() let getShadowStyle = ShadowHook.useGetShadowStyle( ~shadowIntensity=payNowButtonShadowIntensity, ~shadowColor=payNowButtonShadowColor, (), ) let backColor = switch linearGradientColorTuple { | Some(tuple) => tuple | None => switch buttonState { | Normal => ("#0048a0", "#0570de") | LoadingButton => ("#0048a0", "#0570de") | Completed => ("#0048a0", "#0570de") | Disabled => ("#808080", "#808080") } } let disabled = switch buttonState { | Normal => false | _ => true } let loaderIconColor = switch buttonType { | Primary => Some(payNowButtonTextColor) } let (bgColor1, _) = backColor let fillStyle = viewStyle( ~position=#absolute, ~top=0.->dp, ~bottom=0.->dp, ~right=0.->dp, ~opacity=0.4, ~backgroundColor={component.background}, (), ) let widthStyle = viewStyle( ~width=Animated.Interpolation.interpolate( fillAnimation, { inputRange: [0.0, 1.0], outputRange: ["95%", "0%"]->Animated.Interpolation.fromStringArray, }, )->Animated.StyleProp.size, (), ) let fillButton = () => { Animated.timing( fillAnimation, { toValue: 1.0->Animated.Value.Timing.fromRawValue, duration: 1800.0, useNativeDriver: false, }, )->Animated.start() } <View style={array([ getShadowStyle, viewStyle( ~height=primaryButtonHeight->dp, ~width=100.->pct, ~justifyContent=#center, ~alignItems=#center, ~borderRadius, ~borderWidth, ~borderColor, ~backgroundColor=bgColor1, (), ), ])}> <CustomTouchableOpacity disabled testID={testID->Option.getOr("")} style={array([ viewStyle( ~height=100.->pct, ~width=100.->pct, ~borderRadius, ~flex=1., ~flexDirection=#row, ~justifyContent=#center, ~alignItems=#center, (), ), ])} onPress={ev => { Keyboard.dismiss() onPress(ev) }}> {switch children { | Some(child) => child | _ => <> {switch leftIcon { | CustomIcon(element) => element | NoIcon => React.null }} {if buttonState == LoadingButton { fillButton() <Animated.View style={array([fillStyle, widthStyle])} /> } else { React.null }} {switch text { | Some(textStr) if textStr !== "" => <View style={viewStyle(~flex=1., ~alignItems=#center, ~justifyContent=#center, ())}> <TextWrapper text={switch buttonState { | LoadingButton => loadingText | Completed => "Complete" | _ => textStr }} // textType=CardText textType={ButtonTextBold} /> </View> | _ => React.null }} {if buttonState == LoadingButton || buttonState == Completed { <Loadericon iconColor=?loaderIconColor /> } else { switch rightIcon { | CustomIcon(element) => element | NoIcon => React.null } }} </> }} </CustomTouchableOpacity> </View> }
1,072
10,689
hyperswitch-client-core
src/components/common/CustomInput.res
.res
open ReactNative open Style type iconType = | NoIcon | CustomIcon(React.element) @react.component let make = ( ~state, ~setState, ~placeholder="Enter the text here", ~placeholderTextColor=None, ~width=100.->pct, ~height: float=46., ~secureTextEntry=false, ~keyboardType=#default, ~iconLeft: iconType=NoIcon, ~iconRight: iconType=NoIcon, ~multiline: bool=false, ~heading="", ~mandatory=false, ~reference=None, ~autoFocus=false, ~clearTextOnFocus=false, ~maxLength=None, ~onKeyPress=?, ~enableCrossIcon=true, ~textAlign=None, ~onPressIconRight=?, ~isValid=true, ~showEyeIconaftersecureTextEntry=false, ~borderTopWidth=1., ~borderBottomWidth=1., ~borderLeftWidth=1., ~borderRightWidth=1., ~borderTopLeftRadius=7., ~borderTopRightRadius=7., ~borderBottomLeftRadius=7., ~borderBottomRightRadius=7., ~onFocus=() => (), ~onBlur=() => (), ~textColor="black", ~editable=true, ~pointerEvents=#auto, ~fontSize=16., ~enableShadow=true, ~animate=true, ~animateLabel=?, ~name="", ) => { let { placeholderColor, bgColor, primaryColor, errorTextInputColor, normalTextInputBoderColor, component, shadowColor, shadowIntensity, placeholderTextSizeAdjust, } = ThemebasedStyle.useThemeBasedStyle() let getShadowStyle = ShadowHook.useGetShadowStyle(~shadowIntensity, ~shadowColor, ()) let (showPass, setShowPass) = React.useState(_ => secureTextEntry) let (isFocused, setIsFocused) = React.useState(_ => false) let logger = LoggerHook.useLoggerHook() let fontFamily = FontFamily.useCustomFontFamily() // let focusedTextInputBoderColor = "rgba(0, 153, 255, 1)" // let errorTextInputColor = "rgba(218, 14, 15, 1)" // let normalTextInputBoderColor = "rgba(204, 210, 226, 0.75)" // let _ = state != "" && secureTextEntry == false && enableCrossIcon let shadowStyle = enableShadow ? getShadowStyle : viewStyle() let animatedValue = React.useRef(Animated.Value.create(state != "" ? 1. : 0.)).current React.useEffect2(() => { Animated.timing( animatedValue, { toValue: if (isFocused || state != "") && animate { 1.->Animated.Value.Timing.fromRawValue } else { 0.->Animated.Value.Timing.fromRawValue }, duration: 200., useNativeDriver: false, }, )->Animated.start() None }, (isFocused, state)) <View style={viewStyle(~width=100.->pct, ())}> {heading != "" ? <TextWrapper textType={PlaceholderText}> {React.string(heading)} {mandatory ? <TextWrapper textType={ErrorText}> {" *"->React.string} </TextWrapper> : React.null} </TextWrapper> : React.null} <View style={array([ bgColor, viewStyle( ~backgroundColor=component.background, ~borderTopWidth, ~borderBottomWidth, ~borderLeftWidth, ~borderRightWidth, ~borderTopLeftRadius, ~borderTopRightRadius, ~borderBottomLeftRadius, ~borderBottomRightRadius, ~height=height->dp, ~flexDirection=#row, ~borderColor=isValid ? isFocused ? primaryColor : normalTextInputBoderColor : errorTextInputColor, ~width, ~paddingHorizontal=13.->dp, ~alignItems=#center, ~justifyContent=#center, (), ), shadowStyle, // bgColor, ])}> {switch iconLeft { | CustomIcon(element) => <View style={viewStyle(~paddingRight=10.->dp, ())}> element </View> | NoIcon => React.null }} <View style={viewStyle( ~flex=1., ~position=#relative, ~height=100.->pct, ~justifyContent={ animate ? #"flex-end" : #center }, (), )}> {animate ? <Animated.View pointerEvents=#none style={viewStyle( ~top=0.->dp, ~position=#absolute, ~height=animatedValue ->Animated.Interpolation.interpolate({ inputRange: [0., 1.], outputRange: ["100%", "40%"]->Animated.Interpolation.fromStringArray, }) ->Animated.StyleProp.size, ~justifyContent=#center, (), )}> <Animated.Text style={array([ textStyle( ~fontFamily, ~fontWeight=if isFocused || state != "" { #500 } else { #normal }, ~fontSize=animatedValue ->Animated.Interpolation.interpolate({ inputRange: [0., 1.], outputRange: [ fontSize +. placeholderTextSizeAdjust, fontSize +. placeholderTextSizeAdjust -. 5., ]->Animated.Interpolation.fromFloatArray, }) ->Animated.StyleProp.float, ~color=placeholderTextColor->Option.getOr(placeholderColor), (), ), ])}> {React.string({ if isFocused || state != "" { animateLabel->Option.getOr(placeholder) ++ (mandatory ? "*" : "") } else { placeholder } })} </Animated.Text> </Animated.View> : React.null} <TextInput ref=?{switch reference { | Some(ref) => ref->ReactNative.Ref.value->Some | None => None }} style={array([ textStyle( ~fontStyle=#normal, ~color=textColor, ~fontFamily, ~fontSize={fontSize +. placeholderTextSizeAdjust}, ~textAlign?, (), ), viewStyle(~padding=0.->dp, ~height=(height -. 10.)->dp, ~width=100.->pct, ()), ])} testID=name secureTextEntry=showPass autoCapitalize=#none multiline autoCorrect={false} clearTextOnFocus ?maxLength placeholder=?{animate ? None : Some(placeholder)} placeholderTextColor={placeholderTextColor->Option.getOr(placeholderColor)} value={state} ?onKeyPress onChangeText={text => setState(text)} keyboardType autoFocus autoComplete={#off} textContentType={#oneTimeCode} onFocus={_ => { setIsFocused(_ => true) onFocus() logger(~logType=INFO, ~value=placeholder, ~category=USER_EVENT, ~eventName=FOCUS, ()) }} onBlur={_ => { // TODO: remove invalid input (string with only space) eg: " " state->String.trim == "" ? setState("") : () onBlur() setIsFocused(_ => false) logger(~logType=INFO, ~value=placeholder, ~category=USER_EVENT, ~eventName=BLUR, ()) }} editable pointerEvents /> </View> <CustomTouchableOpacity activeOpacity=1. onPress=?onPressIconRight> {switch iconRight { | NoIcon => React.null | CustomIcon(element) => <View style={viewStyle(~flexDirection=#row, ~alignContent=#"space-around", ())}> element </View> }} </CustomTouchableOpacity> {secureTextEntry && showEyeIconaftersecureTextEntry ? { <CustomTouchableOpacity style={viewStyle(~height=100.->pct, ~justifyContent=#center, ~paddingLeft=5.->dp, ())} onPress={_ => {setShowPass(prev => !prev)}}> <TextWrapper textType={PlaceholderText}> {"eye"->React.string} </TextWrapper> </CustomTouchableOpacity> } : React.null} </View> </View> }
1,887
10,690
hyperswitch-client-core
src/components/common/TextWithLine.res
.res
open ReactNative open Style @react.component let make = (~text) => { <View style={viewStyle(~alignItems=#center, ~justifyContent=#center, ~flexDirection=#row, ())}> <View style={viewStyle( ~height=1.->dp, ~marginHorizontal=10.->dp, ~backgroundColor="#CCCCCC", ~flex=1., (), )} /> <TextWrapper text textType=ModalText /> <View style={viewStyle( ~height=1.->dp, ~marginHorizontal=10.->dp, ~backgroundColor="#CCCCCC", ~flex=1., (), )} /> </View> }
158
10,691
hyperswitch-client-core
src/components/common/ReImage.res
.res
open ReactNative open Style @react.component let make = (~uri, ~style=viewStyle(~width=33.->dp, ~height=33.->dp, ())) => { <Image style source={Image.Source.fromUriSource({uri: uri})} /> }
62
10,692
hyperswitch-client-core
src/components/common/CustomSelectBox.res
.res
@react.component let make = (~initialIconName, ~updateIconName, ~isSelected, ~fillIcon) => { let {primaryColor} = ThemebasedStyle.useThemeBasedStyle() let fill = fillIcon ? Some(primaryColor) : None switch updateIconName { | None => <Icon name={initialIconName} height=18. width=18. ?fill /> | Some(updateIconName) => <> <Icon name={initialIconName} height=18. width=18. ?fill style={ReactNative.Style.viewStyle(~display=isSelected ? #flex : #none, ())} /> <Icon name={updateIconName} height=18. width=18. ?fill style={ReactNative.Style.viewStyle(~display=isSelected ? #none : #flex, ())} /> </> } }
202
10,693
hyperswitch-client-core
src/components/common/CustomView.res
.res
open ReactNative open Style type modalPosition = [#center | #top | #bottom] @react.component let make = ( ~onDismiss=() => (), ~children, ~closeOnClickOutSide=true, ~modalPosition=#bottom, ~bottomModalWidth=100.->pct, (), ) => { let (viewPortContants, _) = React.useContext(ViewportContext.viewPortContext) let modalPosStyle = array([ viewStyle(~flex=1., ~width=100.->pct, ~height=100.->pct, ~alignItems=#center, ()), switch modalPosition { | #center => viewStyle(~alignItems=#center, ~justifyContent=#center, ()) | #top => viewStyle(~alignItems=#center, ~justifyContent=#"flex-start", ()) | #bottom => viewStyle(~alignItems=#center, ~justifyContent=#"flex-end", ()) }, ]) let (loading, _) = React.useContext(LoadingContext.loadingContext) let disableClickOutside = switch loading { | FillingDetails => !closeOnClickOutSide | _ => true } // let (locationY, setLocationY) = React.useState(_ => 0.) <View style=modalPosStyle> <CustomTouchableOpacity style={viewStyle(~flex=1., ~width=100.->pct, ~flexGrow=1., ())} disabled=disableClickOutside onPress={_ => { if closeOnClickOutSide { onDismiss() } }} /> // <TouchableWithoutFeedback // onPressIn={e => setLocationY(_ => e.nativeEvent.locationY)} // onPressOut={e => { // if e.nativeEvent.locationY->Float.toInt - locationY->Float.toInt > 20 { // onDismiss() // } // }}> <CustomKeyboardAvoidingView style={viewStyle( ~width=bottomModalWidth, ~borderRadius=15., ~borderBottomLeftRadius=0., ~borderBottomRightRadius=0., ~overflow=#hidden, ~maxHeight=viewPortContants.maxPaymentSheetHeight->pct, ~alignItems=#center, ~justifyContent=#center, (), )}> <SafeAreaView /> {children} </CustomKeyboardAvoidingView> // </TouchableWithoutFeedback> </View> } module Wrapper = { @react.component let make = (~onModalClose, ~width=100.->pct, ~children=React.null) => { let {bgColor, sheetContentPadding} = ThemebasedStyle.useThemeBasedStyle() let (viewPortContants, _) = React.useContext(ViewportContext.viewPortContext) <ScrollView contentContainerStyle={viewStyle( ~minHeight=250.->dp, ~paddingHorizontal=sheetContentPadding->dp, ~paddingTop=sheetContentPadding->dp, ~paddingBottom=viewPortContants.navigationBarHeight->dp, (), )} keyboardShouldPersistTaps={#handled} style={array([viewStyle(~flexGrow=1., ~width, ()), bgColor])}> <ModalHeader onModalClose /> children </ScrollView> } }
728
10,694
hyperswitch-client-core
src/components/common/CustomRadioButton.res
.res
open ReactNative open Style @react.component let make = (~size=18., ~selected, ~color="#006DF9") => { <View style={viewStyle( ~height=size->dp, ~width=size->dp, ~borderRadius=size /. 2., ~borderWidth=1., ~borderColor=selected ? color : "lightgray", ~alignItems=#center, ~justifyContent=#center, (), )}> <View style={viewStyle( ~height=(size -. 8.)->dp, ~width=(size -. 8.)->dp, ~borderRadius=size /. 2., ~backgroundColor=selected ? color : "transparent", (), )} /> </View> }
171
10,695
hyperswitch-client-core
src/components/common/Space.res
.res
open ReactNative open Style @react.component let make = (~width=15., ~height=15.) => { <View style={viewStyle(~height=height->dp, ~width=width->dp, ())} /> }
53
10,696
hyperswitch-client-core
src/components/common/SceneView.res
.res
open ReactNative open Style type handleEnter = int => unit @live type timerFunctionType = {unsubscribe: option<int => int>, timer: option<timeoutId>} @react.component let make = ( ~children: (~loading: bool) => React.element, ~position as _, ~jumpTo as _, ~indexInFocus, ~lazy_, ~layout: Event.ScrollEvent.dimensions, ~index, ~lazyPreloadDistance, ~addEnterListener: handleEnter => unit => unit, ~style=?, ) => { let (isLoading, setIsLoading) = React.useState(() => Math.Int.abs(indexInFocus - index) > lazyPreloadDistance ) if isLoading && Math.Int.abs(indexInFocus - index) <= lazyPreloadDistance { setIsLoading(_ => false) } React.useEffect4(() => { let handleEnter: handleEnter = value => { if value === index { setIsLoading(prevState => { if prevState { false } else { prevState } }) } } let (unsubscribe, timer) = switch (lazy_, isLoading) { | (true, true) => (Some(addEnterListener(handleEnter)), None) | (_, true) => (None, Some(setTimeout(() => setIsLoading(_ => false), 0))) | _ => (None, None) } Some( _ => { switch unsubscribe { | Some(fun) => fun() | _ => () } switch timer { | Some(time) => clearTimeout(time) | None => () } }, ) }, (addEnterListener, index, isLoading, lazy_)) let focused = indexInFocus === index <View accessibilityElementsHidden={!focused} importantForAccessibility={focused ? #auto : #"no-hide-descendants"} style={switch style { | Some(style) => array([viewStyle(~overflow=#hidden, ~width=layout.width->dp, ()), style]) | None => viewStyle(~overflow=#hidden, ~width=layout.width->dp, ()) }}> {focused || layout.width != 0. ? children(~loading=false) : React.null} </View> }
485
10,697
hyperswitch-client-core
src/components/common/Loadericon.res
.res
open ReactNative open Style @react.component let make = (~iconColor=?, ~size=ActivityIndicator.Small) => { let {component} = ThemebasedStyle.useThemeBasedStyle() let loderColor = switch iconColor { | Some(color) => color | None => component.color } <ActivityIndicator animating={true} size color=loderColor style={viewStyle(~marginEnd=10.->dp, ())} /> }
102
10,698
hyperswitch-client-core
src/components/common/TextWrapper.res
.res
open ReactNative open Style type textType = | HeadingBold | Heading | Subheading | SubheadingBold | ModalTextLight | ModalText | ModalTextBold | PlaceholderText | PlaceholderTextBold | ErrorText | ErrorTextBold | ButtonText | ButtonTextBold | LinkText | LinkTextBold | CardTextBold | CardText @react.component let make = ( ~text=?, ~textType: textType, ~children: option<React.element>=?, ~overrideStyle=None, ~ellipsizeMode: ReactNative.Text.ellipsizeMode=#tail, ~numberOfLines: int=0, ) => { let { textPrimary, textSecondary, textSecondaryBold, component, headingTextSizeAdjust, subHeadingTextSizeAdjust, placeholderTextSizeAdjust, buttonTextSizeAdjust, errorTextSizeAdjust, linkTextSizeAdjust, modalTextSizeAdjust, cardTextSizeAdjust, payNowButtonTextColor, errorTextInputColor, errorMessageSpacing, } = ThemebasedStyle.useThemeBasedStyle() let fontFamily = FontFamily.useCustomFontFamily() let renderStyle = switch textType { | Heading => array([ textSecondaryBold, textStyle(~fontSize=17. +. headingTextSizeAdjust, ~letterSpacing=0.3, ()), ]) | HeadingBold => array([ textSecondaryBold, textStyle(~fontSize=17. +. headingTextSizeAdjust, ~fontWeight=#600, ~letterSpacing=0.3, ()), ]) | Subheading => array([textSecondaryBold, textStyle(~fontSize=15. +. subHeadingTextSizeAdjust, ())]) | SubheadingBold => array([ textSecondary, textStyle(~fontSize=15. +. subHeadingTextSizeAdjust, ~fontWeight=#500, ()), ]) | ModalTextLight => array([textStyle(~fontSize=14. +. modalTextSizeAdjust, ~fontWeight=#500, ()), textSecondary]) | ModalText => array([textStyle(~fontSize=14. +. modalTextSizeAdjust, ()), textSecondaryBold]) | ModalTextBold => array([ textStyle(~fontSize=14. +. modalTextSizeAdjust, ~fontWeight=#500, ()), textSecondaryBold, ]) | PlaceholderText => array([ textStyle( ~fontStyle=#normal, ~fontSize=12. +. placeholderTextSizeAdjust, ~marginBottom=2.5->pct, (), ), textPrimary, ]) | PlaceholderTextBold => array([ textStyle( ~fontStyle=#normal, ~fontSize=12. +. placeholderTextSizeAdjust, ~fontWeight=#500, ~marginBottom=2.5->pct, (), ), textPrimary, ]) | ErrorText => array([ textStyle( ~color={errorTextInputColor}, ~fontFamily, ~fontSize=12. +. errorTextSizeAdjust, ~marginTop=errorMessageSpacing->dp, (), ), ]) | ErrorTextBold => array([ textStyle( ~color={errorTextInputColor}, ~fontFamily, ~fontSize=12. +. errorTextSizeAdjust, ~fontWeight=#500, (), ), ]) | ButtonText => array([textStyle(~color=payNowButtonTextColor, ~fontSize=17. +. buttonTextSizeAdjust, ())]) | ButtonTextBold => array([ textStyle( ~color=payNowButtonTextColor, ~fontSize=17. +. buttonTextSizeAdjust, ~fontWeight=#600, (), ), ]) | LinkText => array([textStyle(~fontSize=14. +. linkTextSizeAdjust, ()), textPrimary]) | LinkTextBold => array([textStyle(~fontSize=14. +. linkTextSizeAdjust, ~fontWeight=#500, ()), textPrimary]) | CardTextBold => array([ textStyle(~fontSize=14. +. cardTextSizeAdjust, ~fontWeight=#600, ~color=component.color, ()), ]) | CardText => array([ textStyle(~fontSize=12. +. cardTextSizeAdjust, ~fontWeight=#400, ~color=component.color, ()), ]) } // let textTypeString = switch textType { // | HeadingBold => "SmallHeadingBold" // | Subheading => "Subheading" // | SubheadingBold => "SubheadingBold" // | ModalText => "ModalText" // | ModalTextBold => "ModalTextBold" // | CustomCssText(_) => "CustomCssText" // | CardText => "CardText" // | TextActive => "TextActive" // } let overrideStyle = switch overrideStyle { | Some(val) => val | None => viewStyle() } <Text style={array([textStyle(~fontFamily, ()), renderStyle, overrideStyle])} ellipsizeMode numberOfLines> {switch text { | Some(text) => React.string(text) | None => React.null }} {switch children { | Some(children) => children | None => React.null }} </Text> }
1,205
10,699
hyperswitch-client-core
src/components/common/CustomPicker.res
.res
open ReactNative open Style type customPickerType = { label: string, value: string, icon?: string, } @react.component let make = ( ~value, ~setValue, ~borderBottomLeftRadius=0., ~borderBottomRightRadius=0., ~borderBottomWidth=0., ~disabled=false, ~placeholderText, ~items: array<customPickerType>, ~isValid=true, ~isLoading=false, ~isCountryStateFields=false, ) => { let (isModalVisible, setIsModalVisible) = React.useState(_ => false) let (searchInput, setSearchInput) = React.useState(_ => None) let (_, fetchCountryStateData) = React.useContext(CountryStateDataContext.countryStateDataContext) React.useEffect1(() => { if isCountryStateFields { fetchCountryStateData() } None }, [isCountryStateFields]) let pickerRef = React.useRef(Nullable.null) let searchInputRef = React.useRef(Nullable.null) let { bgColor, component, iconColor, borderRadius, borderWidth, } = ThemebasedStyle.useThemeBasedStyle() let (nativeProps, _) = React.useContext(NativePropContext.nativePropContext) let {bgTransparentColor} = ThemebasedStyle.useThemeBasedStyle() let transparentBG = nativeProps.sdkState == PaymentSheet ? bgTransparentColor : viewStyle() React.useEffect1(() => { setSearchInput(_ => None) None }, [isModalVisible]) <View> <CustomTouchableOpacity disabled activeOpacity=1. onPress={_ => setIsModalVisible(prev => !prev)}> <CustomInput state={switch items->Array.find(x => x.value == value->Option.getOr("")) { | Some(y) => y.label | _ => value->Option.getOr("") }} setState={_ => ()} borderBottomLeftRadius borderBottomRightRadius borderBottomWidth isValid borderTopWidth=borderWidth borderLeftWidth=borderWidth borderRightWidth=borderWidth borderTopLeftRadius=borderRadius borderTopRightRadius=borderRadius placeholder=placeholderText editable=false textColor=component.color iconRight=CustomIcon( <CustomTouchableOpacity disabled onPress={_ => setIsModalVisible(prev => !prev)}> <ChevronIcon width=13. height=13. fill=iconColor /> </CustomTouchableOpacity>, ) pointerEvents={#none} /> </CustomTouchableOpacity> <Modal visible={isModalVisible} transparent={true} animationType=#slide onShow={() => { let _ = setTimeout(() => { switch searchInputRef.current->Nullable.toOption{ | Some(input) => input->TextInputElement.focus | None => () } }, 300) }}> <SafeAreaView /> <View style={array([viewStyle(~flex=1., ~paddingTop=24.->dp, ()), transparentBG])}> <View style={array([ viewStyle( ~flex=1., ~width=100.->pct, ~backgroundColor=component.background, ~justifyContent=#center, ~alignItems=#center, ~borderRadius=10., ~padding=15.->dp, ~paddingHorizontal=20.->dp, (), ), bgColor, ])}> <View style={viewStyle( ~flexDirection=#row, ~width=100.->pct, ~alignItems=#center, ~justifyContent=#"space-between", (), )}> <TextWrapper text=placeholderText textType={HeadingBold} /> <CustomTouchableOpacity onPress={_ => setIsModalVisible(prev => !prev)} style={viewStyle(~padding=14.->dp, ())}> <Icon name="close" width=20. height=20. fill=iconColor /> </CustomTouchableOpacity> </View> <CustomInput reference={Some(searchInputRef)} placeholder={"Search " ++ placeholderText} // MARK: add Search to locale state={searchInput->Option.getOr("")} setState={val => { setSearchInput(_ => Some(val)) }} keyboardType=#default textColor=component.color borderBottomLeftRadius=borderRadius borderBottomRightRadius=borderRadius borderTopLeftRadius=borderRadius borderTopRightRadius=borderRadius borderTopWidth=borderWidth borderBottomWidth=borderWidth borderLeftWidth=borderWidth borderRightWidth=borderWidth /> <Space /> {isLoading ? <ActivityIndicator size={Large} color=iconColor style={viewStyle(~flex=1., ~width=100.->pct, ~paddingHorizontal=10.->dp, ())} /> : <FlatList ref={pickerRef->ReactNative.Ref.value} keyboardShouldPersistTaps={#handled} data={items->Array.filter(x => x.label ->String.toLowerCase ->String.includes(searchInput->Option.getOr("")->String.toLowerCase) )} style={viewStyle(~flex=1., ~width=100.->pct, ~paddingHorizontal=10.->dp, ())} showsHorizontalScrollIndicator=false keyExtractor={(_, i) => i->Int.toString} horizontal=false renderItem={({item, index}) => <CustomTouchableOpacity key={index->Int.toString} style={viewStyle(~height=32.->dp, ~margin=1.->dp, ~justifyContent=#center, ())} onPress={_ => { setValue(_ => Some(item.value)) setIsModalVisible(_ => false) }}> <TextWrapper text={item.icon->Option.getOr("") ++ item.label} textType=ModalText /> </CustomTouchableOpacity>} />} </View> </View> </Modal> {isLoading ? <View style={viewStyle( ~overflow=#hidden, ~position=#absolute, ~opacity=0.6, ~width=100.->pct, ~height=100.->pct, (), )}> <CustomLoader /> </View> : React.null} </View> }
1,395
10,700
hyperswitch-client-core
src/components/common/DynamicFields.res
.res
open ReactNative open Style open RequiredFieldsTypes module RenderField = { let getStateData = (states, country) => { states ->Utils.getStateNames(country) ->Array.map((item): CustomPicker.customPickerType => { { label: item.label != "" ? item.label ++ " - " ++ item.value : item.value, value: item.value, } }) } let getCountryData = (countryArr, contextCountryData: CountryStateDataHookTypes.countries) => { contextCountryData ->Array.filter(item => { countryArr->Array.includes(item.isoAlpha2) }) ->Array.map((item): CustomPicker.customPickerType => { { label: item.label != "" ? item.label ++ " - " ++ item.value : item.value, value: item.isoAlpha2, icon: Utils.getCountryFlags(item.isoAlpha2), } }) } let getCountryValueOfRelativePath = (path, finalJsonDict) => { if path->String.length != 0 { let key = getKey(path, "country") let value = finalJsonDict->Dict.get(key) value ->Option.map(((value, _)) => value->JSON.Decode.string->Option.getOr("")) ->Option.getOr("") } else { "" } } @react.component let make = ( ~required_fields_type: RequiredFieldsTypes.required_fields_type, ~setFinalJsonDict, ~finalJsonDict, ~isSaveCardsFlow, ~statesAndCountry: CountryStateDataContext.data, ~keyToTrigerButtonClickError, ~paymentMethodType: option<RequiredFieldsTypes.payment_method_types_in_bank_debit>, ) => { let localeObject = GetLocale.useGetLocalObj() let {component, dangerColor} = ThemebasedStyle.useThemeBasedStyle() let value = switch required_fields_type.required_field { | StringField(x) => finalJsonDict ->Dict.get(x) ->Option.map(((value, _)) => value->JSON.Decode.string->Option.getOr("")) ->Option.getOr("") | FullNameField(firstName, lastName) => let firstNameValue = finalJsonDict ->Dict.get(firstName) ->Option.map(((value, _)) => value->JSON.Decode.string) ->Option.getOr(None) let lastNameValue = finalJsonDict ->Dict.get(lastName) ->Option.map(((value, _)) => value->JSON.Decode.string) ->Option.getOr(None) switch (firstNameValue, lastNameValue) { | (Some(firstName), Some(lastName)) => [firstName, lastName]->Array.join(" ") | (Some(firstName), _) => firstName | (_, Some(lastName)) => lastName | _ => "" } } let initialValue = switch value { | "" => None | value => Some(value) } let (val, setVal) = React.useState(_ => initialValue) React.useEffect(() => { setVal(_ => initialValue) None }, (required_fields_type, isSaveCardsFlow, initialValue)) let (errorMessage, setErrorMesage) = React.useState(_ => None) let (isFocus, setisFocus) = React.useState(_ => false) React.useEffect1(() => { switch val { | Some(text) => { let requiredFieldPath = RequiredFieldsTypes.getRequiredFieldPath( ~isSaveCardsFlow, ~requiredField={required_fields_type}, ) switch requiredFieldPath { | StringField(stringFieldPath) => let validationErrMsg = RequiredFieldsTypes.checkIsValid( ~text, ~field_type=required_fields_type.field_type, ~localeObject, ~display_name=required_fields_type.display_name, ~paymentMethodType, ) let isCountryField = switch required_fields_type.field_type { | AddressCountry(_) => true | _ => false } setErrorMesage(_ => validationErrMsg) setFinalJsonDict(prev => { let newData = Dict.assign(Dict.make(), prev) if isCountryField { let stateKey = getKey(stringFieldPath, "state") switch newData->Dict.get(stateKey) { | Some(_) => newData->Dict.set(stateKey, (JSON.Encode.null, Some("required"))) | None => () } } newData->Dict.set(stringFieldPath, (text->JSON.Encode.string, validationErrMsg)) newData }) | FullNameField(firstNameFieldPath, lastNameFieldPath) => let arr = text->String.split(" ") let firstNameVal = arr->Array.get(0)->Option.getOr("") let lastNameVal = arr->Array.filterWithIndex((_, index) => index !== 0)->Array.join(" ") let isBillingFields = required_fields_type.field_type === BillingName || required_fields_type.field_type === ShippingName let (firstNameVal, firstNameErrorMessage) = firstNameVal === "" ? ( JSON.Encode.null, isBillingFields ? Some(localeObject.mandatoryFieldText) : Some(localeObject.cardHolderNameRequiredText), ) : ( JSON.Encode.string(firstNameVal), firstNameVal->Validation.containsDigit ? Some(localeObject.invalidDigitsCardHolderNameError) : None, ) let (lastNameVal, lastNameErrorMessage) = lastNameVal === "" ? (JSON.Encode.null, Some(localeObject.lastNameRequiredText)) : ( JSON.Encode.string(lastNameVal), lastNameVal->Validation.containsDigit ? Some(localeObject.invalidDigitsCardHolderNameError) : None, ) setErrorMesage(_ => switch firstNameErrorMessage { | Some(_) => firstNameErrorMessage | None => lastNameErrorMessage } ) setFinalJsonDict(prev => { let newData = Dict.assign(Dict.make(), prev) newData->Dict.set(firstNameFieldPath, (firstNameVal, firstNameErrorMessage)) newData->Dict.set(lastNameFieldPath, (lastNameVal, lastNameErrorMessage)) newData }) } } | None => () } None }, [val]) let onChangeCountry = val => { setVal(val) } let onChange = text => { setVal(prev => RequiredFieldsTypes.allowOnlyDigits( ~text, ~fieldType=required_fields_type.field_type, ~prev, ~paymentMethodType, ) ) } React.useEffect1(() => { keyToTrigerButtonClickError != 0 ? { setVal(prev => prev->Option.isNone ? Some("") : prev) } : () None }, [keyToTrigerButtonClickError]) let isValid = errorMessage->Option.isNone let isValidForFocus = isFocus || isValid let {borderWidth, borderRadius} = ThemebasedStyle.useThemeBasedStyle() let placeholder = RequiredFieldsTypes.useGetPlaceholder( ~field_type=required_fields_type.field_type, ~display_name=required_fields_type.display_name, ~required_field=required_fields_type.required_field, ) let (countryStateData, _) = React.useContext(CountryStateDataContext.countryStateDataContext) <> // <TextWrapper text={placeholder()} textType=SubheadingBold /> // <Space height=5. /> {switch required_fields_type.field_type { | AddressCountry(countryArr) => <CustomPicker value=val setValue=onChangeCountry isCountryStateFields=true borderBottomLeftRadius=borderRadius borderBottomRightRadius=borderRadius borderBottomWidth=borderWidth items={switch countryStateData { | Localdata(res) | FetchData(res: CountryStateDataHookTypes.countryStateData) => switch countryArr { | UseContextData => res.countries->Array.map(item => item.isoAlpha2) | UseBackEndData(data) => data }->getCountryData(res.countries) | _ => [] }} placeholderText={placeholder()} isValid isLoading={switch statesAndCountry { | Loading => true | _ => false }} /> | AddressState => <CustomPicker value=val isCountryStateFields=true setValue=onChangeCountry borderBottomLeftRadius=borderRadius borderBottomRightRadius=borderRadius borderBottomWidth=borderWidth items={switch statesAndCountry { | FetchData(statesAndCountryVal) | Localdata(statesAndCountryVal) => getStateData( statesAndCountryVal.states, getCountryValueOfRelativePath( switch required_fields_type.required_field { | StringField(x) => x | _ => "" }, finalJsonDict, ), ) | _ => [] }} placeholderText={placeholder()} isValid isLoading={switch statesAndCountry { | Loading => true | _ => false }} /> | _ => <CustomInput state={val->Option.getOr("")} setState={text => onChange(Some(text))} placeholder={placeholder()} keyboardType={RequiredFieldsTypes.getKeyboardType( ~field_type=required_fields_type.field_type, )} enableCrossIcon=false isValid=isValidForFocus onFocus={_ => { setisFocus(_ => true) val->Option.isNone ? setVal(_ => Some("")) : () }} onBlur={_ => { setisFocus(_ => false) }} textColor={isFocus || errorMessage->Option.isNone ? component.color : dangerColor} borderTopLeftRadius=borderRadius borderTopRightRadius=borderRadius borderBottomWidth=borderWidth borderLeftWidth=borderWidth borderRightWidth=borderWidth borderTopWidth=borderWidth /> }} {if isFocus { React.null } else { <ErrorText text=errorMessage /> }} // <Space /> </> } } module Fields = { @react.component let make = ( ~fields: array<RequiredFieldsTypes.required_fields_type>, ~finalJsonDict, ~setFinalJsonDict, ~isSaveCardsFlow, ~statesAndCountry: CountryStateDataContext.data, ~keyToTrigerButtonClickError, ~paymentMethodType, ) => { fields ->Array.mapWithIndex((item, index) => <React.Fragment key={index->Int.toString}> {index == 0 ? React.null : <Space height=18. />} <RenderField required_fields_type=item key={index->Int.toString} isSaveCardsFlow statesAndCountry finalJsonDict setFinalJsonDict keyToTrigerButtonClickError paymentMethodType /> </React.Fragment> ) ->React.array } } type fieldType = Other | Billing | Shipping @react.component let make = ( ~requiredFields: RequiredFieldsTypes.required_fields, ~setIsAllDynamicFieldValid, ~setDynamicFieldsJson, ~isSaveCardsFlow=false, ~savedCardsData: option<SdkTypes.savedDataType>, ~keyToTrigerButtonClickError, ~shouldRenderShippingFields=false, //To render shipping fields ~displayPreValueFields=false, ~paymentMethodType=?, ~fieldsOrder: array<fieldType>=[Other, Billing, Shipping], ) => { // let {component} = ThemebasedStyle.useThemeBasedStyle() let clientTimeZone = Intl.DateTimeFormat.resolvedOptions(Intl.DateTimeFormat.make()).timeZone let (statesAndCountry, _) = React.useContext(CountryStateDataContext.countryStateDataContext) let clientCountry = Utils.getClientCountry( switch statesAndCountry { | FetchData(data) | Localdata(data) => data.countries | _ => [] }, clientTimeZone, ) let initialKeysValDict = React.useMemo(() => { switch statesAndCountry { | FetchData(statesAndCountryData) | Localdata(statesAndCountryData) => requiredFields ->RequiredFieldsTypes.filterRequiredFields(isSaveCardsFlow, savedCardsData) ->RequiredFieldsTypes.filterRequiredFieldsForShipping(shouldRenderShippingFields) ->RequiredFieldsTypes.getKeysValArray( isSaveCardsFlow, clientCountry.isoAlpha2, statesAndCountryData.countries->Array.map(item => {item.isoAlpha2}), ) | _ => requiredFields ->RequiredFieldsTypes.filterRequiredFields(isSaveCardsFlow, savedCardsData) ->RequiredFieldsTypes.filterRequiredFieldsForShipping(shouldRenderShippingFields) ->RequiredFieldsTypes.getKeysValArray(isSaveCardsFlow, clientCountry.isoAlpha2, []) } }, ( requiredFields, isSaveCardsFlow, savedCardsData, clientCountry.isoAlpha2, shouldRenderShippingFields, statesAndCountry, )) let (finalJsonDict, setFinalJsonDict) = React.useState(_ => initialKeysValDict) React.useEffect1(() => { let isAllValid = finalJsonDict ->Dict.toArray ->Array.reduce(true, (isValid, (_, (_, errorMessage))) => { isValid && errorMessage->Option.isNone }) setIsAllDynamicFieldValid(_ => isAllValid) setDynamicFieldsJson(_ => finalJsonDict) None }, [finalJsonDict]) let filteredFields = displayPreValueFields ? requiredFields : requiredFields->RequiredFieldsTypes.filterDynamicFieldsFromRendering(initialKeysValDict) // let (outsideBilling, insideBilling, shippingFields) = React.useMemo(() => // filteredFields->Array.reduce(([], [], []), ((outside, inside, shipping), item) => { // let isBillingField = // item.required_field // ->RequiredFieldsTypes.getRequiredFieldName // ->String.split(".") // ->Array.includes("billing") // let isShippingField = // item.required_field // ->RequiredFieldsTypes.getRequiredFieldName // ->String.split(".") // ->Array.includes("shipping") // switch (isBillingField, isShippingField, renderShippingFields) { // | (true, _, _) => (outside, inside->Array.concat([item]), shipping) // | (_, true, true) => (outside, inside, shipping->Array.concat([item])) // | (_, true, false) => (outside, inside, shipping) // | _ => (outside->Array.concat([item]), inside, shipping) // } // }) // , (filteredFields, renderShippingFields)) //logic to sort the fields based on the fieldsOrder let getOrderValue = field => { let path = field.required_field->RequiredFieldsTypes.getRequiredFieldName->String.split(".") let x = if path->Array.includes("billing") { Billing } else if path->Array.includes("shipping") { Shipping } else { Other } fieldsOrder->Array.indexOf(x) } let fields = React.useMemo(() => { filteredFields->Array.sort((a, b) => { let aPath = getOrderValue(a) let bPath = getOrderValue(b) float(aPath - bPath) }) filteredFields }, ( requiredFields, isSaveCardsFlow, savedCardsData, clientCountry.isoAlpha2, fieldsOrder, displayPreValueFields, shouldRenderShippingFields, )) // React.useEffect1(() => { // switch statesAndCountry { // | Some(_) => { // switch requiredFields->Array.find(required_fields_type => { // switch required_fields_type.field_type { // | AddressCountry(_) => true // | _ => false // } // }) { // | Some(required) => // switch required.required_field { // | StringField(path) => // setFinalJsonDict(prev => { // let newData = Dict.assign(Dict.make(), prev) // newData->Dict.set(path, (clientCountry.isoAlpha2->JSON.Encode.string, None)) // newData // }) // | _ => () // } // | _ => () // } // () // } // | _ => () // } // None // }, [statesAndCountry]) let isAddressCountryField = fieldType => switch fieldType.field_type { | AddressCountry(_) => true | _ => false } let updateDictWithCountry = (dict, path, countryCode) => { let newDict = Dict.assign(Dict.make(), dict) newDict->Dict.set(path, (countryCode->JSON.Encode.string, None)) newDict } let handleStringField = (path, prevDict, countryCode) => switch prevDict->Dict.get(path) { | Some((key, _)) if key->JSON.Decode.string->Option.getOr("") != "" => prevDict | _ => updateDictWithCountry(prevDict, path, countryCode) } React.useEffect2(() => { switch statesAndCountry { | FetchData(_) | Localdata(_) => requiredFields ->Array.find(isAddressCountryField) ->Option.forEach(required => { switch required.required_field { | StringField(path) => setFinalJsonDict(prev => handleStringField(path, prev, clientCountry.isoAlpha2)) | _ => () } }) | _ => () } None }, (statesAndCountry, clientCountry.isoAlpha2)) let renderFields = (fields, extraSpacing) => fields->Array.length > 0 ? <> {extraSpacing ? <Space height=24. /> : React.null} <Fields fields finalJsonDict setFinalJsonDict isSaveCardsFlow statesAndCountry paymentMethodType keyToTrigerButtonClickError /> </> : React.null // let renderSectionTitle = (title, show) => // show // ? <Text style={textStyle(~color=component.color, ~fontSize=16., ~marginVertical=10.->dp, ())}> // {title->React.string} // </Text> // : React.null <View style={viewStyle()}> {renderFields(fields, true)} // <Space height=10. /> // {renderSectionTitle("Billing", insideBilling->Array.length > 0)} // {renderFields(insideBilling, false)} // <Space height=10. /> // {renderSectionTitle("Shipping", renderShippingFields && shippingFields->Array.length > 0)} // {renderFields(shippingFields, false)} </View> }
4,072
10,701
hyperswitch-client-core
src/components/common/CustomKeyboardAvoidingView.res
.res
open ReactNative open Style @react.component let make = (~children, ~style, ~keyboardVerticalOffset=48.) => { let frame = React.useRef(None) let keyboardEvent = React.useRef(None) let (bottom, setBottom) = React.useState(() => 0.) let relativeKeyboardHeight = async (keyboardFrame: Keyboard.screenRect) => { if ( Platform.os === #ios && keyboardFrame.screenY === 0. && (await AccessibilityInfo.prefersCrossFadeTransitions()) ) { 0. } else { switch frame.current { | Some(frame: Event.LayoutEvent.layout) => { let keyboardY = keyboardFrame.screenY -. keyboardVerticalOffset max(frame.y +. frame.height -. keyboardY, 0.) } | None => 0. } } } let updateBottomIfNecessary = async () => { switch keyboardEvent.current { | Some(keyboardEvent: Keyboard.keyboardEvent) => { let {duration, easing, endCoordinates} = keyboardEvent let height = await relativeKeyboardHeight(endCoordinates) if bottom != height || height === 0. { setBottom(_ => height < 2. *. keyboardVerticalOffset ? 0. : height) if duration != 0. { LayoutAnimation.configureNext({ duration: duration > 10. ? duration : 10., update: { duration: duration > 10. ? duration : 10., \"type": easing, }, }) } } } | None => setBottom(_ => 0.) } } let onKeyboardChange = event => { keyboardEvent.current = Some(event) updateBottomIfNecessary()->ignore } let onLayoutChange = (event: Event.layoutEvent) => { let oldFrame = frame.current frame.current = Some(event.nativeEvent.layout) switch oldFrame { | Some(frame) => if frame.height !== event.nativeEvent.layout.height { updateBottomIfNecessary()->ignore } | None => updateBottomIfNecessary()->ignore } } React.useEffect0(() => { let subscriptions = [] if Platform.os == #ios { subscriptions->Array.push(Keyboard.addListener(#keyboardWillChangeFrame, onKeyboardChange)) } else { subscriptions->Array.pushMany([ Keyboard.addListener(#keyboardDidShow, onKeyboardChange), Keyboard.addListener(#keyboardDidHide, onKeyboardChange), ]) } Some( _ => { subscriptions->Array.forEach(subscription => subscription->EventSubscription.remove) }, ) }) let style = frame.current->Option.isSome && bottom > 0. ? array([style, viewStyle(~paddingBottom=bottom->dp, ())]) : style <View onLayout=onLayoutChange style> {children} </View> }
628
10,702
hyperswitch-client-core
src/components/common/CustomPressable.res
.res
open ReactNative @react.component let make = ( ~onPress=?, ~children=?, ~style=?, ~disabled=?, ~accessibilityRole=?, ~accessibilityState=?, ~accessibilityLabel=?, ~testID=?, ~activeOpacity as _=?, ) => { <Pressable ?onPress children=?{React.useMemo1(_ => switch children { | Some(children) => Some(_ => children) | None => None } , [children])} style=?{React.useMemo1(_ => switch style { | Some(style) => Some(_ => style) | None => None } , [style])} ?disabled ?accessibilityRole ?accessibilityState ?accessibilityLabel ?testID /> }
173
10,703
hyperswitch-client-core
src/components/common/ErrorText.res
.res
@react.component let make = (~text=None) => { switch text { | None => React.null | Some(val) => val == "" ? React.null : <> <TextWrapper textType={ErrorText}> {val->React.string} </TextWrapper> </> } }
67
10,704
hyperswitch-client-core
src/components/common/CustomTabView.res
.res
open ReactNative open Style @react.component let make = ( ~hocComponentArr: array<PMListModifier.hoc>=[], ~loading=true, ~setConfirmButtonDataRef, ) => { let (indexInFocus, setIndexInFocus) = React.useState(_ => 0) let setIndexInFocus = React.useCallback1(ind => setIndexInFocus(_ => ind), [setIndexInFocus]) let sceneMap = Map.make() let data = React.useMemo1(() => { if loading { hocComponentArr ->Array.pushMany([ { name: "loading", componentHoc: (~isScreenFocus as _, ~setConfirmButtonDataRef as _) => <> <Space height=20. /> <CustomLoader height="33" /> <Space height=5. /> <CustomLoader height="33" /> </>, }, { name: "loading", componentHoc: (~isScreenFocus as _, ~setConfirmButtonDataRef as _) => React.null, }, ]) ->ignore hocComponentArr } else { hocComponentArr } }, [hocComponentArr]) <UIUtils.RenderIf condition={data->Array.length > 0}> { let routes = data->Array.mapWithIndex((hoc, index) => { sceneMap->Map.set(index, (~route as _, ~position as _, ~jumpTo as _) => hoc.componentHoc(~isScreenFocus=indexInFocus == index, ~setConfirmButtonDataRef) ) let route: TabViewType.route = { key: index, title: hoc.name, componentHoc: hoc.componentHoc, } route }) let isScrollBarOnlyCards = data->Array.length == 1 && switch data->Array.get(0) { | Some({name}) => name == "Card" | None => true } <TabView sceneContainerStyle={viewStyle(~padding=10.->dp, ())} style={viewStyle(~marginHorizontal=-10.->dp, ())} indexInFocus routes onIndexChange=setIndexInFocus renderTabBar={(~indexInFocus, ~routes as _, ~position as _, ~layout as _, ~jumpTo) => { isScrollBarOnlyCards ? React.null : <ScrollableCustomTopBar hocComponentArr=data indexInFocus setIndexToScrollParentFlatList={jumpTo} /> }} renderScene={SceneMap.sceneMap(sceneMap)} /> } </UIUtils.RenderIf> }
577
10,705
hyperswitch-client-core
src/components/common/TopTabScreenWraper.res
.res
open ReactNative open Style @react.component let make = (~children, ~setDynamicHeight, ~isScreenFocus) => { let (viewHeight, setViewHeight) = React.useState(_ => 100.) let updateTabHeight = (event: Event.layoutEvent) => { let {height} = event.nativeEvent.layout if height > 100. && (viewHeight -. height)->Math.abs > 10. { setViewHeight(_ => height) LayoutAnimation.configureNext({ duration: 10., update: { duration: 10., \"type": #easeInEaseOut, }, }) } } React.useEffect3(() => { isScreenFocus ? setDynamicHeight(viewHeight) : () None }, (viewHeight, setDynamicHeight, isScreenFocus)) <View onLayout=updateTabHeight style={viewStyle(~width=100.->pct, ())}> children </View> }
218
10,706
hyperswitch-client-core
src/components/common/TabView.res
.res
open ReactNative open Style type isRTL = {isRTL: bool} type i18nManager = {getConstants: unit => isRTL} @val @scope("ReactNative") external i18nManager: i18nManager = "I18nManager" type initialLayout = { height?: float, width?: float, } @live type state = {navigationState: TabViewType.navigationState} @react.component let make = ( ~indexInFocus, ~routes, ~onIndexChange=_ => (), ~renderScene, ~initialLayout: initialLayout={}, ~keyboardDismissMode=#auto, ~lazyFn_: option<(~route: TabViewType.route) => bool>=?, ~lazy_: bool=false, ~lazyPreloadDistance: int=100, ~onSwipeStart: unit => unit=_ => (), ~onSwipeEnd: unit => unit=_ => (), ~renderLazyPlaceholder: (~route: TabViewType.route) => React.element=(~route as _) => React.null, ~renderTabBar, ~sceneContainerStyle: option<ReactNative.Style.t>=?, ~pagerStyle: option<ReactNative.Style.t>=?, ~style: option<ReactNative.Style.t>=?, ~direction: TabViewType.localeDirection=i18nManager.getConstants().isRTL ? #rtl : #ltr, ~swipeEnabled: bool=false, ~tabBarPosition=#top, ~animationEnabled=true, ) => { let defaultLayout: Event.ScrollEvent.dimensions = { width: initialLayout.width->Option.getOr(0.), height: initialLayout.height->Option.getOr(0.), } let (layout, setLayout) = React.useState(_ => defaultLayout) let jumpToIndex = index => { if index !== indexInFocus { onIndexChange(index) } } let handleLayout = (e: Event.layoutEvent) => { let {height, width} = e.nativeEvent.layout setLayout(prevLayout => if prevLayout.width === width && prevLayout.height === height { prevLayout } else { {height, width} } ) } <View onLayout={handleLayout} style={switch style { | Some(style) => array([viewStyle(~flex=1., ~overflow=#hidden, ()), style]) | None => viewStyle(~flex=1., ~overflow=#hidden, ()) }}> <Pager layout indexInFocus routes keyboardDismissMode swipeEnabled onSwipeStart onSwipeEnd onIndexChange=jumpToIndex animationEnabled style=?pagerStyle layoutDirection=direction> {(~addEnterListener, ~jumpTo, ~position, ~render, ~indexInFocus, ~routes) => { <React.Fragment> {tabBarPosition === #top ? renderTabBar(~indexInFocus, ~routes, ~position, ~layout, ~jumpTo) : React.null} {routes ->Array.mapWithIndex((route, i) => { <SceneView indexInFocus position layout jumpTo addEnterListener key={route.title ++ route.key->Int.toString} index=i lazy_={switch lazyFn_ { | Some(fn) => fn(~route) | None => lazy_ }} lazyPreloadDistance style=?sceneContainerStyle> {(~loading) => loading ? renderLazyPlaceholder(~route) : renderScene(~route, ~position, ~layout, ~jumpTo)} </SceneView> }) ->React.array ->render} {tabBarPosition === #bottom ? renderTabBar(~indexInFocus, ~routes, ~position, ~layout, ~jumpTo) : React.null} </React.Fragment> }} </Pager> </View> }
867
10,707
hyperswitch-client-core
src/components/common/TouchableOpacity/TouchableOpacityImpl.native.res
.res
type props = ReactNative.TouchableOpacity.props let make = ReactNative.TouchableOpacity.make
18
10,708
hyperswitch-client-core
src/components/common/TouchableOpacity/TouchableOpacityImpl.web.res
.res
let make = CustomPressable.make
8
10,709
hyperswitch-client-core
src/components/common/TouchableOpacity/CustomTouchableOpacity.res
.res
@module("./TouchableOpacityImpl") external make: React.component<ReactNative.TouchableOpacity.props> = "make"
22
10,710
hyperswitch-client-core
src/components/common/Tooltip/TooltipTypes.res
.res
type positionX = Left(float) | Right(float) type positionY = Top(float) | Bottom(float) type tooltipPosition = { x: positionX, y: positionY, }
40
10,711
hyperswitch-client-core
src/components/common/Tooltip/Tooltip.res
.res
open ReactNative open Style @react.component let make = ( ~children: React.element, ~renderContent: (_ => unit) => React.element, ~maxHeight=200., ~maxWidth=200., ~adjustment=2., ~containerStyle=?, ~backgroundColor=?, ~disabled=false, ~keyboardShouldPersistTaps=false, ) => { let { component, borderWidth, borderRadius, boxBorderColor, shadowColor, shadowIntensity, sheetContentPadding, } = ThemebasedStyle.useThemeBasedStyle() let shadowStyle = ShadowHook.useGetShadowStyle(~shadowIntensity, ~shadowColor, ()) let (viewPortContants, _) = React.useContext(ViewportContext.viewPortContext) let maxHeight = min(viewPortContants.screenHeight -. sheetContentPadding *. 2., maxHeight) let maxWidth = min( viewPortContants.screenWidth -. sheetContentPadding *. 2. -. adjustment *. 2., maxWidth, ) let renderedElement = React.useRef(Nullable.null) let (tooltipPosition, setTooltipPosition) = React.useState(_ => None) let (isVisible, setIsVisible) = React.useState(_ => false) let toggleVisibility = () => { setIsVisible(val => !val) } let calculateTooltipPosition = _ => { setTooltipPosition(_ => None) toggleVisibility() switch renderedElement.current->Js.Nullable.toOption { | Some(element) => element->View.measure((~x as _, ~y as _, ~width as _, ~height, ~pageX, ~pageY) => { let x: TooltipTypes.positionX = if viewPortContants.screenWidth -. pageX < maxWidth { Right(sheetContentPadding -. adjustment) } else { Left(pageX) } let y: TooltipTypes.positionY = if viewPortContants.screenHeight -. pageY < maxHeight { Bottom(viewPortContants.screenHeight -. pageY) } else { Top(pageY +. height) } setTooltipPosition(_ => Some(({x, y}: TooltipTypes.tooltipPosition))) }) | None => () } } let onPress = _ => { !keyboardShouldPersistTaps && Keyboard.isVisible() ? Keyboard.dismiss() : calculateTooltipPosition() } let getPositionStyle = (position: option<TooltipTypes.tooltipPosition>) => { switch position { | None => viewStyle() | Some(pos) => { let xStyle = switch pos.x { | Left(x) => viewStyle(~left=x->dp, ()) | Right(x) => viewStyle(~right=x->dp, ()) } let yStyle = switch pos.y { | Top(y) => viewStyle(~top=y->dp, ()) | Bottom(y) => viewStyle(~bottom=y->dp, ()) } StyleSheet.flatten([xStyle, yStyle]) } } } let tooltipBaseStyle = { let baseStyle = viewStyle( ~position=#absolute, ~paddingHorizontal=20.->dp, ~paddingVertical=10.->dp, ~maxWidth=maxWidth->dp, ~maxHeight=maxHeight->dp, ~backgroundColor=backgroundColor->Option.getOr(component.background), ~borderRadius, ~borderWidth, (), ) StyleSheet.flatten([baseStyle, boxBorderColor, shadowStyle, getPositionStyle(tooltipPosition)]) } let tooltipStyle = switch containerStyle { | Some(customStyle) => [tooltipBaseStyle, customStyle]->StyleSheet.flatten | None => [tooltipBaseStyle]->StyleSheet.flatten } <View ref={Ref.value(renderedElement)} onLayout={_ => ()}> <CustomTouchableOpacity onPress activeOpacity={disabled ? 1. : 0.2} disabled> children </CustomTouchableOpacity> <UIUtils.RenderIf condition={isVisible && tooltipPosition->Option.isSome}> <Portal> <CustomTouchableOpacity activeOpacity=1. onPress={_ => toggleVisibility()} style={viewStyle(~flex=1., ())}> <View style={tooltipStyle}> {renderContent(toggleVisibility)} </View> </CustomTouchableOpacity> </Portal> </UIUtils.RenderIf> </View> }
919
10,712
hyperswitch-client-core
src/components/common/CustomLoader/CustomLoader.res
.res
type props = { height?: string, width?: string, speed?: float, radius?: float, style?: ReactNative.Style.t, } @module("./CustomLoaderImpl") external make: React.component<props> = "make"
52
10,713
hyperswitch-client-core
src/components/common/CustomLoader/CustomLoaderImpl.web.res
.res
module ContentLoaderWeb = { @module("react-content-loader") @react.component external make: ( ~speed: float, ~width: string, ~height: string, ~viewBox: string=?, ~backgroundColor: string=?, ~foregroundColor: string=?, ~style: ReactNative.Style.t=?, ~children: React.element, ) => React.element = "default" } module ContentLoader = { @react.component let make = ( ~speed, ~width, ~height, ~viewBox=?, ~backgroundColor="red", ~foregroundColor="black", ~style=?, ~children=React.null, ) => { <ContentLoaderWeb speed width height ?viewBox backgroundColor foregroundColor ?style> {children} </ContentLoaderWeb> } } @react.component let make = (~height="45", ~width="100%", ~speed=2., ~radius=None, ~style) => { let {borderRadius, loadingBgColor, loadingFgColor} = ThemebasedStyle.useThemeBasedStyle() let br = switch radius { | Some(var) => var | None => borderRadius } <ContentLoader width height speed // viewBox ?style backgroundColor=loadingBgColor foregroundColor=loadingFgColor> <rect x="0" y="0" rx={br->Float.toString} ry={br->Float.toString} width height /> </ContentLoader> }
335
10,714
hyperswitch-client-core
src/components/common/CustomLoader/CustomLoaderImpl.native.res
.res
module ContentLoaderNative = { @module("react-content-loader/native") @react.component external make: ( ~speed: float, ~width: string, ~height: string, ~viewBox: string=?, ~backgroundColor: string=?, ~foregroundColor: string=?, ~style: ReactNative.Style.t=?, ~children: React.element, ) => React.element = "default" } module ContentLoader = { @react.component let make = ( ~speed, ~width, ~height, ~viewBox=?, ~backgroundColor="red", ~foregroundColor="black", ~style=?, ~children=React.null, ) => { <ContentLoaderNative speed width height ?viewBox backgroundColor foregroundColor ?style> {children} </ContentLoaderNative> } } module Rect = { @module("react-content-loader/native") @react.component external make: ( ~width: string, ~height: string, ~x: string, ~y: string, ~rx: string, ~ry: string, ) => React.element = "Rect" } @react.component let make = (~height="45", ~width="100%", ~speed=1.3, ~radius=None, ~style) => { let {borderRadius, loadingBgColor, loadingFgColor} = ThemebasedStyle.useThemeBasedStyle() let br = switch radius { | Some(var) => var | None => borderRadius } <ContentLoader width height speed // viewBox ?style backgroundColor=loadingBgColor foregroundColor=loadingFgColor> <Rect x="0" y="0" rx={br->Float.toString} ry={br->Float.toString} width height /> </ContentLoader> }
406
10,715
hyperswitch-client-core
src/hooks/LightDarkTheme.res
.res
// let useIsDarkMode = () => { // let (theme, _) = React.useContext(ThemeContext.themeContext) // theme->Option.getOr(#dark) == #dark // } open ReactNative let useIsDarkMode = () => { switch Appearance.useColorScheme()->Option.getOr(#light) { | #dark => true | #light => false } }
87
10,716
hyperswitch-client-core
src/hooks/GetLocale.res
.res
let useGetLocalObj = () => { let (localeStrings, _) = React.useContext(LocaleStringDataContext.localeDataContext) switch localeStrings { | Some(data) => data | _ => LocaleDataType.defaultLocale } }
51
10,717
hyperswitch-client-core
src/hooks/SDKLoadCheckHook.res
.res
let useSDKLoadCheck = (~enablePartialLoading=true) => { let samsungPayValidity = SamsungPay.useSamsungPayValidityHook() let (localeStrings, _) = React.useContext(LocaleStringDataContext.localeDataContext) let (canLoad, setCanLoad) = React.useState(_ => false) let checkIsSDKAbleToLoad = () => { if enablePartialLoading { setCanLoad(_ => localeStrings != Loading) } else { let val = samsungPayValidity != SamsungPay.Checking && samsungPayValidity != SamsungPay.Not_Started && localeStrings != Loading setCanLoad(_ => val) } } React.useEffect2(() => { checkIsSDKAbleToLoad() None }, (samsungPayValidity, localeStrings)) canLoad }
175
10,718
hyperswitch-client-core
src/hooks/ThemebasedStyle.res
.res
open ReactNative open Style type statusColorConfig = { textColor: ReactNative.Color.t, backgroundColor: ReactNative.Color.t, } type buttonColorConfig = (string, string) type componentConfig = { background: ReactNative.Color.t, borderColor: ReactNative.Color.t, dividerColor: ReactNative.Color.t, color: ReactNative.Color.t, } type statusColor = { green: statusColorConfig, orange: statusColorConfig, red: statusColorConfig, blue: statusColorConfig, } type maxTextSize = { maxHeadingTextSize: float, maxSubHeadingTextSize: float, maxPlaceholderTextSize: float, maxButtonTextSize: float, maxErrorTextSize: float, maxLinkTextSize: float, maxModalTextSize: float, maxCardTextSize: float, } let getStrProp = (~overRideProp, ~defaultProp) => { let x = switch overRideProp { | Some(val) => val | None => defaultProp } x } let getStyleProp = (~override, ~fn, ~default) => { let x = switch override { | Some(val) => fn(val) | None => default } x } let maxTextSize = { maxHeadingTextSize: 10., maxSubHeadingTextSize: 10., maxPlaceholderTextSize: 5., maxButtonTextSize: 15., maxErrorTextSize: 15., maxLinkTextSize: 7., maxModalTextSize: 6., maxCardTextSize: 7., } let status_color = { green: {textColor: "#36AF47", backgroundColor: "rgba(54, 175, 71, 0.12)"}, orange: {textColor: "#CA8601", backgroundColor: "rgba(202, 134, 1, 0.12)"}, red: {textColor: "#EF6969", backgroundColor: "rgba(239, 105, 105, 0.12)"}, blue: {textColor: "#0099FF", backgroundColor: "rgba(0, 153, 255, 0.12)"}, } let styles = { StyleSheet.create({ "light_bgColor": viewStyle(~backgroundColor="#ffffff", ()), "dark_bgColor": viewStyle(~backgroundColor="#2e2e2e", ()), "flatMinimal_bgColor": viewStyle(~backgroundColor="rgba(107, 114, 128, 1)", ()), "minimal_bgColor": viewStyle(~backgroundColor="#ffffff", ()), "light_bgTransparentColor": viewStyle( ~backgroundColor=Color.rgba(~r=0, ~g=0, ~b=0, ~a=0.2), (), ), "dark_bgTransparentColor": viewStyle(~backgroundColor=Color.rgba(~r=0, ~g=0, ~b=0, ~a=0.2), ()), "flatMinimal_bgTransparentColor": viewStyle( ~backgroundColor=Color.rgba(~r=0, ~g=0, ~b=0, ~a=0.2), (), ), "minimal_bgTransparentColor": viewStyle( ~backgroundColor=Color.rgba(~r=0, ~g=0, ~b=0, ~a=0.2), (), ), "light_textPrimary": textStyle(~color="#0570de", ()), "dark_textPrimary": textStyle(~color="#FFFFFF", ()), "flatMinimal_textPrimary": textStyle(~color="#e0e0e0", ()), "minimal_textPrimary": textStyle(~color="black", ()), "light_textSecondary": textStyle(~color="#767676", ()), "dark_textSecondary": textStyle(~color="#F6F8F9", ()), "flatMinimal_textSeconadry": textStyle(~color="#F6F8FA", ()), "minimal_textSeconadry": textStyle(~color="blue", ()), "light_textSecondary_Bold": textStyle(~color="#000000", ()), "dark_textSecondaryBold": textStyle(~color="#F6F8F9", ()), "flatMinimal_textSeconadryBold": textStyle(~color="#F6F8FA", ()), "minimal_textSeconadryBold": textStyle(~color="blue", ()), "light_textInputBg": viewStyle(~backgroundColor="#ffffff", ()), "dark_textInputBg": viewStyle(~backgroundColor="#444444", ()), "flatMinimal_textInputBg": viewStyle(~backgroundColor="black", ()), "minimal_textInputBg": viewStyle(~backgroundColor="white", ()), "light_boxColor": viewStyle(~backgroundColor="#FFFFFF", ()), "dark_boxColor": viewStyle(~backgroundColor="#191A1A", ()), "flatMinimal_boxColor": viewStyle(~backgroundColor="#191A1A", ()), "minimal_boxColor": viewStyle(~backgroundColor="#191A1A", ()), "light_boxBorderColor": viewStyle(~borderColor="#e4e4e5", ()), "dark_boxBorderColor": viewStyle(~borderColor="#79787d", ()), "flatMinimal_boxBorderColor": viewStyle(~borderColor="#3541ff", ()), "minimal_boxBorderColor": viewStyle(~borderColor="#e4e4e5", ()), }) } type themeBasedStyleObj = { platform: string, bgColor: ReactNative.Style.t, paymentSheetOverlay: string, loadingBgColor: string, loadingFgColor: string, bgTransparentColor: ReactNative.Style.t, textPrimary: ReactNative.Style.t, textSecondary: ReactNative.Style.t, textSecondaryBold: ReactNative.Style.t, placeholderColor: string, textInputBg: ReactNative.Style.t, iconColor: string, lineBorderColor: string, linkColor: ReactNative.Color.t, disableBgColor: ReactNative.Color.t, filterHeaderColor: ReactNative.Color.t, filterOptionTextColor: array<ReactNative.Color.t>, tooltipTextColor: ReactNative.Color.t, tooltipBackgroundColor: ReactNative.Color.t, boxColor: ReactNative.Style.t, boxBorderColor: ReactNative.Style.t, dropDownSelectAll: array<array<ReactNative.Color.t>>, fadedColor: array<ReactNative.Color.t>, status_color: statusColor, detailViewToolTipText: string, summarisedViewSingleStatHeading: string, switchThumbColor: string, shimmerColor: array<string>, //[background color, highlight color] lastOffset: string, dangerColor: string, orderDisableButton: string, toastColorConfig: statusColorConfig, // [backrgroundcolor, textColor] primaryColor: ReactNative.Color.t, borderRadius: float, borderWidth: float, buttonBorderRadius: float, buttonBorderWidth: float, component: componentConfig, locale: SdkTypes.localeTypes, fontFamily: SdkTypes.fontFamilyTypes, headingTextSizeAdjust: float, subHeadingTextSizeAdjust: float, placeholderTextSizeAdjust: float, buttonTextSizeAdjust: float, errorTextSizeAdjust: float, linkTextSizeAdjust: float, modalTextSizeAdjust: float, cardTextSizeAdjust: float, paypalButonColor: buttonColorConfig, samsungPayButtonColor: buttonColorConfig, applePayButtonColor: SdkTypes.applePayButtonStyle, googlePayButtonColor: Appearance.t, payNowButtonColor: buttonColorConfig, payNowButtonTextColor: string, payNowButtonBorderColor: string, payNowButtonShadowColor: string, payNowButtonShadowIntensity: float, focusedTextInputBoderColor: string, errorTextInputColor: string, normalTextInputBoderColor: string, shadowColor: string, shadowIntensity: float, primaryButtonHeight: float, sheetContentPadding: float, errorMessageSpacing: float, } let darkRecord = { primaryButtonHeight: 45., platform: "android", paymentSheetOverlay: "#00000025", bgColor: styles["dark_bgColor"], loadingBgColor: "#3e3e3e90", loadingFgColor: "#2e2e2e", bgTransparentColor: styles["dark_bgTransparentColor"], textPrimary: styles["dark_textPrimary"], textSecondary: styles["dark_textSecondary"], textSecondaryBold: styles["dark_textSecondaryBold"], placeholderColor: "#F6F8F940", textInputBg: styles["dark_textInputBg"], iconColor: "rgba(246, 248, 249, 0.25)", lineBorderColor: "#2C2D2F", linkColor: "#0099FF", disableBgColor: "#202124", filterHeaderColor: "rgba(246, 248, 249, 0.75)", filterOptionTextColor: ["rgba(246, 248, 249, 0.8)", "#F6F8F9"], tooltipTextColor: "#191A1A75", tooltipBackgroundColor: "#F7F8FA", boxColor: styles["dark_boxColor"], boxBorderColor: styles["dark_boxBorderColor"], dropDownSelectAll: [["#202124", "#202124", "#202124"], ["#202124", "#202124", "#202124"]], fadedColor: ["rgba(0, 0, 0, 0.75)", "rgba(0, 0, 0,1)"], status_color, detailViewToolTipText: "rgba(25, 26, 26, 0.75)", summarisedViewSingleStatHeading: "#F6F8F9", switchThumbColor: "#f4f3f4", shimmerColor: ["#191A1A", "#232424"], lastOffset: "#1B1B1D", dangerColor: "#EF6969", orderDisableButton: "#F6F8F9", toastColorConfig: { backgroundColor: "#343434", textColor: "#FFFFFF", }, primaryColor: "#0057c7", borderRadius: 7.0, borderWidth: 1., buttonBorderRadius: 4.0, buttonBorderWidth: 0.0, component: { background: Color.rgb(~r=57, ~g=57, ~b=57), borderColor: "#e6e6e650", dividerColor: "#e6e6e6", color: "#ffffff", }, locale: En, fontFamily: switch WebKit.platform { | #ios | #iosWebView => DefaultIOS | #android | #androidWebView => DefaultAndroid | #web | #next => DefaultWeb }, headingTextSizeAdjust: 0., subHeadingTextSizeAdjust: 0., placeholderTextSizeAdjust: 0., buttonTextSizeAdjust: 0., errorTextSizeAdjust: 0., linkTextSizeAdjust: 0., modalTextSizeAdjust: 0., cardTextSizeAdjust: 0., paypalButonColor: ("#ffffff", "#ffffff"), samsungPayButtonColor: ("#000000", "#000000"), payNowButtonTextColor: "#FFFFFF", applePayButtonColor: #white, googlePayButtonColor: #light, payNowButtonColor: ("#0057c7", "#0057c7"), payNowButtonBorderColor: "#e6e6e650", payNowButtonShadowColor: "black", payNowButtonShadowIntensity: 2., focusedTextInputBoderColor: "#0057c7", errorTextInputColor: "rgba(0, 153, 255, 1)", normalTextInputBoderColor: "rgba(204, 210, 226, 0.75)", shadowColor: "black", shadowIntensity: 2., sheetContentPadding: 20., errorMessageSpacing: 4., } let lightRecord = { primaryButtonHeight: 45., platform: "android", paymentSheetOverlay: "#00000070", bgColor: styles["light_bgColor"], loadingBgColor: "rgb(220,220,220)", loadingFgColor: "rgb(250,250,250)", bgTransparentColor: styles["light_bgTransparentColor"], textPrimary: styles["light_textPrimary"], textSecondary: styles["light_textSecondary"], textSecondaryBold: styles["light_textSecondary_Bold"], placeholderColor: "#00000070", textInputBg: styles["light_textInputBg"], iconColor: "rgba(53, 64, 82, 0.25)", lineBorderColor: "#CCD2E250", linkColor: "#0099FF", disableBgColor: "#ECECEC", filterHeaderColor: "#666666", filterOptionTextColor: ["#354052", "rgba(53, 64, 82, 0.8)"], tooltipTextColor: "#F6F8F975", tooltipBackgroundColor: "#191A1A", boxColor: styles["light_boxColor"], boxBorderColor: styles["light_boxBorderColor"], dropDownSelectAll: [["#E7EAF1", "#E7EAF1", "#E7EAF1"], ["#F1F5FA", "#FDFEFF", "#F1F5FA"]], fadedColor: ["#CCCFD450", "rgba(53, 64, 82, 0.5)"], status_color, detailViewToolTipText: "rgba(246, 248, 249, 0.75)", summarisedViewSingleStatHeading: "#354052", switchThumbColor: "white", shimmerColor: ["#EAEBEE", "#FFFFFF"], lastOffset: "#FFFFFF", dangerColor: "#FF3434", orderDisableButton: "#354052", toastColorConfig: { backgroundColor: "#2C2D2F", textColor: "#F5F7FC", }, primaryColor: "#006DF9", borderRadius: 7.0, borderWidth: 1., buttonBorderRadius: 4.0, buttonBorderWidth: 0.0, component: { background: "#FFFFFF", borderColor: "rgb(226,226,228)", dividerColor: "#e6e6e6", color: "#000000", }, locale: En, fontFamily: switch WebKit.platform { | #ios | #iosWebView => DefaultIOS | #android | #androidWebView => DefaultAndroid | #web | #next => DefaultWeb }, headingTextSizeAdjust: 0., subHeadingTextSizeAdjust: 0., placeholderTextSizeAdjust: 0., buttonTextSizeAdjust: 0., errorTextSizeAdjust: 0., linkTextSizeAdjust: 0., modalTextSizeAdjust: 0., cardTextSizeAdjust: 0., paypalButonColor: ("#F6C657", "#F6C657"), applePayButtonColor: #black, samsungPayButtonColor: ("#000000", "#000000"), googlePayButtonColor: #dark, payNowButtonColor: ("#006DF9", "#006DF9"), payNowButtonTextColor: "#FFFFFF", payNowButtonBorderColor: "#ffffff", payNowButtonShadowColor: "black", payNowButtonShadowIntensity: 2., focusedTextInputBoderColor: "#006DF9", errorTextInputColor: "rgba(0, 153, 255, 1)", normalTextInputBoderColor: "rgba(204, 210, 226, 0.75)", shadowColor: "black", shadowIntensity: 2., sheetContentPadding: 20., errorMessageSpacing: 4., } let minimal = { primaryButtonHeight: 45., platform: "android", paymentSheetOverlay: "#00000025", bgColor: styles["light_bgColor"], loadingBgColor: "rgb(244,244,244)", loadingFgColor: "rgb(250,250,250)", bgTransparentColor: styles["light_bgTransparentColor"], textPrimary: styles["light_textPrimary"], textSecondary: styles["light_textSecondary"], textSecondaryBold: styles["light_textSecondary_Bold"], placeholderColor: "#00000070", textInputBg: styles["light_textInputBg"], iconColor: "rgba(53, 64, 82, 0.25)", lineBorderColor: "#CCD2E250", linkColor: "#0099FF", disableBgColor: "#ECECEC", filterHeaderColor: "#666666", filterOptionTextColor: ["#354052", "rgba(53, 64, 82, 0.8)"], tooltipTextColor: "#F6F8F975", tooltipBackgroundColor: "#191A1A", boxColor: styles["light_boxColor"], boxBorderColor: styles["light_boxBorderColor"], dropDownSelectAll: [["#E7EAF1", "#E7EAF1", "#E7EAF1"], ["#F1F5FA", "#FDFEFF", "#F1F5FA"]], fadedColor: ["#CCCFD450", "rgba(53, 64, 82, 0.5)"], status_color, detailViewToolTipText: "rgba(246, 248, 249, 0.75)", summarisedViewSingleStatHeading: "#354052", switchThumbColor: "white", shimmerColor: ["#EAEBEE", "#FFFFFF"], lastOffset: "#FFFFFF", dangerColor: "#FF3434", orderDisableButton: "#354052", toastColorConfig: { backgroundColor: "#2C2D2F", textColor: "#F5F7FC", }, primaryColor: "#0570de", borderRadius: 7.0, borderWidth: 0.5, buttonBorderRadius: 4.0, buttonBorderWidth: 0.5, component: { background: "#ffffff", borderColor: "#e6e6e6", dividerColor: "#e6e6e6", color: "#000000", }, locale: En, fontFamily: switch WebKit.platform { | #ios | #iosWebView => DefaultIOS | #android | #androidWebView => DefaultAndroid | #web | #next => DefaultWeb }, headingTextSizeAdjust: 0., subHeadingTextSizeAdjust: 0., placeholderTextSizeAdjust: 0., buttonTextSizeAdjust: 0., errorTextSizeAdjust: 0., linkTextSizeAdjust: 0., modalTextSizeAdjust: 0., cardTextSizeAdjust: 0., paypalButonColor: ("#ffc439", "#ffc439"), samsungPayButtonColor: ("#000000", "#000000"), applePayButtonColor: #black, googlePayButtonColor: #dark, payNowButtonColor: ("#0570de", "#0080FE"), payNowButtonTextColor: "#FFFFFF", payNowButtonBorderColor: "#ffffff", payNowButtonShadowColor: "black", payNowButtonShadowIntensity: 3., focusedTextInputBoderColor: "rgba(0, 153, 255, 1)", errorTextInputColor: "rgba(0, 153, 255, 1)", normalTextInputBoderColor: "rgba(204, 210, 226, 0.75)", shadowColor: "black", shadowIntensity: 3., sheetContentPadding: 20., errorMessageSpacing: 4., } let flatMinimal = { primaryButtonHeight: 45., platform: "android", paymentSheetOverlay: "#00000025", bgColor: styles["flatMinimal_bgColor"], loadingBgColor: "rgb(244,244,244)", loadingFgColor: "rgb(250,250,250)", bgTransparentColor: styles["light_bgTransparentColor"], textPrimary: styles["flatMinimal_textPrimary"], textSecondary: styles["flatMinimal_textSeconadry"], textSecondaryBold: styles["flatMinimal_textSeconadryBold"], placeholderColor: "#00000070", textInputBg: styles["light_textInputBg"], iconColor: "rgba(53, 64, 82, 0.25)", lineBorderColor: "#CCD2E250", linkColor: "#0099FF", disableBgColor: "#ECECEC", filterHeaderColor: "#666666", filterOptionTextColor: ["#354052", "rgba(53, 64, 82, 0.8)"], tooltipTextColor: "#F6F8F975", tooltipBackgroundColor: "#191A1A", boxColor: styles["light_boxColor"], boxBorderColor: styles["light_boxBorderColor"], dropDownSelectAll: [["#E7EAF1", "#E7EAF1", "#E7EAF1"], ["#F1F5FA", "#FDFEFF", "#F1F5FA"]], fadedColor: ["#CCCFD450", "rgba(53, 64, 82, 0.5)"], status_color, detailViewToolTipText: "rgba(246, 248, 249, 0.75)", summarisedViewSingleStatHeading: "#354052", switchThumbColor: "white", shimmerColor: ["#EAEBEE", "#FFFFFF"], lastOffset: "#FFFFFF", dangerColor: "#fd1717", orderDisableButton: "#354052", toastColorConfig: { backgroundColor: "#2C2D2F", textColor: "#F5F7FC", }, primaryColor: "#3541ff", borderRadius: 7.0, borderWidth: 0.5, buttonBorderRadius: 4.0, buttonBorderWidth: 0.5, component: { background: "#ffffff", borderColor: "#566186", dividerColor: "#e6e6e6", color: "#30313d", }, locale: En, fontFamily: switch WebKit.platform { | #ios | #iosWebView => DefaultIOS | #android | #androidWebView => DefaultAndroid | #web | #next => DefaultWeb }, headingTextSizeAdjust: 0., subHeadingTextSizeAdjust: 0., placeholderTextSizeAdjust: 0., buttonTextSizeAdjust: 0., errorTextSizeAdjust: 0., linkTextSizeAdjust: 0., modalTextSizeAdjust: 0., cardTextSizeAdjust: 0., paypalButonColor: ("#ffc439", "#ffc439"), applePayButtonColor: #black, googlePayButtonColor: #dark, samsungPayButtonColor: ("#000000", "#000000"), payNowButtonColor: ("#0570de", "#0080FE"), payNowButtonTextColor: "#000000", payNowButtonBorderColor: "#000000", payNowButtonShadowColor: "black", payNowButtonShadowIntensity: 3., focusedTextInputBoderColor: "rgba(0, 153, 255, 1)", errorTextInputColor: "rgba(0, 153, 255, 1)", normalTextInputBoderColor: "rgba(204, 210, 226, 0.75)", shadowColor: "black", shadowIntensity: 3., sheetContentPadding: 20., errorMessageSpacing: 4., } let some = (~override, ~fn, ~default) => { switch override { | Some(val) => fn(val) | None => default } } let itemToObj = ( themeObj: themeBasedStyleObj, appearance: SdkTypes.appearance, isDarkMode: bool, ) => { let appearanceColor: option<SdkTypes.colors> = switch appearance.colors { | Some(Colors(obj)) => Some(obj) | Some(DefaultColors({light, dark})) => isDarkMode ? dark : light | None => None } let btnColor: option<SdkTypes.primaryButtonColor> = switch appearance.primaryButton { | Some(btn) => switch btn.primaryButtonColor { | Some(PrimaryButtonColor(btn_color)) => btn_color | Some(PrimaryButtonDefault({light, dark})) => isDarkMode ? dark : light | None => None } | None => None } let btnShape: option<SdkTypes.shapes> = switch appearance.primaryButton { | Some(btn) => switch btn.shapes { | Some(obj) => Some(obj) | None => None } | None => None } let gpayOverrideStyle = switch appearance.googlePay.buttonStyle { | Some(val) => isDarkMode ? val.dark : val.light | None => themeObj.googlePayButtonColor } let applePayOverrideStyle = switch appearance.applePay.buttonStyle { | Some(val) => isDarkMode ? val.dark : val.light | None => themeObj.applePayButtonColor } { primaryButtonHeight: themeObj.primaryButtonHeight, platform: themeObj.platform, bgColor: getStyleProp( ~override=switch appearanceColor { | Some(obj) => obj.background | _ => None }, ~fn=val => viewStyle(~backgroundColor=val, ()), ~default=themeObj.bgColor, ), loadingBgColor: getStrProp( ~overRideProp=switch appearanceColor { | Some(obj) => obj.loaderBackground | _ => None }, ~defaultProp=themeObj.loadingBgColor, ), loadingFgColor: getStrProp( ~overRideProp=switch appearanceColor { | Some(obj) => obj.loaderBackground | _ => None }, ~defaultProp=themeObj.loadingFgColor, ), bgTransparentColor: styles["light_bgTransparentColor"], textPrimary: getStyleProp( ~override=switch appearanceColor { | Some(obj) => obj.primaryText | _ => None }, ~fn=val => textStyle(~color=val, ()), ~default=themeObj.textPrimary, ), textSecondary: getStyleProp( ~override=switch appearanceColor { | Some(obj) => obj.secondaryText | _ => None }, ~fn=val => textStyle(~color=val, ()), ~default=themeObj.textSecondary, ), textSecondaryBold: getStyleProp( ~override=switch appearanceColor { | Some(obj) => obj.secondaryText | _ => None }, ~fn=val => textStyle(~color=val, ()), ~default=themeObj.textSecondaryBold, ), placeholderColor: getStrProp( ~overRideProp=switch appearanceColor { | Some(obj) => obj.placeholderText | _ => None }, ~defaultProp=themeObj.placeholderColor, ), textInputBg: themeObj.textInputBg, iconColor: getStrProp( ~overRideProp=switch appearanceColor { | Some(obj) => obj.icon | _ => None }, ~defaultProp=themeObj.iconColor, ), lineBorderColor: themeObj.lineBorderColor, linkColor: themeObj.linkColor, disableBgColor: themeObj.disableBgColor, filterHeaderColor: themeObj.filterHeaderColor, filterOptionTextColor: themeObj.filterOptionTextColor, tooltipTextColor: themeObj.tooltipTextColor, tooltipBackgroundColor: themeObj.tooltipBackgroundColor, boxColor: themeObj.boxBorderColor, boxBorderColor: themeObj.boxBorderColor, dropDownSelectAll: themeObj.dropDownSelectAll, fadedColor: themeObj.fadedColor, status_color, detailViewToolTipText: themeObj.detailViewToolTipText, summarisedViewSingleStatHeading: themeObj.summarisedViewSingleStatHeading, switchThumbColor: themeObj.switchThumbColor, shimmerColor: themeObj.shimmerColor, lastOffset: themeObj.lastOffset, dangerColor: getStrProp( ~overRideProp=switch appearanceColor { | Some(obj) => obj.error | _ => None }, ~defaultProp=themeObj.dangerColor, ), orderDisableButton: themeObj.orderDisableButton, toastColorConfig: { backgroundColor: themeObj.toastColorConfig.backgroundColor, textColor: themeObj.toastColorConfig.textColor, }, primaryColor: getStrProp( ~overRideProp=switch appearanceColor { | Some(obj) => obj.primary | _ => None }, ~defaultProp=themeObj.primaryColor, ), borderRadius: getStrProp( ~overRideProp=switch appearance.shapes { | Some(shapeObj) => shapeObj.borderRadius | None => None }, ~defaultProp=themeObj.borderRadius, ), borderWidth: getStrProp( ~overRideProp=switch appearance.shapes { | Some(obj) => obj.borderWidth | None => None }, ~defaultProp=themeObj.borderWidth, ), buttonBorderRadius: getStrProp( ~overRideProp=switch btnShape { | Some(obj) => obj.borderRadius | None => Some(themeObj.buttonBorderRadius) }, ~defaultProp=themeObj.buttonBorderRadius, ), buttonBorderWidth: getStrProp( ~overRideProp=switch btnShape { | Some(obj) => obj.borderWidth | None => Some(themeObj.buttonBorderWidth) }, ~defaultProp=themeObj.buttonBorderWidth, ), component: { background: getStrProp( ~overRideProp=switch appearanceColor { | Some(obj) => obj.componentBackground | _ => None }, ~defaultProp=themeObj.component.background, ), borderColor: getStrProp( ~overRideProp=switch appearanceColor { | Some(obj) => obj.componentBorder | _ => None }, ~defaultProp=themeObj.component.borderColor, ), dividerColor: getStrProp( ~overRideProp=switch appearanceColor { | Some(obj) => obj.componentDivider | _ => None }, ~defaultProp=themeObj.component.dividerColor, ), color: getStrProp( ~overRideProp=switch appearanceColor { | Some(obj) => obj.componentText | _ => None }, ~defaultProp=themeObj.component.color, ), }, locale: switch appearance.locale { | Some(obj) => obj | _ => En }, fontFamily: switch appearance.font { | Some(obj) => switch obj.family { | Some(family) => family | None => themeObj.fontFamily } | None => themeObj.fontFamily }, headingTextSizeAdjust: switch appearance.font { | Some(obj) => switch obj.headingTextSizeAdjust { | Some(size) => size >= maxTextSize.maxHeadingTextSize ? maxTextSize.maxHeadingTextSize : size | None => themeObj.headingTextSizeAdjust } | None => themeObj.headingTextSizeAdjust }, subHeadingTextSizeAdjust: switch appearance.font { | Some(obj) => switch obj.subHeadingTextSizeAdjust { | Some(size) => size >= maxTextSize.maxSubHeadingTextSize ? maxTextSize.maxSubHeadingTextSize : size | None => themeObj.subHeadingTextSizeAdjust } | None => themeObj.subHeadingTextSizeAdjust }, placeholderTextSizeAdjust: switch appearance.font { | Some(obj) => switch obj.placeholderTextSizeAdjust { | Some(size) => size >= maxTextSize.maxPlaceholderTextSize ? maxTextSize.maxPlaceholderTextSize : size | None => themeObj.placeholderTextSizeAdjust } | None => themeObj.placeholderTextSizeAdjust }, buttonTextSizeAdjust: switch appearance.font { | Some(obj) => switch obj.buttonTextSizeAdjust { | Some(size) => size >= maxTextSize.maxButtonTextSize ? maxTextSize.maxButtonTextSize : size | None => themeObj.buttonTextSizeAdjust } | None => themeObj.buttonTextSizeAdjust }, errorTextSizeAdjust: switch appearance.font { | Some(obj) => switch obj.errorTextSizeAdjust { | Some(size) => size >= maxTextSize.maxErrorTextSize ? maxTextSize.maxErrorTextSize : size | None => themeObj.errorTextSizeAdjust } | None => themeObj.errorTextSizeAdjust }, linkTextSizeAdjust: switch appearance.font { | Some(obj) => switch obj.linkTextSizeAdjust { | Some(size) => size >= maxTextSize.maxLinkTextSize ? maxTextSize.maxLinkTextSize : size | None => themeObj.linkTextSizeAdjust } | None => themeObj.linkTextSizeAdjust }, modalTextSizeAdjust: switch appearance.font { | Some(obj) => switch obj.modalTextSizeAdjust { | Some(size) => size >= maxTextSize.maxModalTextSize ? maxTextSize.maxModalTextSize : size | None => themeObj.modalTextSizeAdjust } | None => themeObj.modalTextSizeAdjust }, cardTextSizeAdjust: switch appearance.font { | Some(obj) => switch obj.cardTextSizeAdjust { | Some(size) => size >= maxTextSize.maxCardTextSize ? maxTextSize.maxCardTextSize : size | None => themeObj.cardTextSizeAdjust } | None => themeObj.cardTextSizeAdjust }, paypalButonColor: themeObj.paypalButonColor, samsungPayButtonColor: themeObj.samsungPayButtonColor, applePayButtonColor: applePayOverrideStyle, googlePayButtonColor: gpayOverrideStyle, payNowButtonColor: getStrProp( ~overRideProp=switch btnColor { | Some(obj) => switch obj.background { | Some(str) => Some((str, str)) | None => switch appearanceColor { | Some(appObj) => switch appObj.primary { | Some(str) => Some((str, str)) | None => None } | None => None } } | None => None }, ~defaultProp=themeObj.payNowButtonColor, ), payNowButtonTextColor: getStrProp( ~overRideProp=switch btnColor { | Some(obj) => obj.text | None => None }, ~defaultProp=themeObj.payNowButtonTextColor, ), payNowButtonBorderColor: getStrProp( ~overRideProp=switch btnColor { | Some(obj) => obj.border | None => None }, ~defaultProp=themeObj.payNowButtonBorderColor, ), payNowButtonShadowColor: getStrProp( ~overRideProp=switch btnShape { | Some(obj) => switch obj.shadow { | Some(shadowObj) => shadowObj.color | None => None } | None => None }, ~defaultProp=themeObj.payNowButtonShadowColor, ), payNowButtonShadowIntensity: getStrProp( ~overRideProp=switch btnShape { | Some(obj) => switch obj.shadow { | Some(shadowObj) => shadowObj.intensity | None => None } | None => None }, ~defaultProp=themeObj.payNowButtonShadowIntensity, ), focusedTextInputBoderColor: getStrProp( ~overRideProp=switch appearanceColor { | Some(obj) => obj.componentBorder | _ => None }, ~defaultProp=themeObj.focusedTextInputBoderColor, ), errorTextInputColor: getStrProp( ~overRideProp=switch appearanceColor { | Some(obj) => obj.error | _ => None }, ~defaultProp=themeObj.dangerColor, ), normalTextInputBoderColor: getStrProp( ~overRideProp=switch appearanceColor { | Some(obj) => obj.componentBorder | _ => None }, ~defaultProp=themeObj.component.borderColor, ), shadowColor: getStrProp( ~overRideProp=switch appearance.shapes { | Some(shapeObj) => switch shapeObj.shadow { | Some(shadowObj) => shadowObj.color | None => None } | None => None }, ~defaultProp=themeObj.shadowColor, ), shadowIntensity: getStrProp( ~overRideProp=switch appearance.shapes { | Some(shapeObj) => switch shapeObj.shadow { | Some(shadowObj) => shadowObj.intensity | None => None } | None => None }, ~defaultProp=themeObj.shadowIntensity, ), paymentSheetOverlay: themeObj.paymentSheetOverlay, sheetContentPadding: themeObj.sheetContentPadding, errorMessageSpacing: themeObj.errorMessageSpacing, } } //for preDefine light and dark styles let useThemeBasedStyle = () => { let (themeType, _) = React.useContext(ThemeContext.themeContext) let (nativeProp, _) = React.useContext(NativePropContext.nativePropContext) let themerecord = switch nativeProp.configuration.appearance.theme { | FlatMinimal => Some(flatMinimal) | Minimal => Some(minimal) | Light => Some(lightRecord) | Dark => Some(darkRecord) | Default => None } let themerecordOverridedWithAppObj = switch themeType { | Light(appearance) => itemToObj(themerecord->Option.getOr(lightRecord), appearance, false) | Dark(appearance) => itemToObj(themerecord->Option.getOr(darkRecord), appearance, true) } themerecordOverridedWithAppObj } //for custom light and dark styles // let useCustomThemeBasedStyle = (~lightStyle, ~darkStyle, ~defaultStyle=?, ()) => { // let isDarkMode = LightDarkTheme.useIsDarkMode() // let x = isDarkMode ? darkStyle : lightStyle // switch defaultStyle { // | Some(style) => array([style, x]) // | None => x // } // }
8,945
10,719
hyperswitch-client-core
src/hooks/BrowserHook.res
.res
type animations = { startEnter: string, startExit: string, endEnter: string, endExit: string, } type properties = { dismissButtonStyle: string, preferredBarTintColor: string, preferredControlTintColor: string, readerMode: bool, animated: bool, modalPresentationStyle: string, modalTransitionStyle: string, modalEnabled: bool, enableBarCollapsing: bool, showTitle: bool, toolbarColor: string, secondaryToolbarColor: string, navigationBarColor: string, navigationBarDividerColor: string, enableUrlBarHiding: bool, enableDefaultShare: bool, forceCloseOnRedirection: bool, animations: animations, // headers: { // "my-custom-header": "my custom header value" // } ephemeralWebSession: bool, showInRecents: bool, // waitForRedirectDelay: int, } type res = {url: option<string>, message: string, \"type": string} type status = Success | Failed | Cancel | Error type browserRes = { paymentID: string, amount: string, status: status, } module InAppBrowser = { @module("react-native-inappbrowser-reborn") @scope("InAppBrowser") external openUrl: (string, option<string>, properties) => promise<res> = "openAuth" @module("react-native-inappbrowser-reborn") @scope("InAppBrowser") external isAvailable: unit => promise<bool> = "isAvailable" } let openUrl = ( url, returnUrl, intervalId: React.ref<RescriptCore.Nullable.t<intervalId>>, ~useEphemeralWebSession=false, ~appearance:SdkTypes.appearance, ) => { { ReactNative.Platform.os === #web ? Promise.make((resolve, _reject) => { let newTab = Window.open_(url) intervalId.current = setInterval(() => { try { switch newTab->Nullable.toOption { | Some(tab) => let currentUrl = tab.location.href resolve({message: currentUrl, url: None, \"type": ""}) switch intervalId.current->Nullable.toOption { | Some(id) => clearInterval(id) | None => () } tab.close() | None => () } } catch { | _ => () } }, 1000)->Nullable.Value // Window.setHref(url) // let browserRes = { // paymentID: "", // amount: "", // status: Cancel, // } // resolve(browserRes) }) : InAppBrowser.isAvailable()->Promise.then(_ => { // if !x { // return // } InAppBrowser.openUrl( url, //"https://proyecto26.com/react-native-inappbrowser/?redirect_url=" ++ returnUrl, returnUrl, { // iOS Properties ephemeralWebSession: useEphemeralWebSession, dismissButtonStyle: "cancel", preferredBarTintColor: appearance.colors ->Option.flatMap(a => a->SdkTypes.getPrimaryColor(~theme=appearance.theme)) ->Option.getOr("#453AA4"), preferredControlTintColor: "white", readerMode: false, animated: true, modalPresentationStyle: "fullScreen", modalTransitionStyle: "coverVertical", modalEnabled: true, enableBarCollapsing: false, // Android Properties showInRecents: true, showTitle: false, toolbarColor: appearance.colors ->Option.flatMap(a => a->SdkTypes.getPrimaryColor(~theme=appearance.theme)) ->Option.getOr("#6200EE"), secondaryToolbarColor: "black", navigationBarColor: "black", navigationBarDividerColor: "white", enableUrlBarHiding: true, enableDefaultShare: true, forceCloseOnRedirection: false, // Specify full animation resource identifier(package:anim/name) // or only resource name(in case of animation bundled with app). animations: { startEnter: "slide_in_right", startExit: "slide_out_left", endEnter: "slide_in_left", endExit: "slide_out_right", }, // headers: { // "my-custom-header": "my custom header value" // } // waitForRedirectDelay: 10000, }, ) }) }->Promise.then(res => { try { let message = WebKit.platform === #ios ? res.url->Option.getOr("") : res.message if ( message->String.includes("status=succeeded") || message->String.includes("status=processing") || message->String.includes("status=requires_capture") || message->String.includes("status=partially_captured") ) { let resP = message->String.split("&") let am = (resP[2]->Option.getOr("")->String.split("="))[1]->Option.getOr("") let browserRes = { paymentID: (resP[1]->Option.getOr("")->String.split("="))[1]->Option.getOr(""), amount: am, status: Success, } Promise.resolve(browserRes) } else if ( message->String.includes("status=failed") || message->String.includes("status=requires_payment_method") ) { let resP = message->String.split("&") let am = (resP[2]->Option.getOr("")->String.split("="))[1]->Option.getOr("") let browserRes = { paymentID: String.split(resP[1]->Option.getOr(""), "=")[1]->Option.getOr(""), amount: am, status: Failed, } Promise.resolve(browserRes) } else if res.\"type" == "cancel" { let browserRes = { paymentID: "", amount: "", status: Cancel, } Promise.resolve(browserRes) } else { let browserRes = { paymentID: "", amount: "", status: Error, } Promise.resolve(browserRes) } } catch { | _ => let browserRes = { paymentID: "", amount: "", status: Failed, } Promise.resolve(browserRes) } }) }
1,377
10,720
hyperswitch-client-core
src/hooks/WebButtonHook.res
.res
let usePayButton = () => { let (nativeProp, _) = React.useContext(NativePropContext.nativePropContext) let { applePayButtonColor, googlePayButtonColor, buttonBorderRadius, } = ThemebasedStyle.useThemeBasedStyle() let {launchApplePay, launchGPay} = WebKit.useWebKit() let addApplePay = (~sessionObject: SessionsType.sessions, ~resolve as _) => { let status = Window.useScript( // "https://applepay.cdn-apple.com/jsapi/1.latest/apple-pay-sdk.js", "https://applepay.cdn-apple.com/jsapi/v1.2.0-beta/apple-pay-sdk.js", ) React.useEffect1(() => { status == #ready ? { // let isApplePaySupported = switch Window.sessionForApplePay->Nullable.toOption { // | Some(session) => // try { // session.canMakePayments() // } catch { // | _ => false // } // | None => false // } // resolve(isApplePaySupported) let appleWalletButton = Window.querySelector("apple-pay-button") switch appleWalletButton->Nullable.toOption { | Some(appleWalletButton) => appleWalletButton.removeAttribute("hidden") appleWalletButton.removeAttribute("aria-hidden") appleWalletButton.removeAttribute("disabled") appleWalletButton.setAttribute( "buttonstyle", applePayButtonColor->Utils.getStringFromRecord, ) appleWalletButton.setAttribute( "type", nativeProp.configuration.appearance.applePay.buttonType->Utils.getStringFromRecord, ) appleWalletButton.setAttribute("locale", "en-US") appleWalletButton.onclick = () => { try { launchApplePay( [ ("session_token_data", sessionObject.session_token_data), ("payment_request_data", sessionObject.payment_request_data), ] ->Dict.fromArray ->JSON.Encode.object ->JSON.stringify, ) } catch { | ex => AlertHook.alert(ex->Exn.asJsExn->JSON.stringifyAny->Option.getOr("failed")) } } | _ => () } None } : None }, [status]) } let addGooglePay = (~sessionObject, ~requiredFields) => { let status = Window.useScript("https://pay.google.com/gp/p/js/pay.js") let token = GooglePayTypeNew.getGpayToken( ~obj=sessionObject, ~appEnv=nativeProp.env, ~requiredFields, ) let onGooglePayButtonClick = () => { launchGPay( GooglePayTypeNew.getGpayTokenStringified( ~obj=sessionObject, ~appEnv=nativeProp.env, ~requiredFields, ), ) } React.useEffect1(() => { status == #ready ? { let paymentClient = Window.google(token.environment) let buttonProps: Window.buttonProps = { onClick: () => onGooglePayButtonClick(), buttonType: nativeProp.configuration.appearance.googlePay.buttonType ->Utils.getStringFromRecord ->String.toLowerCase, buttonSizeMode: "fill", buttonColor: switch googlePayButtonColor { | #light => "white" | #dark => "black" }, buttonRadius: buttonBorderRadius, } let googleWalletButton = paymentClient.createButton(buttonProps) let container = Window.querySelector("#google-wallet-button-container") switch container->Nullable.toOption { | Some(container1) => container1.appendChild(googleWalletButton) | _ => () } Some( () => { switch container->Nullable.toOption { | Some(containers) => containers.removeChild(googleWalletButton) | _ => () } }, ) } : None }, [status]) } (addApplePay, addGooglePay) }
849
10,721
hyperswitch-client-core
src/hooks/CountryStateDataHookTypes.res
.res
type country = { isoAlpha2: string, timeZones: array<string>, value: string, label: string, } type state = { label: string, value: string, code: string, } type states = Dict.t<array<state>> type countries = array<country> type countryStateData = { countries: countries, states: states, } let defaultTimeZone = { timeZones: [], value: "-", label: "", isoAlpha2: "", }
111
10,722
hyperswitch-client-core
src/hooks/NetceteraThreeDsHooks.res
.res
open ExternalThreeDsTypes open ThreeDsUtils open SdkStatusMessages let isInitialisedPromiseRef = ref(None) let initialisedNetceteraOnce = (~netceteraSDKApiKey, ~sdkEnvironment) => { switch isInitialisedPromiseRef.contents { | Some(promiseVal) => promiseVal | None => { let promiseVal = Promise.make((resolve, _reject) => { Netcetera3dsModule.initialiseNetceteraSDK( netceteraSDKApiKey, sdkEnvironment->sdkEnvironmentToStrMapper, status => resolve(status), ) }) isInitialisedPromiseRef := Some(promiseVal) promiseVal } } } let useInitNetcetera = () => { let logger = LoggerHook.useLoggerHook() (~netceteraSDKApiKey, ~sdkEnvironment: GlobalVars.envType) => { initialisedNetceteraOnce(~netceteraSDKApiKey, ~sdkEnvironment) ->Promise.then(promiseVal => { logger( ~logType=INFO, ~value=promiseVal->JSON.stringifyAny->Option.getOr(""), ~category=USER_EVENT, ~eventName=NETCETERA_SDK, (), ) Promise.resolve(promiseVal) }) ->ignore } } type postAReqParamsGenerationDecision = RetrieveAgain | Make3DsCall(ExternalThreeDsTypes.aReqParams) type threeDsAuthCallDecision = | GenerateChallenge({challengeParams: ExternalThreeDsTypes.authCallResponse}) | FrictionlessFlow let useExternalThreeDs = () => { let logger = LoggerHook.useLoggerHook() let apiLogWrapper = LoggerHook.useApiLogWrapper() let (_, setLoading) = React.useContext(LoadingContext.loadingContext) ( ~baseUrl, ~appId, ~netceteraSDKApiKey, ~clientSecret, ~publishableKey, ~nextAction, ~sdkEnvironment: GlobalVars.envType, ~retrievePayment: (Types.retrieve, string, string, ~isForceSync: bool=?) => promise<Js.Json.t>, ~onSuccess: string => unit, ~onFailure: string => unit, ) => { let threeDsData = nextAction->ThreeDsUtils.getThreeDsNextActionObj->ThreeDsUtils.getThreeDsDataObj let rec shortPollExternalThreeDsAuthStatus = ( ~pollConfig: PaymentConfirmTypes.pollConfig, ~pollCount, ~onPollCompletion: (~isFinalRetrieve: bool=?) => unit, ) => { if pollCount >= pollConfig.frequency { onPollCompletion() } else { setLoading(ProcessingPayments(None)) let uri = `${baseUrl}/poll/status/${pollConfig.pollId}` apiLogWrapper( ~logType=INFO, ~eventName=POLL_STATUS_CALL_INIT, ~url=uri, ~statusCode="", ~apiLogType=Request, ~data=JSON.Encode.null, (), ) let logInfo = (~statusCode, ~apiLogType, ~data) => { apiLogWrapper( ~logType=INFO, ~eventName=POLL_STATUS_CALL, ~url=uri, ~statusCode, ~apiLogType, ~data, (), ) } let logError = (~statusCode, ~apiLogType, ~data) => { apiLogWrapper( ~logType=ERROR, ~eventName=POLL_STATUS_CALL, ~url=uri, ~statusCode, ~apiLogType, ~data, (), ) } let headers = getAuthCallHeaders(publishableKey) CommonHooks.fetchApi(~uri, ~headers, ~method_=Fetch.Get, ()) ->Promise.then(data => { let statusCode = data->Fetch.Response.status->string_of_int if statusCode->String.charAt(0) === "2" { data ->Fetch.Response.json ->Promise.then(res => { let pollResponse = res ->Utils.getDictFromJson ->ExternalThreeDsTypes.pollResponseItemToObjMapper let logData = [ ("url", uri->JSON.Encode.string), ("statusCode", statusCode->JSON.Encode.string), ("response", pollResponse.status->JSON.Encode.string), ] ->Dict.fromArray ->JSON.Encode.object logInfo(~statusCode, ~apiLogType=Response, ~data=logData) if pollResponse.status === "completed" { Promise.resolve() } else { Promise.make( (_resolve, _reject) => { setTimeout( () => { shortPollExternalThreeDsAuthStatus( ~pollConfig, ~pollCount=pollCount + 1, ~onPollCompletion, ) }, pollConfig.delayInSecs * 1000, )->ignore }, ) } }) } else { data ->Fetch.Response.json ->Promise.thenResolve(res => { logError(~statusCode, ~apiLogType=Err, ~data=res) }) ->ignore Promise.resolve() } }) ->Promise.catch(err => { logError( ~statusCode="504", ~apiLogType=NoResponse, ~data=err->Utils.getError(`Netcetera Error`), ) Promise.resolve() }) ->Promise.finally(_ => { onPollCompletion() }) ->ignore } } let rec retrieveAndShowStatus = (~isFinalRetrieve=?) => { apiLogWrapper( ~logType=INFO, ~eventName=RETRIEVE_CALL_INIT, ~url=baseUrl, ~statusCode="", ~apiLogType=Request, ~data=JSON.Encode.null, (), ) setLoading(ProcessingPayments(None)) retrievePayment(Types.Payment, clientSecret, publishableKey) ->Promise.then(res => { if res == JSON.Encode.null { onFailure(retrievePaymentStatus.apiCallFailure) } else { let status = res->Utils.getDictFromJson->Utils.getString("status", "") let isFinalRetrieve = isFinalRetrieve->Option.getOr(true) switch status { | "processing" | "succeeded" => onSuccess(retrievePaymentStatus.successMsg) | "failed" => onFailure(retrievePaymentStatus.errorMsg) | _ => if isFinalRetrieve { onFailure(retrievePaymentStatus.errorMsg) } else { shortPollExternalThreeDsAuthStatus( ~pollConfig=threeDsData.pollConfig, ~pollCount=0, ~onPollCompletion=retrieveAndShowStatus, ) } } }->ignore Promise.resolve() }) ->Promise.catch(_ => { onFailure(retrievePaymentStatus.apiCallFailure) Promise.resolve() }) ->ignore } let hsAuthorizeCall = (~authorizeUrl) => { apiLogWrapper( ~logType=INFO, ~eventName=AUTHORIZE_CALL_INIT, ~url=authorizeUrl, ~statusCode="", ~apiLogType=Request, ~data=JSON.Encode.null, (), ) let headers = [("Content-Type", "application/json")]->Dict.fromArray CommonHooks.fetchApi(~uri=authorizeUrl, ~bodyStr="", ~headers, ~method_=Fetch.Post, ()) ->Promise.then(async data => { setLoading(ProcessingPayments(None)) let statusCode = data->Fetch.Response.status->string_of_int if statusCode->String.charAt(0) === "2" { apiLogWrapper( ~logType=INFO, ~eventName=AUTHORIZE_CALL, ~url=authorizeUrl, ~statusCode, ~apiLogType=Response, ~data=JSON.Encode.null, (), ) } else { await data ->Fetch.Response.json ->Promise.thenResolve(error => { apiLogWrapper( ~logType=ERROR, ~eventName=AUTHORIZE_CALL, ~url=authorizeUrl, ~statusCode, ~apiLogType=Err, ~data=error, (), ) }) } false }) ->Promise.catch(err => { apiLogWrapper( ~logType=ERROR, ~eventName=AUTHORIZE_CALL, ~url=authorizeUrl, ~statusCode="504", ~apiLogType=NoResponse, ~data=err->Utils.getError(`Netcetera Error`), (), ) Promise.resolve(true) }) } let sendChallengeParamsAndGenerateChallenge = (~challengeParams) => { let threeDSRequestorAppURL = Utils.getReturnUrl( ~appId, ~appURL=challengeParams.threeDSRequestorAppURL , ~useAppUrl=true ) Promise.make((resolve, reject) => { Netcetera3dsModule.recieveChallengeParamsFromRN( challengeParams.acsSignedContent, challengeParams.acsRefNumber, challengeParams.acsTransactionId, challengeParams.threeDSServerTransId, status => { logger( ~logType=INFO, ~value={ "status": status.status, "message": status.message, "threeDSRequestorAppURL": threeDSRequestorAppURL, } ->JSON.stringifyAny ->Option.getOr(""), ~category=USER_EVENT, ~eventName=NETCETERA_SDK, (), ) if status->isStatusSuccess { Netcetera3dsModule.generateChallenge(status => { logger( ~logType=INFO, ~value=status->JSON.stringifyAny->Option.getOr(""), ~category=USER_EVENT, ~eventName=NETCETERA_SDK, (), ) resolve() }) } else { retrieveAndShowStatus() reject() } }, threeDSRequestorAppURL, ) }) } let hsThreeDsAuthCall = (aReqParams: aReqParams) => { let uri = threeDsData.threeDsAuthenticationUrl let bodyStr = generateAuthenticationCallBody(clientSecret, aReqParams) let headers = getAuthCallHeaders(publishableKey) apiLogWrapper( ~logType=INFO, ~eventName=AUTHENTICATION_CALL_INIT, ~url=uri, ~statusCode="", ~apiLogType=Request, ~data=JSON.Encode.null, (), ) CommonHooks.fetchApi(~uri, ~bodyStr, ~headers, ~method_=Post, ()) ->Promise.then(data => { let statusCode = data->Fetch.Response.status->string_of_int if statusCode->String.charAt(0) === "2" { data ->Fetch.Response.json ->Promise.thenResolve(res => { apiLogWrapper( ~logType=INFO, ~eventName=AUTHENTICATION_CALL, ~url=uri, ~statusCode, ~apiLogType=Response, ~data=JSON.Encode.null, (), ) let authResponse = res->authResponseItemToObjMapper switch authResponse { | AUTH_RESPONSE(challengeParams) => logger( ~logType=INFO, ~value=challengeParams.transStatus, ~category=USER_EVENT, ~eventName=DISPLAY_THREE_DS_SDK, (), ) switch challengeParams.transStatus { | "C" => GenerateChallenge({challengeParams: challengeParams}) | _ => FrictionlessFlow } | AUTH_ERROR(errObj) => { logger( ~logType=ERROR, ~value=errObj.errorMessage, ~category=USER_EVENT, ~eventName=DISPLAY_THREE_DS_SDK, (), ) FrictionlessFlow } } }) } else { data ->Fetch.Response.json ->Promise.thenResolve(err => { apiLogWrapper( ~logType=ERROR, ~eventName=AUTHENTICATION_CALL, ~url=uri, ~statusCode, ~apiLogType=Err, ~data=err, (), ) FrictionlessFlow }) } }) ->Promise.catch(err => { apiLogWrapper( ~logType=ERROR, ~eventName=AUTHENTICATION_CALL, ~url=uri, ~statusCode="504", ~apiLogType=NoResponse, ~data=err->Utils.getError(`Netcetera Error`), (), ) Promise.resolve(FrictionlessFlow) }) } let startNetcetera3DSFlow = () => { initialisedNetceteraOnce(~netceteraSDKApiKey, ~sdkEnvironment) ->Promise.then(statusInfo => { logger( ~logType=INFO, ~value=statusInfo->JSON.stringifyAny->Option.getOr(""), ~category=USER_EVENT, ~eventName=NETCETERA_SDK, (), ) if statusInfo->isStatusSuccess { Promise.make((resolve, _reject) => { Netcetera3dsModule.generateAReqParams( threeDsData.messageVersion, threeDsData.directoryServerId, (status, aReqParams) => { logger( ~logType=INFO, ~value=status->JSON.stringifyAny->Option.getOr(""), ~category=USER_EVENT, ~eventName=NETCETERA_SDK, (), ) if status->isStatusSuccess { resolve(Make3DsCall(aReqParams)) } else { resolve(RetrieveAgain) } }, ) }) } else { Promise.resolve(RetrieveAgain) } }) ->Promise.catch(_ => Promise.resolve(RetrieveAgain)) ->Promise.then(decision => { Promise.make((resolve, reject) => { switch decision { | RetrieveAgain => retrieveAndShowStatus() reject() | Make3DsCall(aReqParams) => resolve(aReqParams) } }) }) } let checkSDKPresence = () => { Promise.make((resolve, reject) => { if !Netcetera3dsModule.isAvailable { logger( ~logType=DEBUG, ~value="Netcetera SDK dependency not added", ~category=USER_EVENT, ~eventName=NETCETERA_SDK, (), ) onFailure(externalThreeDsModuleStatus.errorMsg) reject() } else { resolve() } }) } let handleNativeThreeDs = async () => { let isFinalRetrieve = try { await checkSDKPresence() let aReqParams = await startNetcetera3DSFlow() let authCallDecision = await hsThreeDsAuthCall(aReqParams) switch authCallDecision { | GenerateChallenge({challengeParams}) => // setLoading(ExternalThreeDSLoading) await sendChallengeParamsAndGenerateChallenge(~challengeParams) // setLoading(ProcessingPayments) | FrictionlessFlow => () } await hsAuthorizeCall(~authorizeUrl=threeDsData.threeDsAuthorizeUrl) } catch { | _ => true } retrieveAndShowStatus(~isFinalRetrieve) } handleNativeThreeDs()->ignore } }
3,293
10,723
hyperswitch-client-core
src/hooks/CommonHooks.res
.res
let fetchApi = ( ~uri, ~bodyStr: string="", ~headers, ~method_: Fetch.requestMethod, ~mode: option<Fetch.requestMode>=?, ~dontUseDefaultHeader=false, (), ) => { if !dontUseDefaultHeader { Dict.set(headers, "Content-Type", "application/json") Dict.set(headers, "X-Client-Platform", WebKit.platformString) } let body = switch method_ { | Get => Promise.resolve(None) | _ => Promise.resolve(Some(Fetch.BodyInit.make(bodyStr))) } open Promise body->then(body => { Fetch.fetchWithInit( uri, Fetch.RequestInit.make( ~method_, ~body?, ~headers=Fetch.HeadersInit.makeWithDict(headers), ~mode?, (), ), ) ->catch(err => { exception Error(string) Promise.reject(Error(err->Utils.getError(`API call failed: ${uri}`)->JSON.stringify)) }) ->then(resp => { //let status = resp->Fetch.Response.status Promise.resolve(resp) }) }) }
242
10,724
hyperswitch-client-core
src/hooks/S3ApiHook.res
.res
open CountryStateDataHookTypes let decodeCountryArray: array<Js.Json.t> => array<country> = data => { data->Array.map(item => { switch item->Js.Json.decodeObject { | Some(res) => { isoAlpha2: Utils.getString(res, "isoAlpha2", ""), timeZones: Utils.getStrArray(res, "timeZones"), value: Utils.getString(res, "value", ""), label: Utils.getString(res, "label", ""), } | None => defaultTimeZone } }) } let decodeStateJson: Js.Json.t => Dict.t<array<state>> = data => { data ->Utils.getDictFromJson ->Js.Dict.entries ->Array.map(item => { let (key, val) = item let newVal = val ->JSON.Decode.array ->Option.getOr([]) ->Array.map(jsonItem => { let dictItem = jsonItem->Utils.getDictFromJson { label: Utils.getString(dictItem, "label", ""), value: Utils.getString(dictItem, "value", ""), code: Utils.getString(dictItem, "code", ""), } }) (key, newVal) }) ->Js.Dict.fromArray } let decodeJsonTocountryStateData: JSON.t => countryStateData = jsonData => { switch jsonData->Js.Json.decodeObject { | Some(res) => { let countryArr = res ->Js.Dict.get("country") ->Option.getOr([]->Js.Json.Array) ->Js.Json.decodeArray ->Option.getOr([]) let statesDict = res ->Js.Dict.get("states") ->Option.getOr(Js.Json.Object(Js.Dict.empty())) { countries: decodeCountryArray(countryArr), states: decodeStateJson(statesDict), } } | None => { countries: [], states: Js.Dict.empty(), } } } open LocaleDataType let getLocaleStrings: Js.Json.t => localeStrings = data => { switch data->Js.Json.decodeObject { | Some(res) => { locale: Utils.getString(res, "locale", defaultLocale.locale), cardDetailsLabel: Utils.getString(res, "cardDetailsLabel", defaultLocale.cardDetailsLabel), cardNumberLabel: Utils.getString(res, "cardNumberLabel", defaultLocale.cardNumberLabel), localeDirection: Utils.getString(res, "localeDirection", defaultLocale.localeDirection), inValidCardErrorText: Utils.getString( res, "inValidCardErrorText", defaultLocale.inValidCardErrorText, ), unsupportedCardErrorText: Utils.getString( res, "unsupportedCardErrorText", defaultLocale.unsupportedCardErrorText, ), inCompleteCVCErrorText: Utils.getString( res, "inCompleteCVCErrorText", defaultLocale.inCompleteCVCErrorText, ), inValidCVCErrorText: Utils.getString( res, "inValidCVCErrorText", defaultLocale.inValidCVCErrorText, ), inCompleteExpiryErrorText: Utils.getString( res, "inCompleteExpiryErrorText", defaultLocale.inCompleteExpiryErrorText, ), inValidExpiryErrorText: Utils.getString( res, "inValidExpiryErrorText", defaultLocale.inValidExpiryErrorText, ), pastExpiryErrorText: Utils.getString( res, "pastExpiryErrorText", defaultLocale.pastExpiryErrorText, ), poweredBy: Utils.getString(res, "poweredBy", defaultLocale.poweredBy), validThruText: Utils.getString(res, "validThruText", defaultLocale.validThruText), sortCodeText: Utils.getString(res, "sortCodeText", defaultLocale.sortCodeText), cvcTextLabel: Utils.getString(res, "cvcTextLabel", defaultLocale.cvcTextLabel), emailLabel: Utils.getString(res, "emailLabel", defaultLocale.emailLabel), emailInvalidText: Utils.getString(res, "emailInvalidText", defaultLocale.emailInvalidText), emailEmptyText: Utils.getString(res, "emailEmptyText", defaultLocale.emailEmptyText), accountNumberText: Utils.getString(res, "accountNumberText", defaultLocale.accountNumberText), fullNameLabel: Utils.getString(res, "fullNameLabel", defaultLocale.fullNameLabel), line1Label: Utils.getString(res, "line1Label", defaultLocale.line1Label), line1Placeholder: Utils.getString(res, "line1Placeholder", defaultLocale.line1Placeholder), line1EmptyText: Utils.getString(res, "line1EmptyText", defaultLocale.line1EmptyText), line2Label: Utils.getString(res, "line2Label", defaultLocale.line2Label), line2Placeholder: Utils.getString(res, "line2Placeholder", defaultLocale.line2Placeholder), cityLabel: Utils.getString(res, "cityLabel", defaultLocale.cityLabel), cityEmptyText: Utils.getString(res, "cityEmptyText", defaultLocale.cityEmptyText), postalCodeLabel: Utils.getString(res, "postalCodeLabel", defaultLocale.postalCodeLabel), postalCodeEmptyText: Utils.getString( res, "postalCodeEmptyText", defaultLocale.postalCodeEmptyText, ), stateLabel: Utils.getString(res, "stateLabel", defaultLocale.stateLabel), fullNamePlaceholder: Utils.getString( res, "fullNamePlaceholder", defaultLocale.fullNamePlaceholder, ), countryLabel: Utils.getString(res, "countryLabel", defaultLocale.countryLabel), currencyLabel: Utils.getString(res, "currencyLabel", defaultLocale.currencyLabel), bankLabel: Utils.getString(res, "bankLabel", defaultLocale.bankLabel), redirectText: Utils.getString(res, "redirectText", defaultLocale.redirectText), bankDetailsText: Utils.getString(res, "bankDetailsText", defaultLocale.bankDetailsText), orPayUsing: Utils.getString(res, "orPayUsing", defaultLocale.orPayUsing), addNewCard: Utils.getString(res, "addNewCard", defaultLocale.addNewCard), useExisitingSavedCards: Utils.getString( res, "useExisitingSavedCards", defaultLocale.useExisitingSavedCards, ), saveCardDetails: Utils.getString(res, "saveCardDetails", defaultLocale.saveCardDetails), addBankAccount: Utils.getString(res, "addBankAccount", defaultLocale.addBankAccount), achBankDebitTermsPart1: Utils.getString( res, "achBankDebitTermsPart1", defaultLocale.achBankDebitTermsPart1, ), achBankDebitTermsPart2: Utils.getString( res, "achBankDebitTermsPart2", defaultLocale.achBankDebitTermsPart2, ), sepaDebitTermsPart1: Utils.getString( res, "sepaDebitTermsPart1", defaultLocale.sepaDebitTermsPart1, ), sepaDebitTermsPart2: Utils.getString( res, "sepaDebitTermsPart2", defaultLocale.sepaDebitTermsPart2, ), becsDebitTerms: Utils.getString(res, "becsDebitTerms", defaultLocale.becsDebitTerms), cardTermsPart1: Utils.getString(res, "cardTermsPart1", defaultLocale.cardTermsPart1), cardTermsPart2: Utils.getString(res, "cardTermsPart2", defaultLocale.cardTermsPart2), payNowButton: Utils.getString(res, "payNowButton", defaultLocale.payNowButton), cardNumberEmptyText: Utils.getString( res, "cardNumberEmptyText", defaultLocale.cardNumberEmptyText, ), cardExpiryDateEmptyText: Utils.getString( res, "cardExpiryDateEmptyText", defaultLocale.cardExpiryDateEmptyText, ), cvcNumberEmptyText: Utils.getString( res, "cvcNumberEmptyText", defaultLocale.cvcNumberEmptyText, ), enterFieldsText: Utils.getString(res, "enterFieldsText", defaultLocale.enterFieldsText), enterValidDetailsText: Utils.getString( res, "enterValidDetailsText", defaultLocale.enterValidDetailsText, ), card: Utils.getString(res, "card", defaultLocale.card), billingNameLabel: Utils.getString(res, "billingNameLabel", defaultLocale.billingNameLabel), billingNamePlaceholder: Utils.getString( res, "billingNamePlaceholder", defaultLocale.billingNamePlaceholder, ), cardHolderName: Utils.getString(res, "cardHolderName", defaultLocale.cardHolderName), cardNickname: Utils.getString(res, "cardNickname", defaultLocale.cardNickname), firstName: Utils.getString(res, "firstName", defaultLocale.firstName), lastName: Utils.getString(res, "lastName", defaultLocale.lastName), billingDetails: Utils.getString(res, "billingDetails", defaultLocale.billingDetails), requiredText: Utils.getString(res, "requiredText", defaultLocale.requiredText), cardHolderNameRequiredText: Utils.getString( res, "cardHolderNameRequiredText", defaultLocale.cardHolderNameRequiredText, ), invalidDigitsCardHolderNameError: Utils.getString( res, "invalidDigitsCardHolderNameError", defaultLocale.invalidDigitsCardHolderNameError, ), invalidDigitsNickNameError: Utils.getString( res, "invalidDigitsNickNameError", defaultLocale.invalidDigitsNickNameError, ), lastNameRequiredText: Utils.getString( res, "lastNameRequiredText", defaultLocale.lastNameRequiredText, ), cardExpiresText: Utils.getString(res, "cardExpiresText", defaultLocale.cardExpiresText), addPaymentMethodLabel: Utils.getString( res, "addPaymentMethodLabel", defaultLocale.addPaymentMethodLabel, ), walletDisclaimer: Utils.getString(res, "walletDisclaimer", defaultLocale.walletDisclaimer), deletePaymentMethod: Utils.getString( res, "deletePaymentMethod", defaultLocale.deletePaymentMethod->Option.getOr("delete"), ), enterValidDigitsText: Utils.getString( res, "enterValidDigitsText", defaultLocale.enterValidDigitsText, ), digitsText: Utils.getString(res, "digitsText", defaultLocale.digitsText), selectCardBrand: Utils.getString( res, "selectCardBrand", defaultLocale.selectCardBrand, ), mandatoryFieldText: Utils.getString( res, "mandatoryFieldText", defaultLocale.mandatoryFieldText, ), } | None => defaultLocale } } let getLocaleStringsFromJson: Js.Json.t => localeStrings = jsonData => { switch jsonData->Js.Json.decodeObject { | Some(res) => getLocaleStrings(res->Utils.getJsonObjectFromRecord) | None => defaultLocale } } //- let useFetchDataFromS3WithGZipDecoding = () => { let apiFunction = CommonHooks.fetchApi let logger = LoggerHook.useLoggerHook() let baseUrl = GlobalHooks.useGetAssetUrlWithVersion()() (~s3Path: string, ~decodeJsonToRecord) => { let endpoint = `${baseUrl}${s3Path}` logger( ~logType=INFO, ~value=`S3 API called - ${endpoint}`, ~category=API, ~eventName=S3_API, (), ) apiFunction(~uri=endpoint, ~method_=Get, ~headers=Dict.make(), ~dontUseDefaultHeader=true, ()) ->GZipUtils.extractJson ->Promise.then(data => { let countryStaterecord = decodeJsonToRecord(data) Promise.resolve(Some(countryStaterecord)) }) ->Promise.catch(_ => { logger( ~logType=ERROR, ~value=`S3 API failed - ${endpoint}`, ~category=API, ~eventName=S3_API, (), ) Promise.resolve(None) }) } }
2,552
10,725
hyperswitch-client-core
src/hooks/LoggerHook.res
.res
open LoggerTypes open LoggerUtils let useCalculateLatency = () => { let (events, _setEvents) = React.useContext(LoggerContext.loggingContext) eventName => { let currentTimestamp = Date.now() let isRequest = eventName->String.includes("_INIT") let latency = switch eventName { | "PAYMENT_ATTEMPT" => { let appRenderedTimestamp = events->Dict.get("APP_RENDERED") switch appRenderedTimestamp { | Some(float) => currentTimestamp -. float | _ => -1. } } | "RETRIEVE_CALL" | "CONFIRM_CALL" | "SESSIONS_CALL" | "PAYMENT_METHODS_CALL" | "CUSTOMER_PAYMENT_METHODS_CALL" => { let logRequestTimestamp = events->Dict.get(eventName ++ "_INIT") switch (logRequestTimestamp, isRequest) { | (Some(_), true) => 0. | (Some(float), _) => currentTimestamp -. float | _ => 0. } } | _ => 0. } latency > 0. ? latency->Float.toString : "" } } let inactiveScreenApiCall = ( ~paymentId, ~publishableKey, ~appId, ~platform, ~session_id, ~events, ~setEvents, ~nativeProp: SdkTypes.nativeProp, ~uri, ) => { let eventName = INACTIVE_SCREEN let updatedEvents = events let firstEvent = updatedEvents->Dict.get(eventName->eventToStrMapper)->Option.isNone let timestamp = Date.now() let logFile = { logType: INFO, timestamp: timestamp->Float.toString, sessionId: session_id, version: nativeProp.hyperParams.sdkVersion, codePushVersion: getClientCoreVersionNoFromRef(), clientCoreVersion: getClientCoreVersionNoFromRef(), component: MOBILE, value: "Inactive Screen", internalMetadata: "", category: USER_EVENT, paymentId, merchantId: publishableKey, ?appId, platform, userAgent: "userAgent", eventName, firstEvent, source: nativeProp.sdkState->SdkTypes.sdkStateToStrMapper, } sendLogs(logFile, uri, nativeProp.publishableKey, nativeProp.hyperParams.appId) updatedEvents->Dict.set(eventName->eventToStrMapper, timestamp) setEvents(updatedEvents) } let timeOut = ref(Nullable.null) let snooze = ( ~paymentId, ~publishableKey, ~appId, ~platform, ~session_id, ~events, ~setEvents, ~nativeProp, ~uri, ) => { timeOut := Nullable.make( setTimeout( () => inactiveScreenApiCall( ~paymentId, ~publishableKey, ~appId, ~platform, ~session_id, ~events, ~setEvents, ~nativeProp, ~uri, ), 2 * 60 * 1000, ), ) } let cancel = () => Nullable.forEach(timeOut.contents, intervalId => clearTimeout(intervalId)) let useLoggerHook = () => { let (nativeProp, _) = React.useContext(NativePropContext.nativePropContext) let (events, setEvents) = React.useContext(LoggerContext.loggingContext) let calculateLatency = useCalculateLatency() let getLoggingEndpointHook = GlobalHooks.useGetLoggingUrl() getClientCoreVersion() ( ~logType, ~value, ~category, ~paymentMethod=?, ~paymentExperience=?, ~internalMetadata=?, ~eventName, ~latency=?, (), ) => { cancel() let updatedEvents = events let firstEvent = updatedEvents->Dict.get(eventName->eventToStrMapper)->Option.isNone let timestamp = Date.now() let latency = switch latency { | Some(latency) => latency->Float.toString | None => calculateLatency(eventName->eventToStrMapper) } let uri = getLoggingEndpointHook() let logFile = { logType, timestamp: timestamp->Float.toString, sessionId: nativeProp.sessionId, version: nativeProp.hyperParams.sdkVersion, codePushVersion: getClientCoreVersionNoFromRef(), clientCoreVersion: getClientCoreVersionNoFromRef(), component: MOBILE, value, internalMetadata: internalMetadata->Option.getOr(""), category, paymentId: String.split(nativeProp.clientSecret, "_secret_")->Array.get(0)->Option.getOr(""), merchantId: nativeProp.publishableKey, appId: ?nativeProp.hyperParams.appId, platform: WebKit.platformString, userAgent: "userAgent", eventName, firstEvent, paymentMethod: paymentMethod->Option.getOr(""), ?paymentExperience, latency, source: nativeProp.sdkState->SdkTypes.sdkStateToStrMapper, } sendLogs(logFile, uri, nativeProp.publishableKey, nativeProp.hyperParams.appId) updatedEvents->Dict.set(eventName->eventToStrMapper, timestamp) setEvents(updatedEvents) snooze( ~paymentId=String.split(nativeProp.clientSecret, "_secret_")->Array.get(0)->Option.getOr(""), ~publishableKey=nativeProp.publishableKey, ~appId=nativeProp.hyperParams.appId, ~platform=WebKit.platformString, ~session_id=nativeProp.sessionId, ~events, ~setEvents, ~nativeProp, ~uri, ) } } let useApiLogWrapper = () => { let logger = useLoggerHook() ( ~logType, ~eventName, ~url, ~statusCode, ~apiLogType, ~data, ~paymentMethod=?, ~paymentExperience=?, (), ) => { let (value, internalMetadata) = switch apiLogType { | Request => ([("url", url->JSON.Encode.string)], []) | Response => ( [("url", url->JSON.Encode.string), ("statusCode", statusCode->JSON.Encode.string)], [("response", data)], ) | NoResponse => ( [ ("url", url->JSON.Encode.string), ("statusCode", "504"->JSON.Encode.string), ("response", data), ], [("response", data)], ) | Err => ( [ ("url", url->JSON.Encode.string), ("statusCode", statusCode->JSON.Encode.string), ("response", data), ], [("response", data)], ) } logger( ~logType, ~value=value->Dict.fromArray->JSON.Encode.object->JSON.stringify, ~internalMetadata=internalMetadata->Dict.fromArray->JSON.Encode.object->JSON.stringify, ~category=API, ~eventName, ~paymentMethod?, ~paymentExperience?, (), ) } }
1,512
10,726
hyperswitch-client-core
src/hooks/FontFamily.res
.res
let convertFontToGoogleFontURL = fontName => { let normalizedFontName = fontName ->String.splitByRegExp("/[_\s]+/"->RegExp.fromString) ->Array.map(word => switch word { | Some(word) => word->String.charAt(0)->String.toUpperCase ++ word->String.slice(~start=1, ~end=word->String.length)->String.toLowerCase | None => "" } ) ->Array.join("+") Window.useLink(`https://fonts.googleapis.com/css2?family=${normalizedFontName}`)->ignore normalizedFontName } let useCustomFontFamily = () => { let (nativeProp, _) = React.useContext(NativePropContext.nativePropContext) switch ThemebasedStyle.itemToObj( ThemebasedStyle.lightRecord, nativeProp.configuration.appearance, false, ).fontFamily { | CustomFont(font) => if ReactNative.Platform.os === #web { convertFontToGoogleFontURL(font) } else { font } | DefaultAndroid => "Roboto" | DefaultIOS => "System" | DefaultWeb => "Inter,-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica Neue,Ubuntu,sans-serif" } }
270
10,727
hyperswitch-client-core
src/hooks/SamsungPay.res
.res
open SamsungPayType type samsungPayWalletValidity = Checking | Valid | Invalid | Not_Started let val = ref(Not_Started) let isSamsungPayValid = state => { state != Checking && state != Not_Started } let useSamsungPayValidityHook = () => { let (state, setState) = React.useState(_ => val.contents) let isSamsungPayAvailable = SamsungPayModule.isAvailable let (allApiData, _) = React.useContext(AllApiDataContext.allApiDataContext) let (nativeProp, _) = React.useContext(NativePropContext.nativePropContext) let sessionToken = allApiData.sessions->getSamsungPaySessionObject let stringifiedSessionToken = sessionToken ->Utils.getJsonObjectFromRecord ->JSON.stringify let checkSPayStatus = () => { Promise.make((resolve, _reject) => SamsungPayModule.checkSamsungPayValidity(stringifiedSessionToken, status => { if status->ThreeDsUtils.isStatusSuccess { resolve(Valid) } else { resolve(Invalid) } }) ) } let isSamsungPayPresentInPML = { let isPresentInAccPML = allApiData.paymentList->Array.reduce(false, (acc, item) => { let isSamsungPayPresent = switch item { | WALLET(walletVal) => walletVal.payment_method_type_wallet == SAMSUNG_PAY | _ => false } acc || isSamsungPayPresent }) let isPresentInCustPML = switch allApiData.savedPaymentMethods { | Some({pmList: Some(pmList)}) => pmList->Array.reduce(false, (acc, item) => { let isSamsungPayPresent = switch item { | SAVEDLISTWALLET(val) => val.walletType->Option.getOr("")->SdkTypes.walletNameToTypeMapper == SAMSUNG_PAY | _ => false } acc || isSamsungPayPresent }) | _ => false } isPresentInCustPML || isPresentInAccPML } let isSamsungDevice = nativeProp.hyperParams.deviceBrand->Option.getOr("") == "samsung" let handleSPay = async () => { setState(_ => { val := Checking Checking }) if sessionToken.wallet_name != NONE && isSamsungPayPresentInPML && isSamsungDevice { let status = await checkSPayStatus() setState(_ => { val := status status }) } else { setState(_ => { val := Invalid Invalid }) } } React.useEffect2(() => { switch (val.contents, isSamsungPayAvailable, allApiData.sessions) { | (_, false, _) => setState(_ => { val := Invalid Invalid }) | (Not_Started, true, Some(_)) => handleSPay()->ignore | (_, _, _) => () }->ignore None }, (isSamsungPayAvailable, allApiData.sessions)) state } @react.component let make = ( ~walletType: PaymentMethodListType.payment_method_types_wallet, ~sessionObject: SessionsType.sessions, ) => { let samsungPayStatus = useSamsungPayValidityHook() samsungPayStatus == Checking ? <CustomLoader /> : <ButtonElement walletType sessionObject /> }
737
10,728
hyperswitch-client-core
src/hooks/WindowDimension.res
.res
type mediaView = Mobile | Tablet | Desktop let useMediaView = () => { let {width} = ReactNative.Dimensions.useWindowDimensions() () => { if width < 441.0 { Mobile } else if width < 830.0 { Tablet } else { Desktop } } } let useIsMobileView = () => { useMediaView()() == Mobile }
98
10,729
hyperswitch-client-core
src/hooks/PMListModifier.res
.res
type hoc = { name: string, componentHoc: ( ~isScreenFocus: bool, ~setConfirmButtonDataRef: React.element => unit, ) => React.element, } type walletProp = { walletType: PaymentMethodListType.payment_method_types_wallet, sessionObject: SessionsType.sessions, } type paymentList = { tabArr: array<hoc>, elementArr: array<React.element>, } let useListModifier = () => { let (allApiData, _) = React.useContext(AllApiDataContext.allApiDataContext) let handleSuccessFailure = AllPaymentHooks.useHandleSuccessFailure() let (addApplePay, addGooglePay) = WebButtonHook.usePayButton() let samsungPayStatus = SamsungPay.useSamsungPayValidityHook() // React.useMemo2(() => { if allApiData.paymentList->Array.length == 0 { handleSuccessFailure( ~apiResStatus={ { message: "No eligible Payment Method available", code: "PAYMENT_METHOD_NOT_AVAILABLE", type_: "failed", status: "failed", } }, ~closeSDK=true, (), ) { tabArr: [], elementArr: [], } } else { let redirectionList = Types.defaultConfig.redirectionList allApiData.paymentList->Array.reduce( { tabArr: [], elementArr: [], }, (accumulator: paymentList, payment_method) => { switch switch payment_method { | CARD(cardVal) => Some({ name: "Card", componentHoc: (~isScreenFocus, ~setConfirmButtonDataRef) => <CardParent cardVal isScreenFocus setConfirmButtonDataRef />, }) | PAY_LATER(payLaterVal) => let fields = redirectionList ->Array.find(l => l.name == payLaterVal.payment_method_type) ->Option.getOr(Types.defaultRedirectType) let klarnaSDKCheck = if ( payLaterVal.payment_method_type == "klarna" && payLaterVal.payment_experience ->Array.find(x => x.payment_experience_type_decode === INVOKE_SDK_CLIENT) ->Option.isSome ) { KlarnaModule.klarnaReactPaymentView->Option.isSome } else { true } klarnaSDKCheck ? Some({ name: fields.text, componentHoc: (~isScreenFocus, ~setConfirmButtonDataRef) => <Redirect isScreenFocus redirectProp={PAY_LATER(payLaterVal)} fields isDynamicFields={payLaterVal.payment_method_type !== "klarna"} dynamicFields=payLaterVal.required_field setConfirmButtonDataRef />, }) : None | BANK_REDIRECT(bankRedirectVal) => let fields = redirectionList ->Array.find(l => l.name == bankRedirectVal.payment_method_type) ->Option.getOr(Types.defaultRedirectType) Some({ name: fields.text, componentHoc: (~isScreenFocus, ~setConfirmButtonDataRef) => <Redirect isScreenFocus redirectProp=BANK_REDIRECT(bankRedirectVal) fields setConfirmButtonDataRef />, }) | WALLET(walletVal) => let fields = redirectionList ->Array.find(l => l.name == walletVal.payment_method_type) ->Option.getOr(Types.defaultRedirectType) let sessionObject = switch allApiData.sessions { | Some(sessionData) => sessionData ->Array.find(item => item.wallet_name == walletVal.payment_method_type_wallet) ->Option.getOr(SessionsType.defaultToken) | _ => SessionsType.defaultToken } let exp = walletVal.payment_experience->Array.find(x => x.payment_experience_type_decode === INVOKE_SDK_CLIENT ) switch walletVal.payment_method_type_wallet { | GOOGLE_PAY => WebKit.platform !== #ios && WebKit.platform !== #iosWebView && WebKit.platform !== #next && sessionObject.wallet_name !== NONE && allApiData.additionalPMLData.mandateType != NORMAL ? { if ReactNative.Platform.os === #web { addGooglePay(~sessionObject, ~requiredFields=walletVal.required_field) } Some({ name: fields.text, componentHoc: (~isScreenFocus, ~setConfirmButtonDataRef) => <Redirect isScreenFocus redirectProp=WALLET(walletVal) fields setConfirmButtonDataRef sessionObject />, }) //exp } : None | PAYPAL => exp->Option.isNone && allApiData.additionalPMLData.mandateType != NORMAL && PaypalModule.payPalModule->Option.isSome ? Some({ name: fields.text, componentHoc: (~isScreenFocus, ~setConfirmButtonDataRef) => <Redirect isScreenFocus redirectProp=WALLET(walletVal) fields setConfirmButtonDataRef sessionObject />, }) : walletVal.payment_experience ->Array.find(x => x.payment_experience_type_decode === REDIRECT_TO_URL) ->Option.isSome ? Some({ name: fields.text, componentHoc: (~isScreenFocus, ~setConfirmButtonDataRef) => <Redirect isScreenFocus redirectProp=WALLET(walletVal) fields setConfirmButtonDataRef />, }) : None // walletVal.payment_experience->Array.find( // x => x.payment_experience_type_decode === REDIRECT_TO_URL, // ) // : exp | APPLE_PAY => WebKit.platform !== #android && WebKit.platform !== #androidWebView && WebKit.platform !== #next && sessionObject.wallet_name !== NONE && allApiData.additionalPMLData.mandateType != NORMAL ? { if ReactNative.Platform.os === #web { Promise.make((resolve, _) => { addApplePay(~sessionObject, ~resolve) }) // ->Promise.then(isApplePaySupported => { // isApplePaySupported ? exp : None // Promise.resolve() // }) ->ignore } Some({ name: fields.text, componentHoc: (~isScreenFocus, ~setConfirmButtonDataRef) => <Redirect isScreenFocus redirectProp=WALLET(walletVal) fields setConfirmButtonDataRef sessionObject />, }) //exp } : None | _ => Some({ name: fields.text, componentHoc: (~isScreenFocus, ~setConfirmButtonDataRef) => <Redirect isScreenFocus isDynamicFields=true dynamicFields=walletVal.required_field redirectProp=WALLET(walletVal) fields setConfirmButtonDataRef />, }) } | OPEN_BANKING(openBankingVal) => let fields = redirectionList ->Array.find(l => l.name == openBankingVal.payment_method_type) ->Option.getOr(Types.defaultRedirectType) Plaid.isAvailable ? Some({ name: fields.text, componentHoc: (~isScreenFocus, ~setConfirmButtonDataRef) => <Redirect isScreenFocus redirectProp=OPEN_BANKING(openBankingVal) fields setConfirmButtonDataRef />, }) : None | CRYPTO(cryptoVal) => let fields = redirectionList ->Array.find(l => l.name == cryptoVal.payment_method_type) ->Option.getOr(Types.defaultRedirectType) Some({ name: fields.text, componentHoc: (~isScreenFocus, ~setConfirmButtonDataRef) => <Redirect isScreenFocus redirectProp=CRYPTO(cryptoVal) fields setConfirmButtonDataRef />, }) | BANK_DEBIT(bankDebitVal) => let fields = redirectionList ->Array.find(l => l.name == bankDebitVal.payment_method_type) ->Option.getOr(Types.defaultRedirectType) Some({ name: fields.text, componentHoc: (~isScreenFocus, ~setConfirmButtonDataRef) => <Redirect isScreenFocus isDynamicFields={true} dynamicFields={bankDebitVal.required_field} redirectProp=BANK_DEBIT(bankDebitVal) fields setConfirmButtonDataRef />, }) } { | Some(tab) => let isInvalidScreen = tab.name == "" || accumulator.tabArr ->Array.find((item: hoc) => { item.name == tab.name }) ->Option.isSome if !isInvalidScreen { accumulator.tabArr->Array.push(tab) } | None => () } // if !allApiData.isMandate { switch switch payment_method { | WALLET(walletVal) => let sessionObject = switch allApiData.sessions { | Some(sessionData) => sessionData ->Array.find(item => item.wallet_name == walletVal.payment_method_type_wallet) ->Option.getOr(SessionsType.defaultToken) | _ => SessionsType.defaultToken } let exp = walletVal.payment_experience->Array.find(x => x.payment_experience_type_decode === INVOKE_SDK_CLIENT ) switch switch walletVal.payment_method_type_wallet { | GOOGLE_PAY => WebKit.platform !== #ios && WebKit.platform !== #iosWebView && WebKit.platform !== #next && sessionObject.wallet_name !== NONE && sessionObject.connector !== "trustpay" ? { if ReactNative.Platform.os === #web { addGooglePay(~sessionObject, ~requiredFields=walletVal.required_field) } exp } : None | SAMSUNG_PAY => exp->Option.isSome && SamsungPayModule.isAvailable && samsungPayStatus == SamsungPay.Valid ? exp : None | PAYPAL => exp->Option.isSome && PaypalModule.payPalModule->Option.isSome ? exp : walletVal.payment_experience->Array.find(x => x.payment_experience_type_decode === REDIRECT_TO_URL ) | APPLE_PAY => WebKit.platform !== #android && WebKit.platform !== #androidWebView && WebKit.platform !== #next && sessionObject.wallet_name !== NONE ? { if ReactNative.Platform.os === #web { Promise.make((resolve, _) => { addApplePay(~sessionObject, ~resolve) }) // ->Promise.then(isApplePaySupported => { // isApplePaySupported ? exp : None // Promise.resolve() // }) ->ignore } exp } : None | _ => None } { | None => None | Some(exp) => Some({ walletType: { payment_method: walletVal.payment_method, payment_method_type: walletVal.payment_method_type, payment_method_type_wallet: walletVal.payment_method_type_wallet, payment_experience: [exp], required_field: walletVal.required_field, }, sessionObject, }) } | _ => None } { | Some(walletProp) => accumulator.elementArr ->Array.push( walletProp.walletType.payment_method_type_wallet == SAMSUNG_PAY ? <SamsungPay key=walletProp.walletType.payment_method_type walletType=walletProp.walletType sessionObject={walletProp.sessionObject} /> : <ButtonElement key=walletProp.walletType.payment_method_type walletType=walletProp.walletType sessionObject={walletProp.sessionObject} />, ) ->ignore | None => () } // } accumulator }, ) } // }, (pmList, sessionData)) } let widgetModifier = ( pmList: array<PaymentMethodListType.payment_method>, sessionData: AllApiDataContext.sessions, widgetType, confirm, ) => { let modifiedList = pmList->Array.reduce([], (accumulator, payment_method) => { switch payment_method { | WALLET(walletVal) => widgetType == walletVal.payment_method_type_wallet ? { let sessionObject = switch sessionData { | Some(sessionData) => sessionData ->Array.find(item => item.wallet_name == walletVal.payment_method_type_wallet) ->Option.getOr(SessionsType.defaultToken) | _ => SessionsType.defaultToken } let exp = walletVal.payment_experience->Array.find(x => x.payment_experience_type_decode === INVOKE_SDK_CLIENT ) switch switch walletVal.payment_method_type_wallet { | GOOGLE_PAY => WebKit.platform !== #ios && WebKit.platform !== #iosWebView && sessionObject.wallet_name !== NONE ? exp : None | PAYPAL => exp->Option.isNone ? walletVal.payment_experience->Array.find(x => x.payment_experience_type_decode === REDIRECT_TO_URL ) : exp | APPLE_PAY => WebKit.platform !== #android && WebKit.platform !== #androidWebView && sessionObject.wallet_name !== NONE ? exp : None | _ => None } { | Some(exp) => accumulator ->Array.push( <ButtonElement walletType={ payment_method: walletVal.payment_method, payment_method_type: walletVal.payment_method_type, payment_method_type_wallet: walletVal.payment_method_type_wallet, payment_experience: [exp], required_field: walletVal.required_field, } sessionObject confirm />, ) ->ignore | None => () } } : () | _ => () } accumulator }) switch modifiedList->Array.length { | 0 => Some(React.null) | _ => modifiedList->Array.get(0) } }
3,043
10,730