@robylon/react-native-sdk 2.0.31-staging.6 → 2.1.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 (55) 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/module/Chatbotsdk.js +1 -1
  8. package/lib/module/Chatbotsdk.js.map +1 -1
  9. package/lib/module/config.js +1 -1
  10. package/lib/module/config.js.map +1 -1
  11. package/lib/module/constants.js +1 -1
  12. package/lib/module/constants.js.map +1 -1
  13. package/lib/module/openChatbot.js +2 -1
  14. package/lib/module/openChatbot.js.map +1 -1
  15. package/lib/typescript/Chatbotsdk.d.ts.map +1 -1
  16. package/package.json +1 -1
  17. package/android/src/main/AndroidManifest.xml +0 -3
  18. package/android/src/main/java/com/robylonreactnativesdk/RobylonDownloadModule.java +0 -83
  19. package/android/src/main/java/com/robylonreactnativesdk/RobylonReactNativeSdkPackage.java +0 -24
  20. package/src/Chatbotsdk.tsx +0 -946
  21. package/src/FloatingButton/launchers/ImageLauncher.tsx +0 -75
  22. package/src/FloatingButton/launchers/TextLauncher.tsx +0 -84
  23. package/src/FloatingButton/launchers/TextualImageLauncher.tsx +0 -133
  24. package/src/FloatingButton.tsx +0 -97
  25. package/src/LoadingIndicator.tsx +0 -11
  26. package/src/Toast.tsx +0 -65
  27. package/src/components/DebugButton.tsx +0 -46
  28. package/src/components/ErrorBoundary.tsx +0 -38
  29. package/src/config.ts +0 -4
  30. package/src/constants/errorConstants.ts +0 -21
  31. package/src/constants/fontStyles.ts +0 -3
  32. package/src/constants.ts +0 -5
  33. package/src/global.d.ts +0 -11
  34. package/src/hooks/useChatbotEvents.ts +0 -93
  35. package/src/index.tsx +0 -10
  36. package/src/openChatbot.ts +0 -11
  37. package/src/openChatbot.tsx +0 -0
  38. package/src/services/ErrorTrackingService.ts +0 -217
  39. package/src/types/events.ts +0 -28
  40. package/src/types/react-native-flipper-performance-plugin.d.ts +0 -3
  41. package/src/types/react-native-globals.d.ts +0 -10
  42. package/src/utils/animations.ts +0 -120
  43. package/src/utils/colorUtils.ts +0 -35
  44. package/src/utils/cookieUtils.ts +0 -7
  45. package/src/utils/debugConfig.ts +0 -56
  46. package/src/utils/debugMenu.ts +0 -14
  47. package/src/utils/errorHandler.ts +0 -58
  48. package/src/utils/fileDownload.ts +0 -198
  49. package/src/utils/logger.ts +0 -14
  50. package/src/utils/systemInfo.ts +0 -110
  51. package/src/utils/webViewStorage.ts +0 -62
  52. package/src/version.ts +0 -2
  53. package/src/versions/version.dev.ts +0 -2
  54. package/src/versions/version.production.ts +0 -2
  55. package/src/versions/version.staging.ts +0 -2
@@ -1,946 +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
- 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
- logger.debug("messageData====>", JSON.stringify(messageData));
388
- webViewRef.current?.injectJavaScript(`
389
- window.postMessage(${JSON.stringify(messageData)}, '*');`);
390
- }
391
- // if (granted) {
392
- // emitEvent(ChatbotEventType.MIC_PERMISSION_GRANTED);
393
- // } else {
394
- // emitEvent(ChatbotEventType.MIC_PERMISSION_DENIED);
395
- // }
396
- break;
397
- default:
398
- if (onMessage) onMessage(parsedData ?? {});
399
- }
400
- } catch (error) {
401
- errorTracker.trackError(
402
- error instanceof Error
403
- ? error
404
- : new Error("Failed to parse WebView message"),
405
- "ChatbotSDK",
406
- {
407
- type: ErrorTypes.RUNTIME_ERROR,
408
- context: { messageData: data },
409
- }
410
- );
411
- }
412
- },
413
- [
414
- emitEvent,
415
- isWebViewVisible,
416
- onMessage,
417
- systemInfo,
418
- effectiveUserId,
419
- user_token,
420
- user_profile,
421
- ]
422
- );
423
-
424
- // Initialize user ID
425
- useEffect(() => {
426
- const initializeUserId = async () => {
427
- let userId = user_id ? String(user_id) : undefined;
428
-
429
- if (!userId) {
430
- // Try memory cache first
431
- userId = memoryCache.current["rblyn_anon"];
432
-
433
- if (!userId) {
434
- userId = generateUUID();
435
- executeStorageOp(() => {
436
- webViewRef.current?.injectJavaScript(
437
- createStorageMessage(
438
- StorageMessageType.SET_STORAGE,
439
- "rblyn_anon",
440
- userId!
441
- )
442
- );
443
- });
444
- }
445
- }
446
-
447
- setEffectiveUserId(userId);
448
- };
449
-
450
- initializeUserId();
451
- }, [user_id, executeStorageOp]);
452
-
453
- // Removed controlled isOpen syncing to avoid desync issues. Using ref API instead.
454
-
455
- // Initialize WebView storage
456
- useEffect(() => {
457
- if (webViewRef.current) {
458
- webViewRef.current.injectJavaScript(getStorageScript());
459
- // Try to get stored ID once storage is ready
460
- executeStorageOp(() => {
461
- webViewRef.current?.injectJavaScript(
462
- createStorageMessage(StorageMessageType.GET_STORAGE, "rblyn_anon")
463
- );
464
- });
465
- }
466
- }, []);
467
-
468
- useEffect(() => {
469
- const fetchChatbotConfig = async () => {
470
- try {
471
- const endpointUrl = `${API_URL}/chat/chatbot/get/`;
472
- const payload = {
473
- client_user_id: effectiveUserId,
474
- org_id: api_key,
475
- token: user_token,
476
- extra_info: {},
477
- };
478
-
479
- // setToastMessage(endpointUrl + " : " + BASE_CHATBOT_URL);
480
- // setToastVisible(true);
481
-
482
- const response = await fetch(endpointUrl, {
483
- method: "POST",
484
- headers: {
485
- "Content-Type": "application/json",
486
- },
487
- body: JSON.stringify(payload),
488
- });
489
-
490
- if (!response.ok) {
491
- throw new Error("Failed to fetch chatbot configuration");
492
- }
493
-
494
- const data = await response.json();
495
- const orgInfo = data?.user?.org_info;
496
-
497
- if (orgInfo) {
498
- const config: ChatbotConfig = {
499
- brand_colour: orgInfo.brand_config?.colors?.brand_color || "",
500
- image_url: orgInfo.brand_config?.launcher_logo_url || "",
501
- chat_interface_config: {
502
- chat_bubble_prompts: [],
503
- display_name: orgInfo.brand_config?.display_name || "",
504
- welcome_message:
505
- orgInfo.brand_config?.welcome_message ||
506
- "Hey! What can we help you with today?",
507
- redirect_url: orgInfo.brand_config?.redirect_url || "",
508
- },
509
- interface_properties: {
510
- position:
511
- orgInfo.brand_config?.interface_properties?.position ||
512
- WidgetPositionEnums.RIGHT,
513
- side_spacing:
514
- orgInfo.brand_config?.interface_properties?.side_spacing ??
515
- 20,
516
- bottom_spacing:
517
- orgInfo.brand_config?.interface_properties?.bottom_spacing ??
518
- 20,
519
- },
520
- interface_type:
521
- orgInfo.brand_config?.interface_type ||
522
- ChatbotInterfaceType.WIDGET,
523
- launcher_type:
524
- orgInfo.brand_config?.launcher_type || LauncherType.IMAGE,
525
- launcher_properties: {
526
- text: orgInfo.brand_config?.launcher_properties?.text || "",
527
- },
528
- images: {
529
- launcher_image_url: {
530
- url:
531
- orgInfo.brand_config?.images?.launcher_image_url?.url ||
532
- DEFAULT_LAUNCHER_IMAGE,
533
- },
534
- },
535
- chat_iframe_url: orgInfo.brand_config?.chat_iframe_url || "",
536
- };
537
- setChatbotConfig(config);
538
- }
539
- } catch (error) {
540
- errorTracker.trackError(
541
- error instanceof Error
542
- ? error
543
- : new Error("Failed to fetch chatbot configuration"),
544
- "ChatbotSDK",
545
- {
546
- type: ErrorTypes.NETWORK_ERROR,
547
- context: { api_key, user_id },
548
- }
549
- );
550
- } finally {
551
- setLoading(false);
552
- }
553
- };
554
-
555
- if (api_key && effectiveUserId) {
556
- fetchChatbotConfig();
557
- }
558
- }, [api_key, effectiveUserId, user_token]);
559
-
560
- function constructUrl(): string {
561
- if (!effectiveUserId) return "";
562
- const params = new URLSearchParams({
563
- id: api_key,
564
- });
565
- // const iFrameUrlFromBackend = chatbotConfig?.chat_iframe_url;
566
- // if (iFrameUrlFromBackend) {
567
- // return `${iFrameUrlFromBackend}`;
568
- // }
569
- return `${BASE_CHATBOT_URL}?${params.toString()}`;
570
- }
571
-
572
- // Handle opening the chatbot
573
- const openWebView = useCallback(() => {
574
- setIsWebViewVisible(true);
575
- if (enableAnimation) {
576
- animateWebViewOpen(animatedValues, () => {
577
- externalOnOpen?.();
578
- emitEvent(ChatbotEventType.CHATBOT_OPENED);
579
- if (!isFirstLoadRef.current) {
580
- setTimeout(triggerAppInit, 100);
581
- }
582
- });
583
- } else {
584
- requestAnimationFrame(() => {
585
- externalOnOpen?.();
586
- emitEvent(ChatbotEventType.CHATBOT_OPENED);
587
- if (!isFirstLoadRef.current) {
588
- setTimeout(triggerAppInit, 100);
589
- }
590
- });
591
- }
592
- }, [enableAnimation, animatedValues, externalOnOpen, emitEvent]);
593
-
594
- // Handle closing the chatbot
595
- const closeWebView = useCallback(() => {
596
- if (webViewRef.current) {
597
- webViewRef.current.postMessage(
598
- JSON.stringify({
599
- name: "closeFrame",
600
- domain: "app-domain.com",
601
- })
602
- );
603
- }
604
-
605
- if (enableAnimation) {
606
- animateWebViewClose(animatedValues, () => {
607
- setIsWebViewVisible(false);
608
- externalOnClose?.();
609
- emitEvent(ChatbotEventType.CHATBOT_CLOSED);
610
- });
611
- } else {
612
- setIsWebViewVisible(false);
613
- externalOnClose?.();
614
- emitEvent(ChatbotEventType.CHATBOT_CLOSED);
615
- }
616
- }, [enableAnimation, animatedValues, externalOnClose, emitEvent]);
617
-
618
- // Emit button loaded event when component mounts
619
- useEffect(() => {
620
- if (show_floating_button && chatbotConfig) {
621
- emitEvent(ChatbotEventType.CHATBOT_BUTTON_LOADED);
622
- }
623
- }, [show_floating_button, chatbotConfig, emitEvent]);
624
-
625
- // Set initialization state when chatbot is ready
626
- useEffect(() => {
627
- if (!loading && chatbotConfig && effectiveUserId && !isInitialized) {
628
- setIsInitialized(true);
629
- onReady?.();
630
- }
631
- }, [loading, chatbotConfig, effectiveUserId, isInitialized, onReady]);
632
-
633
- const getScreenDimensions = () => {
634
- const windowHeight = Dimensions.get("window").height;
635
- const windowWidth = Dimensions.get("window").width;
636
- const statusBarHeight =
637
- Platform.OS === "ios" ? 0 : StatusBar.currentHeight || 0;
638
-
639
- return {
640
- height: windowHeight - statusBarHeight,
641
- width: windowWidth,
642
- };
643
- };
644
-
645
- const requestAndroidMicPermission = useCallback(async () => {
646
- try {
647
- if (Platform.OS === "ios") {
648
- return true;
649
- }
650
- // Check if already granted
651
- const alreadyGranted = await PermissionsAndroid.check(
652
- PermissionsAndroid.PERMISSIONS.RECORD_AUDIO
653
- );
654
-
655
- if (alreadyGranted) {
656
- return true;
657
- }
658
-
659
- const result = await PermissionsAndroid.request(
660
- PermissionsAndroid.PERMISSIONS.RECORD_AUDIO,
661
- {
662
- title: "Microphone permission",
663
- message: "This app uses your microphone for voice features.",
664
- buttonPositive: "Allow",
665
- buttonNegative: "Deny",
666
- }
667
- );
668
-
669
- const granted = result === PermissionsAndroid.RESULTS.GRANTED;
670
-
671
- if (!granted) {
672
- // Optional UX
673
- Alert.alert(
674
- "Microphone required",
675
- "Voice features will not work unless you allow microphone access."
676
- );
677
- }
678
-
679
- return granted;
680
- } catch (err) {
681
- console.warn("Error requesting mic permission", err);
682
- return false;
683
- }
684
- }, []);
685
-
686
- const screenDimensions = getScreenDimensions();
687
-
688
- useEffect(() => {
689
- if (__DEV__) {
690
- enableNetworkDebug();
691
- }
692
- }, []);
693
-
694
- // Deliberate error for testing error boundary
695
- // useEffect(() => {
696
- // if (__DEV__) {
697
- // // Set up global error handlers
698
- // setupGlobalErrorHandlers();
699
-
700
- // // Test async error
701
- // setTimeout(() => {
702
- // Promise.reject(new Error("Test async error"));
703
- // }, 1000);
704
-
705
- // // Test sync error
706
- // setTimeout(() => {
707
- // throw new Error("Test sync error");
708
- // }, 2000);
709
- // }
710
- // }, []);
711
-
712
- const position = chatbotConfig?.interface_properties?.position || "Right";
713
- const sideSpacing = chatbotConfig?.interface_properties?.side_spacing ?? 20;
714
- const bottomSpacing =
715
- chatbotConfig?.interface_properties?.bottom_spacing ?? 20;
716
-
717
- // const mainContainerStyle = useMemo(() => {
718
- // return {
719
- // ...styles.mainContainer,
720
- // [position.toLowerCase()]: `${sideSpacing ?? 20}px`,
721
- // alignItems:
722
- // position === "Right" ? "flex-end" : ("flex-start" as FlexAlignType),
723
- // // Explicitly clear mobile-specific styles
724
- // top: undefined,
725
- // [position === "Right" ? "left" : "right"]: undefined,
726
- // backgroundColor: "green",
727
- // };
728
- // }, [position, sideSpacing, styles.mainContainer]);
729
-
730
- return (
731
- <ErrorBoundary componentName="ChatbotSDK">
732
- <View style={styles?.mainContainer}>
733
- {!loading && (
734
- <>
735
- <ErrorBoundary componentName="FloatingButton">
736
- {show_floating_button && api_key && chatbotConfig && (
737
- <FloatingButton
738
- chatbotConfig={chatbotConfig}
739
- isWebViewVisible={isWebViewVisible}
740
- onPress={() => {
741
- emitEvent(ChatbotEventType.CHATBOT_BUTTON_CLICKED);
742
- openWebView();
743
- }}
744
- brandColor={chatbotConfig.brand_colour}
745
- imageUrl={chatbotConfig.image_url}
746
- />
747
- )}
748
- </ErrorBoundary>
749
- <View
750
- style={[
751
- styles.webViewWrapper,
752
- { height: isWebViewVisible ? "100%" : 0 },
753
- ]}
754
- pointerEvents={isWebViewVisible ? "auto" : "none"}
755
- >
756
- <Animated.View
757
- style={[
758
- styles.fullScreenContainer,
759
- {
760
- opacity: animatedValues.opacity,
761
- transform: [
762
- { scale: animatedValues.scale },
763
- { translateY: animatedValues.translateY },
764
- ],
765
- },
766
- ]}
767
- >
768
- <ErrorBoundary componentName="ChatbotWebView">
769
- <WebView
770
- mediaCapturePermissionGrantType={"grant"}
771
- webviewDebuggingEnabled={true}
772
- ref={webViewRef}
773
- source={{
774
- uri: constructUrl(),
775
- }}
776
- onMessage={handleMessage}
777
- style={styles.webview}
778
- containerStyle={
779
- isFullScreen
780
- ? {
781
- width: screenDimensions.width,
782
- height: screenDimensions.height - 40,
783
- }
784
- : undefined
785
- }
786
- allowsInlineMediaPlayback={true}
787
- mediaPlaybackRequiresUserAction={false}
788
- allowFileAccess={false}
789
- geolocationEnabled={false}
790
- javaScriptEnabled={true}
791
- domStorageEnabled={true}
792
- cacheEnabled={true}
793
- scrollEnabled={true}
794
- bounces={false}
795
- onShouldStartLoadWithRequest={(request) => {
796
- return (
797
- request.url.startsWith(BASE_CHATBOT_URL) ||
798
- request.url.startsWith(
799
- chatbotConfig?.chat_iframe_url || ""
800
- )
801
- );
802
- }}
803
- startInLoadingState={isFirstLoadRef.current}
804
- onLoadEnd={() => {
805
- if (__DEV__) {
806
- enableWebViewDebug(webViewRef);
807
- }
808
- webViewRef.current?.injectJavaScript(`
809
- if (!document.querySelector('meta[name="viewport"]')) {
810
- var meta = document.createElement('meta');
811
- meta.name = 'viewport';
812
- meta.content = 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no';
813
- document.getElementsByTagName('head')[0].appendChild(meta);
814
- }
815
-
816
- if (!document.querySelector('#injectedStyle')) {
817
- const style = document.createElement('style');
818
- style.id = 'injectedStyle';
819
- style.textContent = \`
820
- html, body, #root, #__next {
821
- height: 100% !important;
822
- min-height: 100% !important;
823
- overflow: hidden !important;
824
- }
825
- \`;
826
- document.head.appendChild(style);
827
- }
828
-
829
- window.sendToChatbot = function(message) {
830
- window.ReactNativeWebView.postMessage(JSON.stringify(message));
831
- };
832
-
833
- // Only create observer if it doesn't exist
834
- if (!window.closeButtonObserver) {
835
- // Setup mutation observer to watch for close button
836
- window.closeButtonObserver = new MutationObserver(function(mutations) {
837
- const closeButton = document.querySelector('.chatbot-close-button');
838
- if (closeButton && !closeButton.hasAttribute('listener-attached')) {
839
- closeButton.setAttribute('listener-attached', 'true');
840
- closeButton.addEventListener('click', () => {
841
- try {
842
- const message = { type: 'close_chatbot' };
843
- window.ReactNativeWebView.postMessage(JSON.stringify(message));
844
- } catch (error) {
845
- console.error('Error sending close message:', error);
846
- }
847
- });
848
- console.log('Close button listener attached');
849
- }
850
- });
851
-
852
- // Start observing
853
- window.closeButtonObserver.observe(document.body, {
854
- childList: true,
855
- subtree: true
856
- });
857
-
858
- // Initial check for existing button
859
- const existingButton = document.querySelector('.chatbot-close-button');
860
- if (existingButton && !existingButton.hasAttribute('listener-attached')) {
861
- existingButton.setAttribute('listener-attached', 'true');
862
- existingButton.addEventListener('click', () => {
863
- try {
864
- const message = { type: 'close_chatbot' };
865
- window.ReactNativeWebView.postMessage(JSON.stringify(message));
866
- } catch (error) {
867
- console.error('Error sending close message:', error);
868
- }
869
- });
870
- console.log('Close button listener attached to existing button');
871
- }
872
- }
873
-
874
- true;
875
- `);
876
- isFirstLoadRef.current = false;
877
- }}
878
- onError={(syntheticEvent) => {
879
- const { nativeEvent } = syntheticEvent;
880
- errorTracker.trackError(
881
- new Error(nativeEvent.description),
882
- "ChatbotWebView",
883
- {
884
- type: ErrorTypes.RUNTIME_ERROR,
885
- context: {
886
- url: nativeEvent.url,
887
- code: nativeEvent.code,
888
- },
889
- }
890
- );
891
- }}
892
- />
893
- </ErrorBoundary>
894
- </Animated.View>
895
- </View>
896
- </>
897
- )}
898
- {/* <Toast message={toastMessage} visible={toastVisible} duration={10000} /> */}
899
- {__DEV__ && <DebugButton />}
900
- </View>
901
- </ErrorBoundary>
902
- );
903
- }
904
- );
905
-
906
- Chatbot.displayName = "Chatbot";
907
-
908
- const styles = StyleSheet.create({
909
- mainContainer: {
910
- flex: 1,
911
- position: "relative",
912
- overflow: "visible",
913
- },
914
- webViewWrapper: {
915
- position: "absolute",
916
- top: 0,
917
- left: 0,
918
- right: 0,
919
- bottom: 0,
920
- overflow: "visible",
921
- zIndex: 10000,
922
- backgroundColor: "#ffffff",
923
- },
924
- fullScreenContainer: {
925
- position: "absolute",
926
- top: 0,
927
- left: 0,
928
- right: 0,
929
- bottom: 0,
930
- backgroundColor: "white",
931
- zIndex: 10000,
932
- overflow: "visible",
933
- // height: Platform.OS === "android" ? "100%" : "100%",
934
- },
935
- inlineContainer: {
936
- flex: 1,
937
- backgroundColor: "white",
938
- },
939
- webview: {
940
- flex: 1,
941
- backgroundColor: "white",
942
- zIndex: 10000,
943
- },
944
- });
945
-
946
- export default Chatbot;