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