chat-sdk-connect
v2.1.29
Published
Universal chat SDK that works with Angular, React, React Native, and vanilla JavaScript
Readme
Universal Chat SDK v2
A framework-agnostic chat SDK that works seamlessly with Angular, React, React Native, and vanilla JavaScript.
Features
- 🚀 Universal: Works with any JavaScript framework or vanilla JS
- 📱 Cross-platform: Web, React Native, and mobile-responsive
- 🎨 Customizable: Full styling and configuration options
- 🔌 Pluggable: Event-driven architecture with hooks
- 📦 Lightweight: Minimal dependencies, tree-shakeable
- 🔒 Secure: Built-in security best practices
Installation
npm install chat-sdk-connectFramework-Specific Imports
For Angular (No React Dependencies)
import { ChatService, ChatComponent } from 'chat-sdk-connect/angular';For React
import { ChatWidget, useChat } from 'chat-sdk-connect/react';For React Native
import { useChat } from 'chat-sdk-connect/react-native';For Vanilla JavaScript
import { createChatWidget } from 'chat-sdk-connect/vanilla';Quick Start
Angular
// chat.service.ts
import { Injectable, Inject, PLATFORM_ID } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';
@Injectable({
providedIn: 'root'
})
export class ChatService {
private chatCore: any = null;
private chatUI: any = null;
constructor(@Inject(PLATFORM_ID) private platformId: Object) { }
async initialize(containerId: string, config: any) {
if (!isPlatformBrowser(this.platformId)) return;
const container = document.getElementById(containerId);
if (!container) throw new Error(`Container not found: ${containerId}`);
const { ChatComponent } = await import('chat-sdk-connect/angular');
const elementRef = { nativeElement: container };
const chatComponent = new ChatComponent(elementRef, config);
await chatComponent.initializeUI();
this.chatCore = chatComponent.chatCore;
this.chatUI = chatComponent.chatUI;
}
async openChat() {
if (this.chatUI?.openChat) await this.chatUI.openChat();
}
async closeChat() {
if (this.chatUI?.closeChat) await this.chatUI.closeChat();
}
}// app.component.ts
import { Component, OnInit } from '@angular/core';
import { ChatService } from './chat.service';
@Component({
selector: 'app-root',
template: `
<div id="chat-container"></div>
<button (click)="openChat()">Open Chat</button>
`
})
export class AppComponent implements OnInit {
constructor(private chatService: ChatService) {}
async ngOnInit() {
await this.chatService.initialize('chat-container', {
apiUrl: 'http://localhost:3001',
sdkKey: 'your-sdk-key',
region: 'ap-southeast-1',
title: 'Support Chat',
primaryColor: '#EA5800'
});
}
async openChat() {
await this.chatService.openChat();
}
}React
import { ChatWidget } from 'chat-sdk-connect/react';
function App() {
return (
<div>
<ChatWidget config={{
apiUrl: 'http://localhost:3001',
sdkKey: 'your-sdk-key',
region: 'ap-southeast-1',
title: 'Support Chat',
primaryColor: '#EA5800'
}} />
</div>
);
}React Native
import React from 'react';
import { View } from 'react-native';
import { ChatWidget, useChat } from 'chat-sdk-connect/react-native';
// Option 1: Pre-built Component
function App() {
return (
<View style={{ flex: 1 }}>
<ChatWidget config={{
apiUrl: 'http://localhost:3001',
sdkKey: 'your-sdk-key',
region: 'ap-southeast-1',
title: 'Support Chat',
primaryColor: '#EA5800'
}} />
</View>
);
}
// Option 2: Custom Implementation with Hook
function CustomChatScreen() {
const { messages, isTyping, sendMessage, startChat } = useChat({
apiUrl: 'http://localhost:3001',
sdkKey: 'your-sdk-key',
region: 'ap-southeast-1'
});
return (
<View style={{ flex: 1 }}>
{/* Your custom chat UI */}
{isTyping && <Text>Agent is typing...</Text>}
</View>
);
}Vanilla JavaScript
<!DOCTYPE html>
<html>
<head>
<title>Chat Widget</title>
</head>
<body>
<div id="chat-container"></div>
<script type="module">
import { initChatWidget } from '@your-org/chat-sdk-universal';
initChatWidget('chat-container', {
apiUrl: 'https://your-api.com',
instanceId: 'your-instance-id',
contactFlowId: 'your-contact-flow-id',
region: 'us-east-1',
title: 'Customer Support',
primaryColor: '#007bff'
});
</script>
</body>
</html>Script Tag (UMD)
<script src="https://unpkg.com/@your-org/chat-sdk-universal/dist/chat-sdk.umd.js"></script>
<div id="chat-widget-container"></div>
<script>
window.ChatSDKConfig = {
apiUrl: 'https://your-api.com',
instanceId: 'your-instance-id',
contactFlowId: 'your-contact-flow-id',
region: 'us-east-1'
};
</script>React
import React from 'react';
import { ChatWidget, useChat } from '@your-org/chat-sdk-universal/react';
// Option 1: Component
function App() {
return (
<div>
<ChatWidget config={{
apiUrl: 'https://your-api.com',
instanceId: 'your-instance-id',
contactFlowId: 'your-contact-flow-id'
}} />
</div>
);
}
// Option 2: Hook
function CustomChat() {
const {
isConnected,
messages,
sendMessage,
startChat,
endChat
} = useChat({
apiUrl: 'https://your-api.com',
instanceId: 'your-instance-id',
contactFlowId: 'your-contact-flow-id'
});
return (
<div>
{/* Your custom UI */}
</div>
);
}React Native
import React from 'react';
import { View } from 'react-native';
import { ChatWidget } from '@your-org/chat-sdk-universal/react-native';
function App() {
return (
<View style={{ flex: 1 }}>
<ChatWidget
config={{
apiUrl: 'https://your-api.com',
instanceId: 'your-instance-id',
contactFlowId: 'your-contact-flow-id',
userData: {} // Used instead of localStorage
}}
/>
</View>
);
}Angular
// app.module.ts
import { NgModule } from '@angular/core';
import { ChatService } from '@your-org/chat-sdk-universal/angular';
@NgModule({
providers: [ChatService]
})
export class AppModule {}
// chat.component.ts
import { Component, ElementRef, OnInit, OnDestroy } from '@angular/core';
import { ChatComponent } from '@your-org/chat-sdk-universal/angular';
@Component({
selector: 'app-chat',
template: '<div></div>'
})
export class ChatWidgetComponent extends ChatComponent implements OnInit, OnDestroy {
constructor(elementRef: ElementRef) {
super(elementRef, {
apiUrl: 'https://your-api.com',
instanceId: 'your-instance-id',
contactFlowId: 'your-contact-flow-id'
});
}
ngOnInit() {
this.initializeUI();
}
ngOnDestroy() {
this.destroy();
}
}Configuration Options
const config = {
// Required
apiUrl: 'https://your-api.com',
instanceId: 'your-instance-id',
contactFlowId: 'your-contact-flow-id',
// Optional
region: 'us-east-1',
logoUrl: 'https://your-logo.png',
title: 'Customer Support',
subtitle: 'We\'re here to help',
primaryColor: '#007bff',
fontFamily: 'system-ui, sans-serif',
// Custom styles (CSS string)
customStyles: `
.chat-widget { border-radius: 20px; }
.chat-launcher { background: linear-gradient(45deg, #ff6b6b, #4ecdc4); }
`,
// User data (React Native uses this instead of localStorage)
userData: {
userId: 'user123',
name: 'John Doe'
},
// Event callbacks
onChatStart: (session) => console.log('Chat started', session),
onChatEnd: () => console.log('Chat ended'),
onMessageReceived: (message) => console.log('Received', message),
onMessageSent: (message) => console.log('Sent', message)
};API Reference
ChatCore
The core chat functionality that's framework-agnostic.
import { ChatCore } from '@your-org/chat-sdk-universal';
const chatCore = new ChatCore(config);
// Methods
await chatCore.startChat();
await chatCore.endChat();
await chatCore.sendMessage('Hello', 'text');
const state = chatCore.getState();
chatCore.updateConfig(newConfig);
chatCore.destroy();
// Events
chatCore.on('chatStarted', (data) => {});
chatCore.on('chatEnded', () => {});
chatCore.on('messageReceived', (message) => {});
chatCore.on('messageSent', (message) => {});
chatCore.on('chatError', (error) => {});ChatUI
The UI layer that renders the chat interface.
import { ChatUI } from '@your-org/chat-sdk-universal';
const chatUI = new ChatUI(containerElement, chatCore);
// Methods
chatUI.updateConfig(newConfig);
chatUI.destroy();Advanced Usage
Custom Storage Adapter
const config = {
// ... other config
storageAdapter: {
getItem: (key) => myStorage.get(key),
setItem: (key, value) => myStorage.set(key, value),
removeItem: (key) => myStorage.remove(key)
}
};Event Handling
const chatCore = new ChatCore(config);
chatCore.on('messageReceived', (message) => {
// Handle incoming messages
if (message.type === 'interactive') {
// Handle interactive messages
}
});
chatCore.on('chatError', (error) => {
// Handle errors
console.error('Chat error:', error);
});Custom Styling
const config = {
customStyles: `
.chat-widget {
--primary-color: #your-color;
--font-family: 'Your Font', sans-serif;
}
.chat-launcher {
background: var(--primary-color);
box-shadow: 0 4px 20px rgba(0,0,0,0.15);
}
.chat-window {
border-radius: 16px;
overflow: hidden;
}
`
};Browser Support
- Chrome 60+
- Firefox 55+
- Safari 12+
- Edge 79+
- React Native 0.60+
License
MIT License - see LICENSE file for details.
Framework Comparison
| Feature | Angular | React | React Native | Vanilla JS | |---------|---------|-------|--------------|------------| | Bundle Size | Smallest | Small | Medium | Smallest | | Dependencies | None | React 16.8+ | React Native 0.60+ | None | | TypeScript | ✅ Full support | ✅ Full support | ✅ Full support | ✅ Available | | SSR Support | ✅ Built-in | ✅ Available | ❌ N/A | ✅ Available | | Tree Shaking | ✅ Optimal | ✅ Good | ✅ Good | ✅ Manual | | Setup Complexity | Medium | Easy | Medium | Easy |
Framework-Specific Benefits
Angular
- No React bloat: Zero React dependencies
- Smaller bundles: Only includes Angular-specific code
- SSR ready: Built-in server-side rendering support
- Type safety: Full TypeScript integration
- Angular patterns: Uses services and dependency injection
React
- Component-based: Natural React component integration
- Hooks support: Use
useChathook for state management - JSX friendly: Clean component syntax
- Ecosystem: Works with React ecosystem tools
React Native
- Mobile optimized: Native mobile performance
- Cross-platform: iOS and Android support
- Native modules: Access to device features
- Offline support: Built-in offline capabilities
Vanilla JavaScript
- Framework agnostic: Works anywhere
- Minimal overhead: No framework dependencies
- Legacy support: Works with older browsers
- Easy integration: Drop-in solution
Documentation
- Angular Usage Guide - Complete Angular integration guide
- React Usage Guide - React component examples
- React Native Guide - Mobile implementation with typing indicators
- Integration Guide - General integration patterns
- API Reference - Complete API documentation
Development
Local Development with npm link
# In the SDK directory
cd packages/ev-chat-sdk
npm link
# In your project directory
npm link chat-sdk-connectBuilding the SDK
npm run buildTesting
npm testLicense
MIT License - see LICENSE file for details.
