@robylon/react-native-sdk 2.0.29-staging.7 → 2.0.30

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