@robylon/react-native-sdk 2.0.21 → 2.0.22-staging.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/lib/commonjs/config.js +1 -1
  2. package/lib/commonjs/config.js.map +1 -1
  3. package/lib/commonjs/constants.js +1 -1
  4. package/lib/commonjs/constants.js.map +1 -1
  5. package/lib/commonjs/versions/version.dev.js +1 -1
  6. package/lib/commonjs/versions/version.staging.js +1 -1
  7. package/lib/module/config.js +1 -1
  8. package/lib/module/config.js.map +1 -1
  9. package/lib/module/constants.js +1 -1
  10. package/lib/module/constants.js.map +1 -1
  11. package/lib/module/openChatbot.js.map +1 -1
  12. package/lib/module/versions/version.dev.js +1 -1
  13. package/lib/module/versions/version.staging.js +1 -1
  14. package/lib/typescript/versions/version.dev.d.ts +1 -1
  15. package/lib/typescript/versions/version.staging.d.ts +1 -1
  16. package/package.json +1 -1
  17. package/src/Chatbotsdk.tsx +782 -0
  18. package/src/FloatingButton/launchers/ImageLauncher.tsx +75 -0
  19. package/src/FloatingButton/launchers/TextLauncher.tsx +84 -0
  20. package/src/FloatingButton/launchers/TextualImageLauncher.tsx +133 -0
  21. package/src/FloatingButton.tsx +97 -0
  22. package/src/LoadingIndicator.tsx +11 -0
  23. package/src/Toast.tsx +65 -0
  24. package/src/components/DebugButton.tsx +46 -0
  25. package/src/components/ErrorBoundary.tsx +38 -0
  26. package/src/config.ts +4 -0
  27. package/src/constants/errorConstants.ts +21 -0
  28. package/src/constants/fontStyles.ts +3 -0
  29. package/src/constants.ts +4 -0
  30. package/src/global.d.ts +11 -0
  31. package/src/hooks/useChatbotEvents.ts +93 -0
  32. package/src/index.tsx +10 -0
  33. package/src/openChatbot.ts +11 -0
  34. package/src/openChatbot.tsx +0 -0
  35. package/src/services/ErrorTrackingService.ts +217 -0
  36. package/src/types/events.ts +25 -0
  37. package/src/types/react-native-flipper-performance-plugin.d.ts +3 -0
  38. package/src/types/react-native-globals.d.ts +10 -0
  39. package/src/utils/animations.ts +120 -0
  40. package/src/utils/colorUtils.ts +35 -0
  41. package/src/utils/cookieUtils.ts +7 -0
  42. package/src/utils/debugConfig.ts +56 -0
  43. package/src/utils/debugMenu.ts +14 -0
  44. package/src/utils/errorHandler.ts +58 -0
  45. package/src/utils/logger.ts +14 -0
  46. package/src/utils/systemInfo.ts +84 -0
  47. package/src/utils/webViewStorage.ts +62 -0
  48. package/src/version.ts +2 -0
  49. package/src/versions/version.dev.ts +2 -0
  50. package/src/versions/version.production.ts +2 -0
  51. package/src/versions/version.staging.ts +2 -0
@@ -0,0 +1,782 @@
1
+ import React, {
2
+ useState,
3
+ useEffect,
4
+ useRef,
5
+ useMemo,
6
+ useCallback,
7
+ } from "react";
8
+ import {
9
+ View,
10
+ StyleSheet,
11
+ Animated,
12
+ Dimensions,
13
+ Platform,
14
+ StatusBar,
15
+ PixelRatio,
16
+ FlexAlignType,
17
+ } from "react-native";
18
+ import { WebView, WebViewMessageEvent } from "react-native-webview";
19
+ import FloatingButton from "./FloatingButton";
20
+ import { API_URL, BASE_CHATBOT_URL } from "./constants";
21
+ import { getSystemInfo, getBrowserAndOSInfoScript } from "./utils/systemInfo";
22
+ import { useChatbotEvents } from "./hooks/useChatbotEvents";
23
+ import { ChatbotEventType, ChatbotEventHandler } from "./types/events";
24
+ import { logger } from "./utils/logger";
25
+ import { enableNetworkDebug, enableWebViewDebug } from "./utils/debugConfig";
26
+ import DebugButton from "./components/DebugButton";
27
+ import { ErrorBoundary } from "./components/ErrorBoundary";
28
+ import {
29
+ ErrorCodes,
30
+ ErrorTypes,
31
+ ErrorMessages,
32
+ } from "./constants/errorConstants";
33
+ import { setupGlobalErrorHandlers } from "./utils/errorHandler";
34
+ import { errorTracker } from "./services/ErrorTrackingService";
35
+ import { generateUUID } from "./utils/cookieUtils";
36
+ import {
37
+ StorageMessageType,
38
+ StorageMessage,
39
+ getStorageScript,
40
+ createStorageMessage,
41
+ } from "./utils/webViewStorage";
42
+ import { animateWebViewOpen, animateWebViewClose } from "./utils/animations";
43
+
44
+ export interface ChatbotProps {
45
+ api_key: string;
46
+ user_id?: string | null | number;
47
+ user_token?: string;
48
+ user_profile?: {
49
+ email?: string;
50
+ name?: string;
51
+ mobile?: string;
52
+ is_test_user?: boolean;
53
+ };
54
+ onEvent?: ChatbotEventHandler;
55
+ }
56
+
57
+ interface InternalChatbotProps extends ChatbotProps {
58
+ show_floating_button?: boolean;
59
+ onMessage?: (message: any) => void;
60
+ isFullScreen?: boolean;
61
+ enableAnimation?: boolean;
62
+ onOpen?: () => void;
63
+ onClose?: () => void;
64
+ }
65
+
66
+ interface ChatbotMessage {
67
+ type: string;
68
+ data?: any;
69
+ level?: string;
70
+ }
71
+
72
+ export enum ChatbotInterfaceType {
73
+ WIDGET = "WIDGET",
74
+ POPOVER = "POPOVER",
75
+ EMBED = "EMBED",
76
+ }
77
+
78
+ export enum WidgetPositionEnums {
79
+ RIGHT = "Right",
80
+ LEFT = "Left",
81
+ }
82
+
83
+ export interface WidgetInterfaceProperties {
84
+ position: WidgetPositionEnums;
85
+ side_spacing?: number;
86
+ bottom_spacing?: number;
87
+ }
88
+
89
+ export enum LauncherType {
90
+ TEXT = "TEXT",
91
+ IMAGE = "IMAGE",
92
+ TEXTUAL_IMAGE = "TEXTUAL_IMAGE",
93
+ }
94
+
95
+ export interface ChatbotConfig {
96
+ brand_colour: string;
97
+ image_url?: string;
98
+ chat_interface_config?: {
99
+ chat_bubble_prompts?: string[];
100
+ display_name?: string;
101
+ welcome_message?: string;
102
+ redirect_url?: string;
103
+ };
104
+ interface_type?: ChatbotInterfaceType;
105
+ interface_properties?: WidgetInterfaceProperties;
106
+ launcher_type: LauncherType;
107
+ launcher_properties: {
108
+ text?: string;
109
+ };
110
+ images: {
111
+ launcher_image_url?: {
112
+ url: string;
113
+ };
114
+ };
115
+ }
116
+
117
+ const Chatbot: React.FC<InternalChatbotProps> = ({
118
+ api_key,
119
+ user_id,
120
+ user_token,
121
+ show_floating_button = true,
122
+ onEvent,
123
+ onMessage,
124
+ isFullScreen = true,
125
+ enableAnimation = true,
126
+ onOpen,
127
+ onClose,
128
+ user_profile,
129
+ }) => {
130
+ const [isWebViewVisible, setIsWebViewVisible] = useState(false);
131
+ const [chatbotConfig, setChatbotConfig] = useState<ChatbotConfig | null>(
132
+ null
133
+ );
134
+ const [loading, setLoading] = useState(true);
135
+ const webViewRef = useRef<WebView>(null);
136
+ const isFirstLoadRef = useRef(true);
137
+ const [toastVisible, setToastVisible] = useState(false);
138
+ const [toastMessage, setToastMessage] = useState("");
139
+ const [effectiveUserId, setEffectiveUserId] = useState<string>();
140
+ const [isStorageReady, setIsStorageReady] = useState(false);
141
+ const pendingStorageOps = useRef<Array<() => void>>([]);
142
+ const memoryCache = useRef<Record<string, string>>({});
143
+ const [systemInfo, setSystemInfo] = useState({ os: "", browser: "" });
144
+
145
+ // Initialize animated values
146
+ const animatedValues = useRef({
147
+ scale: new Animated.Value(1),
148
+ translateY: new Animated.Value(0),
149
+ opacity: new Animated.Value(1),
150
+ }).current;
151
+
152
+ // Create chatbotConfig object for events
153
+ const chatbotConfigForEvents = useMemo(
154
+ () => ({
155
+ userId: effectiveUserId,
156
+ isAnonymous: !user_id && user_id !== 0,
157
+ // Add other config properties as needed
158
+ }),
159
+ [effectiveUserId, user_id]
160
+ );
161
+
162
+ // Initialize event handling
163
+ const { emitEvent, onInternalEvent } = useChatbotEvents({
164
+ api_key,
165
+ chatbotConfig: chatbotConfigForEvents ?? {},
166
+ user_profile: user_profile,
167
+ onEvent: onEvent,
168
+ systemInfo: systemInfo ?? { os: "", browser: "" },
169
+ });
170
+
171
+ const triggerAppInit = () => {
172
+ if (webViewRef.current) {
173
+ webViewRef.current.injectJavaScript(`
174
+ // Trigger APP_READY equivalent
175
+ window.ReactNativeWebView.postMessage(JSON.stringify({ type: 'APP_READY' }));
176
+ true;
177
+ `);
178
+ }
179
+ };
180
+
181
+ const executeStorageOp = useCallback(
182
+ (operation: () => void) => {
183
+ if (isStorageReady) {
184
+ operation();
185
+ } else {
186
+ pendingStorageOps.current.push(operation);
187
+ }
188
+ },
189
+ [isStorageReady]
190
+ );
191
+
192
+ // Handle WebView messages
193
+ const handleMessage = useCallback(
194
+ (event: WebViewMessageEvent) => {
195
+ const { data } = event.nativeEvent;
196
+
197
+ try {
198
+ const parsedData: ChatbotMessage = JSON.parse(data);
199
+
200
+ // Handle storage messages
201
+ if (
202
+ Object.values(StorageMessageType).includes(
203
+ parsedData.type as StorageMessageType
204
+ )
205
+ ) {
206
+ const storageMessage = parsedData as StorageMessage;
207
+ switch (storageMessage.type) {
208
+ case StorageMessageType.STORAGE_READY:
209
+ setIsStorageReady(true);
210
+ pendingStorageOps.current.forEach((op) => op());
211
+ pendingStorageOps.current = [];
212
+ // Try to get stored ID immediately after storage is ready
213
+ webViewRef.current?.injectJavaScript(
214
+ createStorageMessage(
215
+ StorageMessageType.GET_STORAGE,
216
+ "rblyn_anon"
217
+ )
218
+ );
219
+ break;
220
+ case StorageMessageType.STORAGE_RESPONSE:
221
+ if (storageMessage.key && storageMessage.value) {
222
+ memoryCache.current[storageMessage.key] = storageMessage.value;
223
+ if (storageMessage.key === "rblyn_anon") {
224
+ setEffectiveUserId(storageMessage.value);
225
+ }
226
+ }
227
+ break;
228
+ case StorageMessageType.STORAGE_ERROR:
229
+ logger.error("WebView storage error:", storageMessage.error);
230
+ break;
231
+ }
232
+ return;
233
+ }
234
+
235
+ // Add debug logging
236
+ if (__DEV__) {
237
+ if (parsedData?.type === "CONSOLE") {
238
+ console.log(`WebView ${parsedData?.level}:`, parsedData?.data);
239
+ return;
240
+ }
241
+ if (parsedData?.type === "ERROR") {
242
+ console.error("WebView Error:", parsedData?.data);
243
+ return;
244
+ }
245
+ }
246
+
247
+ if (parsedData?.type === "SYSTEM_INFO") {
248
+ setSystemInfo(parsedData?.data ?? { os: "", browser: "" });
249
+ return;
250
+ }
251
+
252
+ if (parsedData?.type === "APP_READY") {
253
+ emitEvent(ChatbotEventType.CHATBOT_APP_READY);
254
+ if (webViewRef.current && isWebViewVisible) {
255
+ webViewRef.current?.injectJavaScript(getBrowserAndOSInfoScript());
256
+
257
+ const messageData = {
258
+ name: "registerUserId",
259
+ action: "registerUserId",
260
+ data: {
261
+ userId: effectiveUserId,
262
+ token: user_token ? `${user_token}` : undefined,
263
+ userProfile: {
264
+ ...user_profile,
265
+ },
266
+ },
267
+ };
268
+ logger.debug("messageData====>", JSON.stringify(messageData));
269
+ webViewRef.current?.injectJavaScript(`
270
+ window.postMessage(${JSON.stringify({
271
+ name: "openFrame",
272
+ domain: "app-domain.com",
273
+ })}, '*');
274
+ window.postMessage(${JSON.stringify(messageData)}, '*');
275
+ `);
276
+ }
277
+ }
278
+
279
+ // Handle other message types
280
+ switch (parsedData?.type) {
281
+ case "close_chatbot":
282
+ closeWebView();
283
+ break;
284
+ case "CHATBOT_LOADED":
285
+ emitEvent(ChatbotEventType.CHATBOT_LOADED, parsedData?.data);
286
+ break;
287
+ case "CHAT_INITIALIZED":
288
+ emitEvent(ChatbotEventType.CHAT_INITIALIZED, parsedData?.data);
289
+ break;
290
+ case "SESSION_REFRESHED":
291
+ emitEvent(ChatbotEventType.SESSION_REFRESHED, parsedData?.data);
292
+ break;
293
+ case "CHAT_INITIALIZATION_FAILED":
294
+ emitEvent(
295
+ ChatbotEventType.CHAT_INITIALIZATION_FAILED,
296
+ parsedData?.data
297
+ );
298
+ break;
299
+ default:
300
+ if (onMessage) onMessage(parsedData ?? {});
301
+ }
302
+ } catch (error) {
303
+ errorTracker.trackError(
304
+ error instanceof Error
305
+ ? error
306
+ : new Error("Failed to parse WebView message"),
307
+ "ChatbotSDK",
308
+ {
309
+ type: ErrorTypes.RUNTIME_ERROR,
310
+ context: { messageData: data },
311
+ }
312
+ );
313
+ }
314
+ },
315
+ [
316
+ emitEvent,
317
+ isWebViewVisible,
318
+ onMessage,
319
+ systemInfo,
320
+ effectiveUserId,
321
+ user_token,
322
+ user_profile,
323
+ ]
324
+ );
325
+
326
+ // Initialize user ID
327
+ useEffect(() => {
328
+ const initializeUserId = async () => {
329
+ let userId = user_id ? String(user_id) : undefined;
330
+
331
+ if (!userId) {
332
+ // Try memory cache first
333
+ userId = memoryCache.current["rblyn_anon"];
334
+
335
+ if (!userId) {
336
+ userId = generateUUID();
337
+ executeStorageOp(() => {
338
+ webViewRef.current?.injectJavaScript(
339
+ createStorageMessage(
340
+ StorageMessageType.SET_STORAGE,
341
+ "rblyn_anon",
342
+ userId!
343
+ )
344
+ );
345
+ });
346
+ }
347
+ }
348
+
349
+ setEffectiveUserId(userId);
350
+ };
351
+
352
+ initializeUserId();
353
+ }, [user_id, executeStorageOp]);
354
+
355
+ // Initialize WebView storage
356
+ useEffect(() => {
357
+ if (webViewRef.current) {
358
+ webViewRef.current.injectJavaScript(getStorageScript());
359
+ // Try to get stored ID once storage is ready
360
+ executeStorageOp(() => {
361
+ webViewRef.current?.injectJavaScript(
362
+ createStorageMessage(StorageMessageType.GET_STORAGE, "rblyn_anon")
363
+ );
364
+ });
365
+ }
366
+ }, []);
367
+
368
+ useEffect(() => {
369
+ const fetchChatbotConfig = async () => {
370
+ try {
371
+ const endpointUrl = `${API_URL}/chat/chatbot/get/`;
372
+ const payload = {
373
+ client_user_id: effectiveUserId,
374
+ org_id: api_key,
375
+ token: user_token,
376
+ extra_info: {},
377
+ };
378
+
379
+ // setToastMessage(endpointUrl + " : " + BASE_CHATBOT_URL);
380
+ // setToastVisible(true);
381
+
382
+ const response = await fetch(endpointUrl, {
383
+ method: "POST",
384
+ headers: {
385
+ "Content-Type": "application/json",
386
+ },
387
+ body: JSON.stringify(payload),
388
+ });
389
+
390
+ if (!response.ok) {
391
+ throw new Error("Failed to fetch chatbot configuration");
392
+ }
393
+
394
+ const data = await response.json();
395
+ const orgInfo = data?.user?.org_info;
396
+
397
+ if (orgInfo) {
398
+ const config: ChatbotConfig = {
399
+ brand_colour: orgInfo.brand_config?.colors?.brand_color || "",
400
+ image_url: orgInfo.brand_config?.launcher_logo_url || "",
401
+ chat_interface_config: {
402
+ chat_bubble_prompts: [],
403
+ display_name: orgInfo.brand_config?.display_name || "",
404
+ welcome_message:
405
+ orgInfo.brand_config?.welcome_message ||
406
+ "Hey! What can we help you with today?",
407
+ redirect_url: orgInfo.brand_config?.redirect_url || "",
408
+ },
409
+ interface_properties: {
410
+ position:
411
+ orgInfo.brand_config?.interface_properties?.position ||
412
+ WidgetPositionEnums.RIGHT,
413
+ side_spacing:
414
+ orgInfo.brand_config?.interface_properties?.side_spacing ?? 20,
415
+ bottom_spacing:
416
+ orgInfo.brand_config?.interface_properties?.bottom_spacing ??
417
+ 20,
418
+ },
419
+ interface_type:
420
+ orgInfo.brand_config?.interface_type ||
421
+ ChatbotInterfaceType.WIDGET,
422
+ launcher_type:
423
+ orgInfo.brand_config?.launcher_type || LauncherType.IMAGE,
424
+ launcher_properties: {
425
+ text: orgInfo.brand_config?.launcher_properties?.text || "",
426
+ },
427
+ images: {
428
+ launcher_image_url: {
429
+ url:
430
+ orgInfo.brand_config?.images?.launcher_image_url?.url || "",
431
+ },
432
+ },
433
+ };
434
+ setChatbotConfig(config);
435
+ }
436
+ } catch (error) {
437
+ errorTracker.trackError(
438
+ error instanceof Error
439
+ ? error
440
+ : new Error("Failed to fetch chatbot configuration"),
441
+ "ChatbotSDK",
442
+ {
443
+ type: ErrorTypes.NETWORK_ERROR,
444
+ context: { api_key, user_id },
445
+ }
446
+ );
447
+ } finally {
448
+ setLoading(false);
449
+ }
450
+ };
451
+
452
+ if (api_key && effectiveUserId) {
453
+ fetchChatbotConfig();
454
+ }
455
+ }, [api_key, effectiveUserId, user_token]);
456
+
457
+ function constructUrl(): string {
458
+ if (!effectiveUserId) return "";
459
+ const params = new URLSearchParams({
460
+ id: api_key,
461
+ });
462
+ console.log("BASE_CHATBOT_URL SDK_VERSION", BASE_CHATBOT_URL);
463
+ return `${BASE_CHATBOT_URL}?${params.toString()}`;
464
+ }
465
+
466
+ // Handle opening the chatbot
467
+ const openWebView = useCallback(() => {
468
+ setIsWebViewVisible(true);
469
+ if (enableAnimation) {
470
+ animateWebViewOpen(animatedValues, () => {
471
+ onOpen?.();
472
+ emitEvent(ChatbotEventType.CHATBOT_OPENED);
473
+ if (!isFirstLoadRef.current) {
474
+ setTimeout(triggerAppInit, 100);
475
+ }
476
+ });
477
+ } else {
478
+ requestAnimationFrame(() => {
479
+ onOpen?.();
480
+ emitEvent(ChatbotEventType.CHATBOT_OPENED);
481
+ if (!isFirstLoadRef.current) {
482
+ setTimeout(triggerAppInit, 100);
483
+ }
484
+ });
485
+ }
486
+ }, [enableAnimation, animatedValues, onOpen, emitEvent]);
487
+
488
+ // NOt Needed
489
+ // Handle closing the chatbot
490
+ const closeWebView = useCallback(() => {
491
+ if (webViewRef.current) {
492
+ webViewRef.current.postMessage(
493
+ JSON.stringify({
494
+ name: "closeFrame",
495
+ domain: "app-domain.com",
496
+ })
497
+ );
498
+ }
499
+
500
+ if (enableAnimation) {
501
+ animateWebViewClose(animatedValues, () => {
502
+ setIsWebViewVisible(false);
503
+ onClose?.();
504
+ emitEvent(ChatbotEventType.CHATBOT_CLOSED);
505
+ });
506
+ } else {
507
+ setIsWebViewVisible(false);
508
+ onClose?.();
509
+ emitEvent(ChatbotEventType.CHATBOT_CLOSED);
510
+ }
511
+ }, [enableAnimation, animatedValues, onClose, emitEvent]);
512
+
513
+ // Emit button loaded event when component mounts
514
+ useEffect(() => {
515
+ if (show_floating_button && chatbotConfig) {
516
+ emitEvent(ChatbotEventType.CHATBOT_BUTTON_LOADED);
517
+ }
518
+ }, [show_floating_button, chatbotConfig, emitEvent]);
519
+
520
+ const getScreenDimensions = () => {
521
+ const windowHeight = Dimensions.get("window").height;
522
+ const windowWidth = Dimensions.get("window").width;
523
+ const statusBarHeight =
524
+ Platform.OS === "ios" ? 0 : StatusBar.currentHeight || 0;
525
+
526
+ return {
527
+ height: windowHeight - statusBarHeight,
528
+ width: windowWidth,
529
+ };
530
+ };
531
+
532
+ const screenDimensions = getScreenDimensions();
533
+
534
+ useEffect(() => {
535
+ if (__DEV__) {
536
+ enableNetworkDebug();
537
+ }
538
+ }, []);
539
+
540
+ // Deliberate error for testing error boundary
541
+ // useEffect(() => {
542
+ // if (__DEV__) {
543
+ // // Set up global error handlers
544
+ // setupGlobalErrorHandlers();
545
+
546
+ // // Test async error
547
+ // setTimeout(() => {
548
+ // Promise.reject(new Error("Test async error"));
549
+ // }, 1000);
550
+
551
+ // // Test sync error
552
+ // setTimeout(() => {
553
+ // throw new Error("Test sync error");
554
+ // }, 2000);
555
+ // }
556
+ // }, []);
557
+
558
+ const position = chatbotConfig?.interface_properties?.position || "Right";
559
+ const sideSpacing = chatbotConfig?.interface_properties?.side_spacing ?? 20;
560
+ const bottomSpacing =
561
+ chatbotConfig?.interface_properties?.bottom_spacing ?? 20;
562
+
563
+ // const mainContainerStyle = useMemo(() => {
564
+ // return {
565
+ // ...styles.mainContainer,
566
+ // [position.toLowerCase()]: `${sideSpacing ?? 20}px`,
567
+ // alignItems:
568
+ // position === "Right" ? "flex-end" : ("flex-start" as FlexAlignType),
569
+ // // Explicitly clear mobile-specific styles
570
+ // top: undefined,
571
+ // [position === "Right" ? "left" : "right"]: undefined,
572
+ // backgroundColor: "green",
573
+ // };
574
+ // }, [position, sideSpacing, styles.mainContainer]);
575
+
576
+ return (
577
+ <ErrorBoundary componentName="ChatbotSDK">
578
+ <View style={styles?.mainContainer}>
579
+ {!loading && (
580
+ <>
581
+ <ErrorBoundary componentName="FloatingButton">
582
+ {show_floating_button && api_key && chatbotConfig && (
583
+ <FloatingButton
584
+ chatbotConfig={chatbotConfig}
585
+ isWebViewVisible={isWebViewVisible}
586
+ onPress={() => {
587
+ emitEvent(ChatbotEventType.CHATBOT_BUTTON_CLICKED);
588
+ openWebView();
589
+ }}
590
+ brandColor={chatbotConfig.brand_colour}
591
+ imageUrl={chatbotConfig.image_url}
592
+ />
593
+ )}
594
+ </ErrorBoundary>
595
+ <View
596
+ style={[
597
+ styles.webViewWrapper,
598
+ { height: isWebViewVisible ? "100%" : 0 },
599
+ ]}
600
+ pointerEvents={isWebViewVisible ? "auto" : "none"}
601
+ >
602
+ <Animated.View
603
+ style={[
604
+ styles.fullScreenContainer,
605
+ {
606
+ opacity: animatedValues.opacity,
607
+ transform: [
608
+ { scale: animatedValues.scale },
609
+ { translateY: animatedValues.translateY },
610
+ ],
611
+ },
612
+ ]}
613
+ >
614
+ <ErrorBoundary componentName="ChatbotWebView">
615
+ <WebView
616
+ ref={webViewRef}
617
+ source={{
618
+ uri: constructUrl(),
619
+ }}
620
+ onMessage={handleMessage}
621
+ style={styles.webview}
622
+ containerStyle={
623
+ isFullScreen
624
+ ? {
625
+ width: screenDimensions.width,
626
+ height: screenDimensions.height - 40,
627
+ }
628
+ : undefined
629
+ }
630
+ allowsInlineMediaPlayback={true}
631
+ mediaPlaybackRequiresUserAction={false}
632
+ allowFileAccess={false}
633
+ geolocationEnabled={false}
634
+ javaScriptEnabled={true}
635
+ domStorageEnabled={true}
636
+ cacheEnabled={true}
637
+ scrollEnabled={true}
638
+ bounces={false}
639
+ onShouldStartLoadWithRequest={(request) => {
640
+ return request.url.startsWith(BASE_CHATBOT_URL);
641
+ }}
642
+ startInLoadingState={isFirstLoadRef.current}
643
+ onLoadEnd={() => {
644
+ if (__DEV__) {
645
+ enableWebViewDebug(webViewRef);
646
+ }
647
+ webViewRef.current?.injectJavaScript(`
648
+ if (!document.querySelector('meta[name="viewport"]')) {
649
+ var meta = document.createElement('meta');
650
+ meta.name = 'viewport';
651
+ meta.content = 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no';
652
+ document.getElementsByTagName('head')[0].appendChild(meta);
653
+ }
654
+
655
+ if (!document.querySelector('#injectedStyle')) {
656
+ const style = document.createElement('style');
657
+ style.id = 'injectedStyle';
658
+ style.textContent = \`
659
+ html, body, #root, #__next {
660
+ height: 100% !important;
661
+ min-height: 100% !important;
662
+ overflow: hidden !important;
663
+ }
664
+ \`;
665
+ document.head.appendChild(style);
666
+ }
667
+
668
+ window.sendToChatbot = function(message) {
669
+ window.ReactNativeWebView.postMessage(JSON.stringify(message));
670
+ };
671
+
672
+ // Only create observer if it doesn't exist
673
+ if (!window.closeButtonObserver) {
674
+ // Setup mutation observer to watch for close button
675
+ window.closeButtonObserver = new MutationObserver(function(mutations) {
676
+ const closeButton = document.querySelector('.chatbot-close-button');
677
+ if (closeButton && !closeButton.hasAttribute('listener-attached')) {
678
+ closeButton.setAttribute('listener-attached', 'true');
679
+ closeButton.addEventListener('click', () => {
680
+ try {
681
+ const message = { type: 'close_chatbot' };
682
+ window.ReactNativeWebView.postMessage(JSON.stringify(message));
683
+ } catch (error) {
684
+ console.error('Error sending close message:', error);
685
+ }
686
+ });
687
+ console.log('Close button listener attached');
688
+ }
689
+ });
690
+
691
+ // Start observing
692
+ window.closeButtonObserver.observe(document.body, {
693
+ childList: true,
694
+ subtree: true
695
+ });
696
+
697
+ // Initial check for existing button
698
+ const existingButton = document.querySelector('.chatbot-close-button');
699
+ if (existingButton && !existingButton.hasAttribute('listener-attached')) {
700
+ existingButton.setAttribute('listener-attached', 'true');
701
+ existingButton.addEventListener('click', () => {
702
+ try {
703
+ const message = { type: 'close_chatbot' };
704
+ window.ReactNativeWebView.postMessage(JSON.stringify(message));
705
+ } catch (error) {
706
+ console.error('Error sending close message:', error);
707
+ }
708
+ });
709
+ console.log('Close button listener attached to existing button');
710
+ }
711
+ }
712
+
713
+ true;
714
+ `);
715
+ isFirstLoadRef.current = false;
716
+ }}
717
+ onError={(syntheticEvent) => {
718
+ const { nativeEvent } = syntheticEvent;
719
+ errorTracker.trackError(
720
+ new Error(nativeEvent.description),
721
+ "ChatbotWebView",
722
+ {
723
+ type: ErrorTypes.RUNTIME_ERROR,
724
+ context: {
725
+ url: nativeEvent.url,
726
+ code: nativeEvent.code,
727
+ },
728
+ }
729
+ );
730
+ }}
731
+ />
732
+ </ErrorBoundary>
733
+ </Animated.View>
734
+ </View>
735
+ </>
736
+ )}
737
+ {/* <Toast message={toastMessage} visible={toastVisible} duration={10000} /> */}
738
+ {__DEV__ && <DebugButton />}
739
+ </View>
740
+ </ErrorBoundary>
741
+ );
742
+ };
743
+
744
+ const styles = StyleSheet.create({
745
+ mainContainer: {
746
+ flex: 1,
747
+ position: "relative",
748
+ overflow: "visible",
749
+ },
750
+ webViewWrapper: {
751
+ position: "absolute",
752
+ top: 0,
753
+ left: 0,
754
+ right: 0,
755
+ bottom: 0,
756
+ overflow: "visible",
757
+ zIndex: 10000,
758
+ backgroundColor: "#ffffff",
759
+ },
760
+ fullScreenContainer: {
761
+ position: "absolute",
762
+ top: 0,
763
+ left: 0,
764
+ right: 0,
765
+ bottom: 0,
766
+ backgroundColor: "white",
767
+ zIndex: 10000,
768
+ overflow: "visible",
769
+ // height: Platform.OS === "android" ? "100%" : "100%",
770
+ },
771
+ inlineContainer: {
772
+ flex: 1,
773
+ backgroundColor: "white",
774
+ },
775
+ webview: {
776
+ flex: 1,
777
+ backgroundColor: "white",
778
+ zIndex: 10000,
779
+ },
780
+ });
781
+
782
+ export default Chatbot;