Skip to content

feat: 🎸 implement widget state (loaded, error) #9

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Sep 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions .npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
examples/

# Logs
*.log
npm-debug.log

# Runtime data
tmp
build
dist
*.tgz

# Dependency directory
node_modules/

.DS_Store
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ export default function App() {
onClosed={() => console.log('Widget closed')}
onLoaded={() => console.log('Widget loaded')}
onNewMessage={(message) => console.log('New message:', message)}
onError={(message) => console.log('Error', message)}
/>
</View>
);
Expand All @@ -85,6 +86,7 @@ export default function App() {
| onClosed | () => void | No | Callback when the widget is closed |
| onLoaded | () => void | No | Callback when the widget is loaded |
| onNewMessage | () => void | No | Callback when a new message is received |
| onError | (error:string) => void | No | Callback function triggered when an error occurs. |

## Methods

Expand Down
7 changes: 6 additions & 1 deletion examples/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { Button, SafeAreaView, StyleSheet, View } from 'react-native';

export default function App() {
const chativeWidgetRef = useRef(null);
const channelId = 's49f3a621-2f07-45a4-8019-92663014b998'; // Replace with your channel id
const channelId = 's49f3a621-2f07-45a4-8019-92663014b997'; // Replace with your channel id

const handleOpenModal = () => {
chativeWidgetRef.current.show();
Expand All @@ -22,6 +22,10 @@ export default function App() {
console.log('onNewMessage');
}

const onError = (error) => {
console.log('Error:', error);
}

const user = {
user_id: 'UNIQUE_USER_ID',
user: {
Expand All @@ -44,6 +48,7 @@ export default function App() {
onLoaded={onLoaded}
onClosed={handleCloseModal}
onNewMessage={onNewMessage}
onError={onError}
/>
</SafeAreaView>
);
Expand Down
4 changes: 2 additions & 2 deletions examples/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@
"android": "expo start --android",
"ios": "expo start --ios",
"web": "expo start --web",
"livechat": "yarn remove @chative.io/react-native-widget || true && yarn cache clean && yarn add ../chative.io-react-native-widget-v0.5.0.tgz"
"livechat": "yarn remove @chative.io/react-native-widget || true && yarn cache clean && yarn add ../chative.io-react-native-widget-v0.5.1.tgz"
},
"dependencies": {
"@chative.io/react-native-widget": "../chative.io-react-native-widget-v0.5.0.tgz",
"@chative.io/react-native-widget": "../chative.io-react-native-widget-v0.5.1.tgz",
"@react-native-async-storage/async-storage": "^1.23.1",
"@types/react": "~18.2.79",
"expo": "~51.0.20",
Expand Down
6 changes: 3 additions & 3 deletions examples/yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -796,9 +796,9 @@
"@babel/helper-validator-identifier" "^7.24.7"
to-fast-properties "^2.0.0"

"@chative.io/react-native-widget@../chative.io-react-native-widget-v0.5.0.tgz":
version "0.5.0"
resolved "../chative.io-react-native-widget-v0.5.0.tgz#b074a980cd915570a5770b8a540949b47b951214"
"@chative.io/react-native-widget@../chative.io-react-native-widget-v0.5.1.tgz":
version "0.5.1"
resolved "../chative.io-react-native-widget-v0.5.1.tgz#915eab11f56669755299544d916a25c03297064a"

"@expo/bunyan@^4.0.0":
version "4.0.0"
Expand Down
1 change: 1 addition & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ declare module '@chative.io/react-native-widget' {
insetBottom?: number;
onClosed?: () => void;
onLoaded?: () => void;
onError?: (error: any) => void;
onNewMessage?: (message: any) => void;
}

Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@chative.io/react-native-widget",
"version": "0.5.0",
"version": "0.5.2",
"description": "React Native SDK for Chative",
"main": "index.js",
"scripts": {
Expand Down
3 changes: 3 additions & 0 deletions src/ChativeWidget.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ const propTypes = {
onClosed: PropTypes.func,
onLoaded: PropTypes.func,
onNewMessage: PropTypes.func,
onError: PropTypes.func,
};

const ChativeWidget = forwardRef(({
Expand All @@ -27,6 +28,7 @@ const ChativeWidget = forwardRef(({
onClosed,
onLoaded,
onNewMessage,
onError,
}, ref) => {
const [isModalVisible, setIsModalVisible] = useState(false);
const webViewRef = useRef(null);
Expand Down Expand Up @@ -74,6 +76,7 @@ const ChativeWidget = forwardRef(({
onLoaded={onLoaded}
onNewMessage={onNewMessage}
onClosedWidget={handleClose}
onError={onError}
/>
</View>
</SafeAreaView>
Expand Down
18 changes: 14 additions & 4 deletions src/WebView.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,21 @@ import React, { forwardRef, useImperativeHandle, useRef } from 'react';
import { StyleSheet } from 'react-native';
import WebView from 'react-native-webview';
import { WIDGET_URL } from './constants';
import { generateScript, safeParse } from './utils';
import { generateScript, generateScriptGetError, safeParse } from './utils';

const propTypes = {
channelId: PropTypes.string.isRequired,
user: PropTypes.object,
onLoaded: PropTypes.func,
onClosedWidget: PropTypes.func,
onNewMessage: PropTypes.func,
onError: PropTypes.func,
};

const WebViewComponent = forwardRef(({ channelId, user, onLoaded, onClosedWidget, onNewMessage }, ref) => {
const WebViewComponent = forwardRef(({ channelId, user, onLoaded, onClosedWidget, onNewMessage, onError }, ref) => {
const webViewRef = useRef(null);
const javascriptInit = React.useMemo(() => generateScript(user), [user]);
const errorScript = React.useMemo(() => generateScriptGetError(), []);

useImperativeHandle(ref, () => ({
injectJavaScript: (script) => {
Expand All @@ -30,12 +32,12 @@ const WebViewComponent = forwardRef(({ channelId, user, onLoaded, onClosedWidget
<WebView
ref={webViewRef}
style={styles.webViewContainer}
injectedJavaScript={errorScript}
source={{
uri: `${WIDGET_URL}/${channelId}?mode=livechat&state=${user ? 'off' : 'on'}`,
}}
onLoadEnd={() => {
webViewRef.current?.injectJavaScript(javascriptInit);
onLoaded && onLoaded();
}}
onMessage={(event) => {
const { data } = event.nativeEvent;
Expand All @@ -48,6 +50,14 @@ const WebViewComponent = forwardRef(({ channelId, user, onLoaded, onClosedWidget
if (parsedData.event === 'new-agent-message') {
onNewMessage && onNewMessage();
}

if (parsedData.event === 'ready') {
onLoaded && onLoaded();
}

if (parsedData.event === 'error') {
onError && onError(parsedData.message);
}
}}
/>
);
Expand All @@ -61,4 +71,4 @@ const styles = StyleSheet.create({

WebViewComponent.propTypes = propTypes;

export default WebViewComponent;
export default React.memo(WebViewComponent);
1 change: 1 addition & 0 deletions src/constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@ export const COLOR_WHITE = '#fff';
export const INDEX_SHOW = 999;
export const INDEX_HIDE = -1;
export const WIDGET_URL = 'https://messenger.svc.chative.io/site';
export const QUERY_URL = 'https://gateway.svc.chative.io/web/live/query';
36 changes: 36 additions & 0 deletions src/utils.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { QUERY_URL, WIDGET_URL } from './constants';
export const generateScript = (user = {}) => {
const userString = safeStringify(user);
return `
Expand Down Expand Up @@ -25,9 +26,44 @@ export const generateScript = (user = {}) => {
window.cti_api('addEventListener', { event: 'new-agent-message', callback: () => {
window.ReactNativeWebView.postMessage(JSON.stringify({ event: 'new-agent-message' }));
}});

window.cti_api('addEventListener', { event: 'ready', callback: () => {
window.ReactNativeWebView.postMessage(JSON.stringify({ event: 'ready' }));
}});
`;
};

export const generateScriptGetError = (channelId) => {
return `
function getTimeZone() {
const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
return timeZone;
}
(function() {
fetch("${QUERY_URL}", {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
"app_id": "${channelId}",
"user_id": "",
"locale": "en-US",
"timezone": getTimeZone(),
"template": false,
"host": "${WIDGET_URL}/${channelId}?mode=livechat"
})
}).then((response) => {
if (response.status !== 200) {
window.ReactNativeWebView.postMessage(JSON.stringify({ event: 'error', message: 'missing_config' }));
}
}).catch((error) => {
window.ReactNativeWebView.postMessage(JSON.stringify({ event: 'error', data: error }));
});
})();
`;
}

export const WidgetApi = (event, data) => {
return `
window.cti_api('${event}', ${data});
Expand Down