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