@robylon/react-native-sdk 2.0.27-staging.9 → 2.0.28

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