import React, { useEffect, useMemo, useRef, useState } from 'react'; import { ActivityIndicator, Modal,BackHandler, Keyboard, LayoutAnimation, Linking, NativeEventEmitter, NativeModules, Platform, Pressable, SafeAreaView, StatusBar, StyleSheet, Text, View } from 'react-native'; import { WebView } from 'react-native-webview'; import { EnxChatController } from '../controller'; import { useControllerVersion } from '../hooks'; import { defaultTheme, EnxAction, EnxBotConfig, EnxChatTheme, EnxConnectionStatus, EnxMessage, } from '../types'; import { requestCameraAndMicrophoneForMedia, requestLocationForWebView } from '../mediaPermissions'; import { ChatList, ChatListHandle } from './ChatList'; import { InputBar } from './InputBar'; const CHAT_URL = 'https://voiceassist.enablex.io/chatbot_mobi/index.html'; /** * True when running on iOS and the EnxChatBridge native module is available. * Video calls on iOS are handled by the same EnxChatBridge module — it exposes * openVideoCall / closeVideoCall and emits EnxVideoCallEvent. * No React WebView is rendered for video calls on this platform. */ const usesNativeVideoCall = Platform.OS === 'ios' && !!NativeModules.EnxChatBridge; /** * Lets pages use navigator.geolocation / getUserMedia and receive OS + WebView permission flows * (iOS: WKWebView media capture + location prompts; Android: WebChromeClient → Activity permission dialogs). */ const webViewBrowserPermissionProps = { geolocationEnabled: true, mediaCapturePermissionGrantType: 'prompt' as const, ...(Platform.OS === 'android' ? { allowsProtectedMedia: true, } : {}), }; /** * Injected into the Android hidden WebView before the page scripts run. * Sets up window.ReactNativeWebView forwarding and console capture. * Not used on iOS — the native WKWebView module handles that side. */ const androidBridge = ` (function() { function sendToRN(data) { try { var msg = typeof data === 'string' ? data : JSON.stringify(data); if (window.ReactNativeWebView && typeof window.ReactNativeWebView.postMessage === 'function') { window.ReactNativeWebView.postMessage(msg); } } catch (e) {} } var originalLog = console.log; var originalError = console.error; var originalWarn = console.warn; // The chat page fires events via console.log(JSON.stringify({event, data})). // Forward the raw string directly so onMessage can parse it as a chat event. // Non-string / multi-arg calls are wrapped in a CONSOLE envelope (debug only). console.log = function() { var args = Array.prototype.slice.call(arguments); if (args.length >= 1 && typeof args[0] === 'string') { sendToRN(args[0]); } else { sendToRN({ type: 'CONSOLE', level: 'log', data: args }); } originalLog.apply(console, args); }; console.error = function() { var args = Array.prototype.slice.call(arguments); sendToRN({ type: 'CONSOLE', level: 'error', data: args }); originalError.apply(console, args); }; console.warn = function() { var args = Array.prototype.slice.call(arguments); sendToRN({ type: 'CONSOLE', level: 'warn', data: args }); originalWarn.apply(console, args); }; window.ReactNativeBridge = { postMessage: function(data) { sendToRN(data); } }; })(); true; `; type Props = { config?: EnxBotConfig; controller?: EnxChatController; theme?: Partial; showCallingOptions?: boolean; onMessageReceived?: (message: EnxMessage) => void; onMessageSent?: (message: EnxMessage) => void; onError?: (message: string, type: string) => void; onBotInfo?: (info: Record) => void; onAudioCall?: () => void; onVideoCall?: () => void; /** Called when the bot sends a video-room URL; the widget also opens a full-screen WebView unless you handle it yourself. */ onVideoCallRequest?: (url: string) => void; /** After `audio_video_action: stop` from the bot; video modal is closed before this runs. */ onVideoCallEnded?: () => void; /** * Android: opt-in only. When true, request location once on mount. Default false — location is asked when * the chat page calls `navigator.geolocation` (WebView flow), not when opening the widget. */ proactiveLocationPermission?: boolean; }; export const EnxChatWidget = ({ config, controller, theme, showCallingOptions = false, onMessageReceived, onMessageSent, onError, onBotInfo, onAudioCall, onVideoCall, onVideoCallRequest, onVideoCallEnded, proactiveLocationPermission = false, }: Props): React.JSX.Element => { const ownsController = !controller; const managed = useMemo(() => (controller ? controller : new EnxChatController(config!)), [config, controller]); const webRef = useRef(null); const chatListRef = useRef(null); const [videoCallUrl, setVideoCallUrl] = useState(null); // iOS keyboard avoidance: extra bottom padding pushed in when the keyboard // appears so the InputBar stays above the keyboard. // Android is handled natively via windowSoftInputMode="adjustResize" in // AndroidManifest.xml — no JS changes needed on that platform. const [iosBottomPad, setIosBottomPad] = useState(0); useControllerVersion(managed); // ── iOS keyboard avoidance ───────────────────────────────────────────────── // We listen to keyboardWillShow/Hide (fired before the keyboard animates in) // and apply e.endCoordinates.height as paddingBottom on the root container. // This is the keyboard panel height measured from the physical screen bottom — // exactly the amount we need to push the InputBar up regardless of where the // widget sits in the host app's layout hierarchy. // LayoutAnimation.configureNext runs the layout change on the native thread in // sync with the iOS keyboard spring so there is no JS-animation jank. useEffect(() => { if (Platform.OS !== 'ios') return; const onShow = Keyboard.addListener('keyboardWillShow', (e) => { LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut); setIosBottomPad(e.endCoordinates.height - 35); // Scroll to the latest message once the keyboard animation has settled. // We wait for the LayoutAnimation duration (≈300 ms) so the FlatList has // its final, smaller frame before we call scrollToEnd — calling it earlier // would land at the wrong offset because the metrics haven't updated yet. setTimeout(() => chatListRef.current?.scrollToBottom(true), 320); }); const onHide = Keyboard.addListener('keyboardWillHide', () => { LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut); setIosBottomPad(0); // After the keyboard hides the list grows back; scroll to bottom so the // last message stays visible in the expanded space. setTimeout(() => chatListRef.current?.scrollToBottom(true), 320); }); return () => { onShow.remove(); onHide.remove(); }; }, []); useEffect(() => { if (proactiveLocationPermission) void requestLocationForWebView(); }, [proactiveLocationPermission]); useEffect(() => { if (managed.bridge.usesNativePath) { // iOS: the WKWebView is owned by the native EnxChatBridge module. // We just initialise the controller and start the native module. void managed.initialize(); managed.bridge.initializeNative(); } else { // Android: the hidden react-native-webview WebView handles communication. managed.bridge.attachWebViewRef(webRef); void managed.initialize(); } return () => { managed.bridge.resetWebViewSession(); if (ownsController) void managed.dispose(); }; }, [managed, ownsController]); useEffect(() => { managed.onMessageReceived = onMessageReceived; managed.onError = onError; managed.onBotInfoReceived = onBotInfo; }, [managed, onBotInfo, onError, onMessageReceived]); useEffect(() => { managed.onVideoCallRequest = (url: string) => { void (async () => { onVideoCallRequest?.(url); await requestCameraAndMicrophoneForMedia(); if (usesNativeVideoCall) { // iOS — openVideoCall is exported by the same EnxChatBridge module. // It presents EnxVideoCallViewController (EnxVideoCallView.swift) // full-screen with a WKWebView. No React WebView is rendered. NativeModules.EnxChatBridge.openVideoCall(url); } else { // Android — show the in-tree overlay WebView. setVideoCallUrl(url); } })(); }; return () => { managed.onVideoCallRequest = undefined; }; }, [managed, onVideoCallRequest]); useEffect(() => { managed.onVideoCallEnd = () => { if (usesNativeVideoCall) { // iOS — closeVideoCall is exported by the same EnxChatBridge module. // The Swift side dismisses silently (no 'closed' event) since the bot // signal already drives this path. NativeModules.EnxChatBridge.closeVideoCall(); } else { // Android — hide the in-tree overlay. setVideoCallUrl(null); } onVideoCallEnded?.(); }; return () => { managed.onVideoCallEnd = undefined; }; }, [managed, onVideoCallEnded]); // iOS only — listen for 'EnxVideoCallEvent' on the existing EnxChatBridge // module. Fires when the user taps the close button inside // EnxVideoCallViewController (user-initiated close, not a bot-driven stop). useEffect(() => { if (!usesNativeVideoCall) return; const emitter = new NativeEventEmitter(NativeModules.EnxChatBridge); const sub = emitter.addListener('EnxVideoCallEvent', (payload: Record) => { if (String(payload.event ?? '') === 'closed') { onVideoCallEnded?.(); } }); return () => sub.remove(); }, [onVideoCallEnded]); // Android only — intercept hardware back press to close the video overlay. // On iOS the native UIViewController handles its own dismiss gesture. useEffect(() => { if (usesNativeVideoCall || !videoCallUrl) return; const sub = BackHandler.addEventListener('hardwareBackPress', () => { setVideoCallUrl(null); return true; // consumed — do not bubble to the navigator }); return () => sub.remove(); }, [videoCallUrl]); const mergedTheme: EnxChatTheme = { ...defaultTheme, ...theme }; const closeVideoCall = (): void => setVideoCallUrl(null); const videoCallTopPad = Platform.OS === 'android' ? (StatusBar.currentHeight ?? 0) + 8 : 52; const Banner = (): React.JSX.Element | null => { if (managed.status === EnxConnectionStatus.Connected) return null; if (managed.status === EnxConnectionStatus.Loading) return ; if (managed.status === EnxConnectionStatus.Disconnected) return void managed.reconnect()} />; if (managed.status === EnxConnectionStatus.Reconnecting) return ; return void managed.reconnect()} />; }; return ( {/* Android only: hidden WebView that loads the chat page and bridges communication. On iOS this is handled entirely by the native EnxChatBridge module (WKWebView). */} {!managed.bridge.usesNativePath && ( managed.bridge.initializeAfterPageLoad()} /> )} {managed.status === EnxConnectionStatus.Loading && managed.messages.length === 0 ? ( Loading chat... ) : ( void managed.sendSuggestions(titles, type)} onActionTap={(action: EnxAction) => { if (action.url) void Linking.openURL(action.url); }} /> )} { void managed.sendText(text); onMessageSent?.({ sender: 'user' as never, type: 'text' as never, timestamp: new Date(), text }); }} onSendFile={(payload) => { if (!payload.base64) return; void managed.sendFile(payload); }} onAudioCall={onAudioCall} onVideoCall={onVideoCall} /> {/* ── Video call full-screen overlay (Android only) ────────────────────── On iOS the video call is handled entirely by EnxVideoCallViewController (a native UIViewController with a full-screen WKWebView) opened via NativeModules.EnxVideoCallBridge.openVideoCall(). Nothing is rendered here on that platform. On Android the overlay is an absolutely-positioned in-tree View that sits above all chat UI. Using Modal here caused a blank-page bug (react-native-webview + Modal on New Architecture) so we use an absolute View instead. Android hardware-back is handled above. */} {!usesNativeVideoCall && !!videoCallUrl && ( ← {!!videoCallUrl && ( )} )} ); }; const StatusBanner = ({ label, color, loading, action, onAction, }: { label: string; color: string; loading?: boolean; action?: string; onAction?: () => void; }): React.JSX.Element => ( {label} {loading && } {!loading && action && onAction && ( {action} )} ); const styles = StyleSheet.create({ root: { flex: 1 }, // ── Video call overlay ────────────────────────────────────────────────────── // Absolutely fills the root View and sits above all other children (rendered // last in the tree). zIndex is set as a belt-and-suspenders guard. videoCallOverlay: { ...StyleSheet.absoluteFillObject, zIndex: 999, backgroundColor: '#f3f4f6', }, videoCallRoot: { flex: 1, backgroundColor: '#f3f4f6' }, // SafeAreaView fills the overlay so content clears notch / status bar. videoCallSafe: { flex: 1 }, videoCallHeader: { flexDirection: 'row', alignItems: 'center', paddingHorizontal: 8, paddingVertical: 8, backgroundColor: '#f3f4f6', }, videoCallBackHit: { paddingVertical: 10, paddingHorizontal: 12, justifyContent: 'center', alignItems: 'center' }, videoCallBackArrow: { color: '#111827', fontSize: 28, fontWeight: '300', lineHeight: 32 }, videoCallWeb: { flex: 1, backgroundColor: '#000000' }, hidden: { position: 'absolute', left: 0, top: 0, width: 1, height: 1, opacity: 0.01 }, banner: { minHeight: 32, paddingHorizontal: 12, paddingVertical: 6, flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' }, bannerTxt: { color: '#fff', fontSize: 13, fontWeight: '500' }, bannerAction: { color: '#fff', fontWeight: '700' }, body: { flex: 1 }, center: { flex: 1, alignItems: 'center', justifyContent: 'center' }, centerTxt: { marginTop: 10, color: '#4b5563' }, });