@robylon/react-native-sdk 2.0.22 → 2.0.23-staging.1

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