@robylon/react-native-sdk 2.1.0 → 2.1.1-staging.3

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