import React, { Fragment, useRef, useState } from 'react'; import { ActivityIndicator, Platform, StyleSheet, Text, View, } from 'react-native'; import { WebView, type WebViewMessageEvent } from 'react-native-webview'; import { serverSdkBaseUrl } from '../../lib/config'; type RegisterSuccessType = { customerRef: string; walletId: string; }; type OmnipayProps = { color: string; env: 'dev' | 'prod'; publicKey: string; phoneNumber: string; onRegistrationSuccessful?: ({ customerRef, walletId, }: RegisterSuccessType) => void; onClose?: () => void; }; // type PostMessage = { // [key: string]: unknown; // }; type Status = 'error' | 'loading' | 'success'; export const Registration = ({ color, env, publicKey, phoneNumber, onRegistrationSuccessful, onClose, }: OmnipayProps): JSX.Element => { const webviewRef = useRef(null); const [webviewStatus, setWebviewStatus] = useState('loading'); const webHost = getWebHost(); const webUrl = getWebUrl(); const onWebviewMount = ` window.nativeOs = ${Platform.OS}; true; `; function getWebHost() { return serverSdkBaseUrl[env]; } function getWebUrl() { const themeColor = color.includes('#') ? color.split('#')[1] : color; return `${webHost}auth/register?theme=${themeColor}&publicKey=${publicKey}&phoneNumber=${phoneNumber}`; } // function postMessage(data: PostMessage) { // if (!webviewRef.current) { // return; // } // try { // webviewRef.current.postMessage(JSON.stringify(data)); // } catch (error) {} // } async function onWebviewMessage(e: WebViewMessageEvent) { try { if (e.nativeEvent && e.nativeEvent.data) { const eventData = JSON.parse(e.nativeEvent.data); const { dataKey, dataValue } = eventData; if (dataKey === 'customer.registered') { if (onRegistrationSuccessful) { onRegistrationSuccessful({ customerRef: dataValue.customerRef, walletId: dataValue.walletId, }); } return; } if (dataKey === 'close.registration') { if (onClose) { onClose(); } return; } } } catch (error) {} } if (!publicKey.includes('OMNIPUBKEY_')) { return Invalid public key; } if (phoneNumber.length < 10) { return Invalid phone number; } if (color.length < 3) { return Invalid color; } if (!['dev', 'prod'].includes(env)) { return Invalid environment; } return ( setWebviewStatus('success')} /> {webviewStatus === 'loading' && ( )} ); }; const styles = StyleSheet.create({ hide: { display: 'none', }, full: { flex: 1, width: '100%', height: '100%', }, webview: { flex: 1, width: '100%', height: '100%', }, webviewLoader: { zIndex: 3, backgroundColor: 'white', alignItems: 'center', justifyContent: 'center', flex: 1, width: '100%', height: '100%', position: 'absolute', top: 0, left: 0, }, });