npm package: @skywu/virtual-chat-sdk
Description: Virtual Chat SDK - Floating chat widget with 20+ languages support for seamless website integration
Author: Virtual Chat Team
Latest version: 2.5.4

# @skywu/virtual-chat-sdk

[![npm version](https://badge.fury.io/js/%40skywu%2Fvirtual-chat-sdk.svg)](https://badge.fury.io/js/%40skywu%2Fvirtual-chat-sdk)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

A modern JavaScript/TypeScript SDK for embedding floating chat widgets into web applications. Features real-time messaging, virtual chat simulations, **20+ languages support**, and seamless integration.

## ✨ Features

- 🎈 **Floating Button Mode** - Non-intrusive chat widget with smooth expand/collapse animations
- 🌍 **20+ Languages** - Built-in i18n support (English, 简体中文, 繁體中文, Español, हिन्दी, العربية, Português, Deutsch, 日本語, 한국어, Français, Русский, Italiano, Türkçe, Polski, Tiếng Việt, ไทย, Bahasa Indonesia, Nederlands, and more)
- 🎨 **Multiple UI Templates** - WhatsApp and Telegram-style themes with dark mode support
- ⚡ **Real-time Communication** - WebSocket-based messaging with automatic reconnection
- 📱 **Responsive Design** - Optimized for desktop, tablet, and mobile devices
- 🔧 **Highly Customizable** - Configurable positioning, colors, and behavior
- 📦 **TypeScript Support** - Full type definitions and IntelliSense support
- 🚀 **Zero Config** - Works out of the box with minimal setup
- 🔒 **Secure** - Built-in XSS protection and Shadow DOM isolation

## 📦 Installation

### npm/yarn (Recommended)

```bash
# npm
npm install @skywu/virtual-chat-sdk

# yarn
yarn add @skywu/virtual-chat-sdk

# pnpm
pnpm add @skywu/virtual-chat-sdk
```

### CDN (Browser)

### Option A: UMD (script tag) - Floating Button Mode

```html
<!-- 1) Include SDK from your server -->
<script src="https://YOUR_SERVER_DOMAIN/sdk/chat-sdk.umd.js"></script>

<!-- 2) Create a container (optional for floating mode) -->
<div id="chat-container"></div>

<!-- 3) Initialize with floating button mode -->
<script>
  const chat = ChatSDK.init({
    container: '#chat-container',
    projectId: 'YOUR_PROJECT_ID',
    username: 'Visitor',
    language: 'zh',
    uiTemplate: 'whatsapp',
    autoJoin: true,
    // point SDK API to your server
    apiBaseUrl: 'https://YOUR_SERVER_DOMAIN',
    socketUrl: 'https://YOUR_SERVER_DOMAIN',

    // Floating button mode (recommended for third-party sites)
    mode: 'floating',
    floatingButton: {
      position: 'bottom-right',
      offset: { bottom: 20, right: 20 },
      icon: 'chat'
    }
  })
  // No need to call chat.open() in floating mode - button handles it
</script>
```

### Option B: ESM (module) - Floating Button Mode

```html
<script type="module">
  import { ChatSDK } from 'https://YOUR_SERVER_DOMAIN/sdk/chat-sdk.esm.js'
  const chat = ChatSDK.init({
    container: '#chat-container',
    projectId: 'YOUR_PROJECT_ID',
    username: 'Visitor',
    language: 'en',
    autoJoin: true,
    apiBaseUrl: 'https://YOUR_SERVER_DOMAIN',
    socketUrl: 'https://YOUR_SERVER_DOMAIN',

    // Floating button mode (recommended for third-party sites)
    mode: 'floating',
    floatingButton: {
      position: 'bottom-right',
      offset: { bottom: 20, right: 20 }
    }
  })
  // No need to call chat.open() in floating mode - button handles it
</script>
```

## Display Modes

### Floating Button Mode (Recommended for Third-Party Sites)
- **Default behavior**: Shows a floating button, expands to full-screen chat when clicked
- **Configuration**: `mode: 'floating'` with `floatingButton` options
- **Best for**: Third-party website integration, non-intrusive user experience

### Full-Screen Mode (Traditional)
- **Behavior**: Directly shows the chat interface
- **Configuration**: `mode: 'fullscreen'` or omit the mode property
- **Best for**: Dedicated chat pages, internal applications

## Notes:
- No API key is required on the client.
- Replace `YOUR_SERVER_DOMAIN` with your actual server domain where this app is hosted.
- `projectId` can be found in the Admin panel (Projects list).
- CORS: ensure your server allows the third‑party origin if needed.
- Optional UI customization: `primaryColor`, `backgroundColor`, `width`, `height`.
- **Floating button positioning**: `position` ('bottom-right', 'bottom-left', 'top-right', 'top-left'), `offset` (pixels from edges), `zIndex`


### 1. Include the SDK
## Floating Button Configuration Examples

### Basic Floating Button
```javascript
const chat = ChatSDK.init({
  container: document.body,
  projectId: 'YOUR_PROJECT_ID',
  mode: 'floating',
  apiBaseUrl: 'https://YOUR_SERVER_DOMAIN',
  socketUrl: 'https://YOUR_SERVER_DOMAIN'
})
```

### Custom Positioned Floating Button
```javascript
const chat = ChatSDK.init({
  container: document.body,
  projectId: 'YOUR_PROJECT_ID',
  mode: 'floating',
  floatingButton: {
    position: 'bottom-left',        // 'bottom-right', 'bottom-left', 'top-right', 'top-left'
    offset: { bottom: 24, left: 24 }, // Distance from edges in pixels
    icon: 'chat',                   // Button icon type
    zIndex: 2147483000             // CSS z-index for layering
  },
  apiBaseUrl: 'https://YOUR_SERVER_DOMAIN',
  socketUrl: 'https://YOUR_SERVER_DOMAIN'
})
```

### Full-Screen Mode (Traditional)
```javascript
const chat = ChatSDK.init({
  container: '#chat-container',
  projectId: 'YOUR_PROJECT_ID',
  mode: 'fullscreen',  // or omit this line for default behavior
  apiBaseUrl: 'https://YOUR_SERVER_DOMAIN',
  socketUrl: 'https://YOUR_SERVER_DOMAIN'
})
chat.open() // Required for full-screen mode
```

```html
<!-- Via CDN -->
<script src="https://cdn.example.com/chat-sdk.umd.js"></script>

<!-- Or download and host locally -->
<script src="path/to/chat-sdk.umd.js"></script>
```

### 2. Create a Container

```html
<div id="chat-container"></div>
```

### 3. Initialize the Chat

```javascript
const chat = ChatSDK.init({
  container: '#chat-container',
  projectId: 'your-project-id',
  username: 'John Doe',
  language: 'en',
  theme: 'light',
  onReady: () => console.log('Chat ready!'),
  onMessage: (message) => console.log('New message:', message)
});
```

## Configuration Options

### Required Options

| Option | Type | Description |
|--------|------|-------------|
| `container` | `string \| HTMLElement` | CSS selector or DOM element for the chat widget |
| `projectId` | `string` | Unique identifier for your chat project |

### Optional Options

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `templateId` | `string` | `undefined` | Specific template to load (uses project default if not specified) |
| `userId` | `string` | Auto-generated | Unique user identifier |
| `username` | `string` | Auto-generated | Display name for the user |
| `language` | `string` | `'en'` | Language code: `'en'`, `'zh'`, `'zh-TW'`, `'es'`, `'hi'`, `'ar'`, `'pt'`, `'de'`, `'ja'`, `'ko'`, `'fr'`, `'ru'`, `'it'`, `'tr'`, `'pl'`, `'vi'`, `'th'`, `'id'`, `'nl'` |
| `theme` | `'light' \| 'dark' \| 'auto'` | `'light'` | UI theme |
| `uiTemplate` | `'whatsapp' \| 'telegram' \| 'discord' \| 'slack'` | `'whatsapp'` | Chat UI style |
| `width` | `string \| number` | `'400px'` | Widget width |
| `height` | `string \| number` | `'600px'` | Widget height |
| `autoJoin` | `boolean` | `false` | Automatically join chat on initialization |
| `showAvatars` | `boolean` | `true` | Show user avatars |
| `showUsernames` | `boolean` | `true` | Show usernames |
| `allowInput` | `boolean` | `true` | Allow user to send messages |

### API Configuration

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `apiBaseUrl` | `string` | Current origin | Base URL for API requests |
| `socketUrl` | `string` | Current origin | WebSocket server URL |
| `token` | `string` | `undefined` | Authentication token |

### Event Callbacks

| Callback | Parameters | Description |
|----------|------------|-------------|
| `onReady` | `()` | Called when SDK is initialized |
| `onOpen` | `()` | Called when chat widget opens |
| `onClose` | `()` | Called when chat widget closes |
| `onJoin` | `({ userId, username })` | Called when user joins chat |
| `onMessage` | `(message)` | Called when any message is received |
| `onUserMessage` | `(message)` | Called when user sends a message |
| `onError` | `(error)` | Called when an error occurs |
| `onLanguageChange` | `(language)` | Called when language changes |
| `onThemeChange` | `(theme)` | Called when theme changes |

## API Methods

### Core Methods

```javascript
// Open/close the chat widget
chat.open();
chat.close();

// Join/leave the chat
chat.joinChat();
chat.leaveChat();

// Send a message programmatically
chat.sendMessage('Hello world!', 'text');

// Destroy the widget
chat.destroy();
```

### Configuration Methods

```javascript
// Change language
chat.setLanguage('zh');

// Change theme
chat.setTheme('dark');

// Switch template
chat.setTemplate('template-id');
```

### State Methods

```javascript
// Check widget state
const isOpen = chat.isOpen();
const isJoined = chat.isJoined();

// Get configuration
const config = chat.getConfig();

// Get message history
const messages = chat.getMessages();
```

### Event Methods

```javascript
// Listen to events
chat.on('message', (message) => {
  console.log('New message:', message);
});

// Remove event listeners
chat.off('message');

// Emit custom events
chat.emit('custom-event', data);
```

## Examples

### Basic Chat Widget

```javascript
const chat = ChatSDK.init({
  container: '#chat',
  projectId: 'demo-project',
  username: 'Visitor',
  autoJoin: true
});
```

### Customized Widget

```javascript
const chat = ChatSDK.init({
  container: document.getElementById('chat-container'),
  projectId: 'my-project',
  templateId: 'customer-support',
  username: 'Customer',
  language: 'zh',
  theme: 'dark',
  width: '100%',
  height: '500px',
  uiTemplate: 'telegram',

  onReady: () => {
    console.log('Chat is ready!');
    chat.open();
  },

  onMessage: (message) => {
    // Track messages in analytics
    analytics.track('chat_message_received', {
      content: message.content,
      type: message.messageType
    });
  },

  onUserMessage: (message) => {
    // Track user messages
    analytics.track('chat_message_sent', {
      content: message.content
    });
  }
});
```

### Multi-language Support (20+ Languages)

```javascript
const chat = ChatSDK.init({
  container: '#chat',
  projectId: 'support-chat',
  language: 'en', // Start with English
  mode: 'floating'
});

// Language switcher - dynamically change UI language
document.getElementById('lang-zh').addEventListener('click', () => {
  chat.setLanguage('zh'); // 简体中文
});

document.getElementById('lang-es').addEventListener('click', () => {
  chat.setLanguage('es'); // Español
});

document.getElementById('lang-ar').addEventListener('click', () => {
  chat.setLanguage('ar'); // العربية (RTL support)
});

// Supported languages:
// 'en' (English), 'zh' (简体中文), 'zh-TW' (繁體中文), 'es' (Español),
// 'hi' (हिन्दी), 'ar' (العربية), 'pt' (Português), 'de' (Deutsch),
// 'ja' (日本語), 'ko' (한국어), 'fr' (Français), 'ru' (Русский),
// 'it' (Italiano), 'tr' (Türkçe), 'pl' (Polski), 'vi' (Tiếng Việt),
// 'th' (ไทย), 'id' (Bahasa Indonesia), 'nl' (Nederlands)
```

### Event-driven Integration

```javascript
const chat = ChatSDK.init({
  container: '#chat',
  projectId: 'sales-demo',

  onJoin: ({ userId, username }) => {
    // Notify your backend
    fetch('/api/chat-joined', {
      method: 'POST',
      body: JSON.stringify({ userId, username })
    });
  },

  onUserMessage: (message) => {
    // Process user messages
    if (message.content.includes('pricing')) {
      // Show pricing modal
      showPricingModal();
    }
  },

  onError: (error) => {
    // Handle errors gracefully
    console.error('Chat error:', error);
    showErrorNotification('Chat temporarily unavailable');
  }
});
```

## Browser Support

- Chrome 60+
- Firefox 55+
- Safari 12+
- Edge 79+
- Mobile browsers (iOS Safari, Chrome Mobile)

## TypeScript Support

The SDK includes full TypeScript definitions:

```typescript
import { ChatSDK, ChatSDKConfig, ChatMessage } from '@skywu/virtual-chat-sdk';

const config: ChatSDKConfig = {
  container: '#chat',
  projectId: 'my-project',
  language: 'zh', // 简体中文
  mode: 'floating',
  onMessage: (message: ChatMessage) => {
    console.log(message.content);
  }
};

const chat = ChatSDK.init(config);
```

## Error Handling

```javascript
const chat = ChatSDK.init({
  container: '#chat',
  projectId: 'my-project',

  onError: (error) => {
    switch (error.code) {
      case 'CONTAINER_NOT_FOUND':
        console.error('Chat container not found');
        break;
      case 'PROJECT_LOAD_ERROR':
        console.error('Failed to load project');
        break;
      case 'SOCKET_CONNECTION_ERROR':
        console.error('Connection failed');
        break;
      default:
        console.error('Unknown error:', error.message);
    }
  }
});
```

## Building from Source

```bash
# Install dependencies
npm install

# Build for production
npm run build

# Build and watch for development
npm run dev

# Type checking
npm run type-check
```

## License

MIT License - see LICENSE file for details.