@robylon/react-native-sdk 1.10.1-staging.7 → 1.10.1-staging.8

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.
@@ -3,5 +3,4 @@ __tests__/
3
3
  __fixtures__/
4
4
  __mocks__/
5
5
  .env*
6
- *.log
7
- src
6
+ *.log
@@ -1,2 +1,3 @@
1
- Object.defineProperty(exports,"__esModule",{value:true});exports.openChatbot=void 0;var _reactNative=require("react-native");var _constants=require("./constants");var openChatbot=exports.openChatbot=function openChatbot(chatbotId){var additionalParams=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var params=new URLSearchParams(Object.assign({id:chatbotId},additionalParams));var url=_constants.BASE_CHATBOT_URL+"?"+params.toString();_reactNative.Linking.openURL(url);};
1
+
2
+ //# sourceMappingURL=openChatbot.js.mape",{value:true});exports.openChatbot=void 0;var _reactNative=require("react-native");var _constants=require("./constants");var openChatbot=exports.openChatbot=function openChatbot(chatbotId){var additionalParams=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var params=new URLSearchParams(Object.assign({id:chatbotId},additionalParams));var url=_constants.BASE_CHATBOT_URL+"?"+params.toString();_reactNative.Linking.openURL(url);};
2
3
  //# sourceMappingURL=openChatbot.js.map
@@ -1 +1 @@
1
- {"version":3,"names":["_reactNative","require","_constants","openChatbot","exports","chatbotId","additionalParams","arguments","length","undefined","params","URLSearchParams","Object","assign","id","url","BASE_CHATBOT_URL","toString","Linking","openURL"],"sourceRoot":"../../src","sources":["openChatbot.ts"],"mappings":"oFAAA,IAAAA,YAAA,CAAAC,OAAA,iBACA,IAAAC,UAAA,CAAAD,OAAA,gBAEO,GAAM,CAAAE,WAAW,CAAAC,OAAA,CAAAD,WAAA,CAAG,QAAd,CAAAA,WAAWA,CACtBE,SAAiB,CAER,IADT,CAAAC,gBAAwC,CAAAC,SAAA,CAAAC,MAAA,IAAAD,SAAA,MAAAE,SAAA,CAAAF,SAAA,IAAG,CAAC,CAAC,CAE7C,GAAM,CAAAG,MAAM,CAAG,GAAI,CAAAC,eAAe,CAAAC,MAAA,CAAAC,MAAA,EAAGC,EAAE,CAAET,SAAS,EAAKC,gBAAgB,CAAE,CAAC,CAC1E,GAAM,CAAAS,GAAG,CAAMC,2BAAgB,KAAIN,MAAM,CAACO,QAAQ,CAAC,CAAG,CACtDC,oBAAO,CAACC,OAAO,CAACJ,GAAG,CAAC,CACtB,CAAC","ignoreList":[]}
1
+ {"version":3,"names":[],"sourceRoot":"../../src","sources":["openChatbot.tsx"],"mappings":"","ignoreList":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@robylon/react-native-sdk",
3
- "version": "1.10.1-staging.7",
3
+ "version": "1.10.1-staging.8",
4
4
  "description": "React Native SDK for Robylon",
5
5
  "main": "lib/commonjs/index.js",
6
6
  "module": "lib/module/index.js",
@@ -0,0 +1,44 @@
1
+ // File: src/ChatbotWebview.tsx
2
+ import React, { useEffect, useState } from "react";
3
+ import { View } from "react-native";
4
+ import { WebView } from "react-native-webview";
5
+ import { BASE_CHATBOT_URL } from "./constants";
6
+ import LoadingIndicator from "./LoadingIndicator";
7
+
8
+ interface ChatbotWebviewProps {
9
+ chatbotId: string;
10
+ additionalParams?: Record<string, string>;
11
+ }
12
+
13
+ const constructUrl = (
14
+ chatbotId: string,
15
+ additionalParams: Record<string, string> = {}
16
+ ): string => {
17
+ const params = new URLSearchParams({ id: chatbotId, ...additionalParams });
18
+ return `${BASE_CHATBOT_URL}?${params.toString()}`;
19
+ };
20
+
21
+ export const ChatbotWebview: React.FC<ChatbotWebviewProps> = ({
22
+ chatbotId,
23
+ additionalParams,
24
+ }) => {
25
+ const [url, setUrl] = useState<string>("");
26
+
27
+ useEffect(() => {
28
+ setUrl(constructUrl(chatbotId, additionalParams));
29
+ }, [chatbotId, additionalParams]);
30
+
31
+ return (
32
+ <View style={{ flex: 1 }}>
33
+ {url ? (
34
+ <WebView
35
+ source={{ uri: url }}
36
+ startInLoadingState={true}
37
+ renderLoading={() => <LoadingIndicator />}
38
+ />
39
+ ) : (
40
+ <LoadingIndicator />
41
+ )}
42
+ </View>
43
+ );
44
+ };
@@ -0,0 +1,379 @@
1
+ import React, { useState, useEffect, useRef, useMemo } from "react";
2
+ import {
3
+ View,
4
+ StyleSheet,
5
+ Animated,
6
+ Dimensions,
7
+ Platform,
8
+ StatusBar,
9
+ } from "react-native";
10
+ import { WebView, WebViewMessageEvent } from "react-native-webview";
11
+ import FloatingButton from "./FloatingButton";
12
+ import { BASE_CHATBOT_URL } from "./constants";
13
+
14
+ interface ChatbotSDKProps {
15
+ api_key: string;
16
+ user_id?: string;
17
+ user_token?: string;
18
+ additional_params?: Record<string, string>;
19
+ show_floating_button?: boolean;
20
+ onMessage?: (message: any) => void;
21
+ isFullScreen?: boolean;
22
+ enableAnimation?: boolean;
23
+ onOpen?: () => void;
24
+ onClose?: () => void;
25
+ }
26
+
27
+ interface ChatbotMessage {
28
+ type: string;
29
+ data?: any;
30
+ }
31
+
32
+ interface ChatbotConfig {
33
+ brand_color: string;
34
+ image_url: string;
35
+ welcome_message: string;
36
+ }
37
+
38
+ const ChatbotSDK: React.FC<ChatbotSDKProps> = ({
39
+ api_key,
40
+ user_id,
41
+ user_token,
42
+ additional_params = {},
43
+ show_floating_button = true,
44
+ onMessage,
45
+ isFullScreen = true,
46
+ enableAnimation = true,
47
+ onOpen,
48
+ onClose,
49
+ }) => {
50
+ const [isWebViewVisible, setIsWebViewVisible] = useState(false);
51
+ const [chatbotConfig, setChatbotConfig] = useState<ChatbotConfig | null>(
52
+ null
53
+ );
54
+ const [loading, setLoading] = useState(true);
55
+ const webViewRef = useRef<WebView>(null);
56
+ const fadeAnim = useRef(new Animated.Value(0)).current;
57
+ const isFirstLoadRef = useRef(true);
58
+ const webViewUrl = useMemo(
59
+ () => constructUrl(),
60
+ [api_key, user_id, additional_params]
61
+ );
62
+
63
+ const stableAdditionalParams = useMemo(
64
+ () => additional_params,
65
+ [JSON.stringify(additional_params)]
66
+ );
67
+
68
+ const triggerAppInit = () => {
69
+ if (webViewRef.current) {
70
+ webViewRef.current.injectJavaScript(`
71
+ // Trigger APP_READY equivalent
72
+ window.ReactNativeWebView.postMessage(JSON.stringify({ type: 'APP_READY' }));
73
+ true;
74
+ `);
75
+ }
76
+ };
77
+
78
+ useEffect(() => {
79
+ const fetchChatbotConfig = async () => {
80
+ try {
81
+ const endpointUrl = `https://stage-api.robylon.ai/users/auth/copilot/`;
82
+ const payload = {
83
+ client_user_id: user_id,
84
+ org_id: api_key,
85
+ token: user_token,
86
+ extra_info: stableAdditionalParams,
87
+ };
88
+
89
+ const response = await fetch(endpointUrl, {
90
+ method: "POST",
91
+ headers: {
92
+ "Content-Type": "application/json",
93
+ },
94
+ body: JSON.stringify(payload),
95
+ });
96
+
97
+ if (!response.ok) {
98
+ throw new Error("Failed to fetch chatbot configuration");
99
+ }
100
+
101
+ const data = await response.json();
102
+ const orgInfo = data?.user?.org_info;
103
+
104
+ if (orgInfo) {
105
+ setChatbotConfig({
106
+ brand_color: orgInfo?.config?.brand_colour || "#007AFF",
107
+ image_url: orgInfo?.brand_config?.launcher_logo_url || "",
108
+ welcome_message: orgInfo?.config?.welcome_message || "",
109
+ });
110
+ }
111
+ } catch (error) {
112
+ console.error("Error fetching chatbot configuration:", error);
113
+ } finally {
114
+ setLoading(false);
115
+ }
116
+ };
117
+
118
+ if (api_key && user_id) {
119
+ fetchChatbotConfig();
120
+ }
121
+ }, [api_key, user_id, user_token, stableAdditionalParams]);
122
+
123
+ function constructUrl(): string {
124
+ if (!user_id) return "";
125
+ const params = new URLSearchParams({
126
+ id: api_key,
127
+ user_id,
128
+ ...additional_params,
129
+ });
130
+ return `${BASE_CHATBOT_URL}?${params.toString()}`;
131
+ }
132
+
133
+ const openWebView = () => {
134
+ setIsWebViewVisible(true);
135
+ if (enableAnimation) {
136
+ Animated.timing(fadeAnim, {
137
+ toValue: 1,
138
+ duration: 250,
139
+ useNativeDriver: true,
140
+ }).start(() => {
141
+ onOpen?.();
142
+ if (!isFirstLoadRef.current) {
143
+ // If not first load, manually trigger initialization
144
+ setTimeout(triggerAppInit, 100);
145
+ }
146
+ });
147
+ } else {
148
+ fadeAnim.setValue(1);
149
+ requestAnimationFrame(() => {
150
+ onOpen?.();
151
+ if (!isFirstLoadRef.current) {
152
+ setTimeout(triggerAppInit, 100);
153
+ }
154
+ });
155
+ }
156
+ };
157
+
158
+ const closeWebView = () => {
159
+ if (webViewRef.current) {
160
+ console.log("closeWebView");
161
+ webViewRef.current.postMessage(
162
+ JSON.stringify({
163
+ name: "closeFrame",
164
+ domain: "app-domain.com",
165
+ })
166
+ );
167
+ }
168
+
169
+ const complete = () => {
170
+ setIsWebViewVisible(false);
171
+ onClose?.();
172
+ };
173
+
174
+ if (enableAnimation) {
175
+ Animated.timing(fadeAnim, {
176
+ toValue: 0,
177
+ duration: 200,
178
+ useNativeDriver: true,
179
+ }).start(complete);
180
+ } else {
181
+ fadeAnim.setValue(0);
182
+ requestAnimationFrame(complete);
183
+ }
184
+ };
185
+
186
+ const handleMessage = (event: WebViewMessageEvent) => {
187
+ const { data } = event.nativeEvent;
188
+
189
+ try {
190
+ const parsedData: ChatbotMessage = JSON.parse(data);
191
+
192
+ if (parsedData.type === "APP_READY") {
193
+ console.log("APP_READY", webViewRef.current && isWebViewVisible);
194
+ if (webViewRef.current && isWebViewVisible) {
195
+ webViewRef.current.injectJavaScript(`
196
+ window.postMessage(${JSON.stringify({
197
+ name: "openFrame",
198
+ domain: "app-domain.com",
199
+ })}, '*');
200
+ window.postMessage(${JSON.stringify({
201
+ name: "registerUserId",
202
+ action: "registerUserId",
203
+ domain: "app-domain.com",
204
+ data: {
205
+ userId: `${user_id}`,
206
+ token: `${user_token}`,
207
+ },
208
+ })}, '*');
209
+ `);
210
+ }
211
+ }
212
+
213
+ if (typeof parsedData !== "object" || !parsedData.type) {
214
+ console.warn("Invalid message structure");
215
+ return;
216
+ }
217
+
218
+ switch (parsedData.type) {
219
+ case "close_chatbot":
220
+ closeWebView();
221
+ break;
222
+ default:
223
+ if (onMessage) onMessage(parsedData);
224
+ }
225
+ } catch (error) {
226
+ console.error("Failed to parse or process WebView message:", error);
227
+ }
228
+ };
229
+
230
+ const getScreenDimensions = () => {
231
+ const windowHeight = Dimensions.get("window").height;
232
+ const windowWidth = Dimensions.get("window").width;
233
+ const statusBarHeight =
234
+ Platform.OS === "ios" ? 0 : StatusBar.currentHeight || 0;
235
+
236
+ return {
237
+ height: windowHeight - statusBarHeight,
238
+ width: windowWidth,
239
+ };
240
+ };
241
+
242
+ const screenDimensions = getScreenDimensions();
243
+
244
+ return (
245
+ <View style={styles.mainContainer}>
246
+ {!loading && (
247
+ <>
248
+ {show_floating_button && api_key && chatbotConfig && (
249
+ <FloatingButton
250
+ onPress={openWebView}
251
+ brandColor={chatbotConfig.brand_color}
252
+ imageUrl={chatbotConfig.image_url}
253
+ />
254
+ )}
255
+ <View
256
+ style={[
257
+ styles.webViewWrapper,
258
+ { height: isWebViewVisible ? "100%" : 0 },
259
+ ]}
260
+ pointerEvents={isWebViewVisible ? "auto" : "none"}
261
+ >
262
+ <Animated.View
263
+ style={[
264
+ isFullScreen
265
+ ? styles.fullScreenContainer
266
+ : styles.inlineContainer,
267
+ { opacity: fadeAnim },
268
+ ]}
269
+ >
270
+ <WebView
271
+ ref={webViewRef}
272
+ source={{ uri: webViewUrl }}
273
+ onMessage={handleMessage}
274
+ style={styles.webview}
275
+ containerStyle={
276
+ isFullScreen
277
+ ? {
278
+ width: screenDimensions.width,
279
+ height: screenDimensions.height,
280
+ }
281
+ : undefined
282
+ }
283
+ allowsInlineMediaPlayback={true}
284
+ mediaPlaybackRequiresUserAction={false}
285
+ allowFileAccess={false}
286
+ geolocationEnabled={false}
287
+ javaScriptEnabled={true}
288
+ domStorageEnabled={true}
289
+ cacheEnabled={true}
290
+ scrollEnabled={true}
291
+ bounces={false}
292
+ onShouldStartLoadWithRequest={(request) => {
293
+ return request.url.startsWith(BASE_CHATBOT_URL);
294
+ }}
295
+ startInLoadingState={isFirstLoadRef.current}
296
+ onLoadEnd={() => {
297
+ webViewRef.current?.injectJavaScript(`
298
+ if (!document.querySelector('meta[name="viewport"]')) {
299
+ var meta = document.createElement('meta');
300
+ meta.name = 'viewport';
301
+ meta.content = 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no';
302
+ document.getElementsByTagName('head')[0].appendChild(meta);
303
+ }
304
+
305
+ if (!document.querySelector('#injectedStyle')) {
306
+ const style = document.createElement('style');
307
+ style.id = 'injectedStyle';
308
+ style.textContent = \`
309
+ html, body, #root, #__next {
310
+ height: 100% !important;
311
+ min-height: 100% !important;
312
+ overflow: hidden !important;
313
+ }
314
+ \`;
315
+ document.head.appendChild(style);
316
+ }
317
+
318
+ window.sendToChatbot = function(message) {
319
+ window.ReactNativeWebView.postMessage(JSON.stringify(message));
320
+ };
321
+
322
+ var closeButton = document.querySelector('.chatbot-close-button');
323
+ if (closeButton) {
324
+ closeButton.addEventListener('click', () => {
325
+ window.sendToChatbot({ type: 'close_chatbot' });
326
+ });
327
+ }
328
+
329
+ true;
330
+ `);
331
+ isFirstLoadRef.current = false;
332
+ }}
333
+ onError={(syntheticEvent) => {
334
+ const { nativeEvent } = syntheticEvent;
335
+ console.warn("WebView error:", nativeEvent);
336
+ }}
337
+ />
338
+ </Animated.View>
339
+ </View>
340
+ </>
341
+ )}
342
+ </View>
343
+ );
344
+ };
345
+
346
+ const styles = StyleSheet.create({
347
+ mainContainer: {
348
+ flex: 1,
349
+ position: "relative",
350
+ },
351
+ webViewWrapper: {
352
+ position: "absolute",
353
+ top: 0,
354
+ left: 0,
355
+ right: 0,
356
+ bottom: 0,
357
+ overflow: "hidden",
358
+ zIndex: 1000,
359
+ },
360
+ fullScreenContainer: {
361
+ position: "absolute",
362
+ top: 0,
363
+ left: 0,
364
+ right: 0,
365
+ bottom: 0,
366
+ backgroundColor: "white",
367
+ zIndex: 1000,
368
+ },
369
+ inlineContainer: {
370
+ flex: 1,
371
+ backgroundColor: "white",
372
+ },
373
+ webview: {
374
+ flex: 1,
375
+ backgroundColor: "white",
376
+ },
377
+ });
378
+
379
+ export default ChatbotSDK;
@@ -0,0 +1,57 @@
1
+ import React from "react";
2
+ import { TouchableOpacity, StyleSheet, Text, Image } from "react-native";
3
+
4
+ interface FloatingButtonProps {
5
+ onPress: () => void;
6
+ brandColor?: string; // For dynamic branding
7
+ imageUrl?: string; // For brand logo or icon
8
+ }
9
+
10
+ const FloatingButton: React.FC<FloatingButtonProps> = ({
11
+ onPress,
12
+ brandColor = "#007AFF", // Default color
13
+ imageUrl,
14
+ }) => {
15
+ return (
16
+ <TouchableOpacity
17
+ style={[styles.button, { backgroundColor: brandColor }]}
18
+ onPress={onPress}
19
+ >
20
+ {imageUrl ? (
21
+ <Image source={{ uri: imageUrl }} style={styles.buttonImage} />
22
+ ) : (
23
+ <Text style={styles.buttonText}>Chat</Text>
24
+ )}
25
+ </TouchableOpacity>
26
+ );
27
+ };
28
+
29
+ const styles = StyleSheet.create({
30
+ button: {
31
+ position: "absolute",
32
+ bottom: 20,
33
+ right: 20,
34
+ borderRadius: 30,
35
+ width: 60,
36
+ height: 60,
37
+ justifyContent: "center",
38
+ alignItems: "center",
39
+ elevation: 5,
40
+ shadowColor: "#000",
41
+ shadowOffset: { width: 0, height: 2 },
42
+ shadowOpacity: 0.25,
43
+ shadowRadius: 3.84,
44
+ },
45
+ buttonText: {
46
+ color: "white",
47
+ fontSize: 16,
48
+ fontWeight: "bold",
49
+ },
50
+ buttonImage: {
51
+ width: 40,
52
+ height: 40,
53
+ borderRadius: 20,
54
+ },
55
+ });
56
+
57
+ export default FloatingButton;
@@ -0,0 +1,11 @@
1
+ import React, { useEffect, useState } from "react";
2
+ import { View, ActivityIndicator } from "react-native";
3
+ import { WebView } from "react-native-webview";
4
+
5
+ const LoadingIndicator: React.FC = () => (
6
+ <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
7
+ <ActivityIndicator size="large" color="#0000ff" />
8
+ </View>
9
+ );
10
+
11
+ export default LoadingIndicator;
package/src/config.ts ADDED
@@ -0,0 +1,4 @@
1
+ export const config = {
2
+ API_URL: process.env.API_URL || 'https://api.robylon.com',
3
+ DEBUG: process.env.DEBUG === 'true'
4
+ };
@@ -0,0 +1,3 @@
1
+ const BASE_CHATBOT_DOMAIN = process.env.CHATBOT_DOMAIN || "";
2
+ const CHATBOT_PATH = process.env.CHATBOT_PATH || "";
3
+ export const BASE_CHATBOT_URL = `${BASE_CHATBOT_DOMAIN}/${CHATBOT_PATH}`;
@@ -0,0 +1,6 @@
1
+ // declare module "react-native" {
2
+ // export const View: any;
3
+ // export const ActivityIndicator: any;
4
+ // export const Linking: any;
5
+ // // Add other React Native exports as needed
6
+ // }
package/src/index.tsx ADDED
@@ -0,0 +1,2 @@
1
+ export { default as ChatbotSDK } from "./Chatbotsdk";
2
+ export { openChatbot } from "./openChatbot";
@@ -0,0 +1,11 @@
1
+ import { Linking } from "react-native";
2
+ import { BASE_CHATBOT_URL } from "./constants";
3
+
4
+ export const openChatbot = (
5
+ chatbotId: string,
6
+ additionalParams: Record<string, string> = {}
7
+ ): void => {
8
+ const params = new URLSearchParams({ id: chatbotId, ...additionalParams });
9
+ const url = `${BASE_CHATBOT_URL}?${params.toString()}`;
10
+ Linking.openURL(url);
11
+ };
File without changes