data-platform-chatbot
Version:
A configurable and customizable React chat component library
471 lines (374 loc) โข 11.9 kB
Markdown
A configurable and customizable React chat component library built with TypeScript, Vite, and Tailwind CSS.
- ๐จ **Fully Customizable** - Configure themes, colors, positioning, and more
- ๐ฑ **Responsive Design** - Works seamlessly on desktop and mobile
- ๐ **Streaming Support** - Real-time streaming chat responses with OpenAI-compatible API
- ๐ **Rich Content** - Supports markdown tables, links, and formatted text
- ๐ก **Smart Suggestions** - Interactive suggestion bubbles with custom icons that send messages directly
- ๐ **Copy Functionality** - Easy message copying with clipboard integration
- ๐พ **Persistent Storage** - Messages are automatically saved to localStorage
- ๐ฏ **TypeScript** - Full TypeScript support with comprehensive type definitions
- โก **Lightweight** - Minimal dependencies (only Lucide React for icons)
- ๐งช **Well Tested** - Comprehensive visual and functional tests with Playwright
- ๐ญ **Multiple Themes** - Built-in themes (default, dark, green, pixie) with custom theme support
- ๐จ **Live Theme Editor** - Real-time theme customization in development with color pickers and export
- ๐ **Error Handling** - Automatic retry functionality with user-friendly error messages
- ๐ก๏ธ **Input Validation** - Built-in message sanitization and validation
- ๐ช **Error Boundaries** - Graceful error handling with React Error Boundaries
## Prerequisites
- Node.js >= 18.0.0
- React >= 18.0.0
- React DOM >= 18.0.0
```bash
npm install data-platform-chatbot lucide-react
yarn add data-platform-chatbot lucide-react
pnpm add data-platform-chatbot lucide-react
```
The component uses Tailwind CSS classes. Make sure Tailwind is configured in your project:
```bash
npm install -D tailwindcss @tailwindcss/postcss autoprefixer
```
Update your `tailwind.config.js`:
```js
/** @type {import('tailwindcss').Config} */
export default {
content: [
"./src/**/*.{js,ts,jsx,tsx}",
"./node_modules/data-platform-chatbot/dist/**/*.{js,ts,jsx,tsx}"
],
theme: { extend: {} },
plugins: [],
}
```
**IMPORTANT**: The chat component requires a proxy configuration to work in development. Without this, chat requests will fail.
Add this to your `vite.config.ts`:
```typescript
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [react()],
server: {
proxy: {
'/v1/chat/completions': {
target: process.env.VITE_PROXY_TARGET || 'http://44.215.72.157:8001',
changeOrigin: true,
secure: false,
},
},
},
})
```
Then use the proxy endpoint in your config:
```tsx
<ChatAssistant
config={{
endpoint: '/v1/chat/completions', // Use proxy path, not direct URL
// ... other config
}}
/>
```
```bash
git clone <repository-url>
cd data-chatbot
npm install
npx playwright install
npm run dev
```
```tsx
import React from 'react';
import { ChatAssistant } from 'data-platform-chatbot';
import 'data-platform-chatbot/dist/index.css';
function App() {
return (
<div>
<h1>My App</h1>
<ChatAssistant
config={{
endpoint: '/v1/chat/completions', // Use proxy endpoint
title: 'My Assistant',
theme: {
primary: '#3b82f6'
}
}}
/>
</div>
);
}
```
The `ChatAssistant` component accepts a `config` prop with the following options:
```tsx
interface ChatConfig {
endpoint?: string; // API endpoint for chat
model?: string; // Model name to use
headers?: Record<string, string>; // Custom headers
title?: string; // Chat window title
subtitle?: string; // Chat window subtitle
placeholder?: string; // Input placeholder text
position?: 'bottom-right' | 'bottom-left' | 'top-right' | 'top-left';
width?: number; // Chat window width
height?: number; // Chat window height
}
```
```tsx
interface ChatTheme {
primary?: string; // Primary color
background?: string; // Background color
userMessageBg?: string; // User message background
assistantMessageBg?: string; // Assistant message background
borderColor?: string; // Border color
textColor?: string; // Text color
fabBg?: string; // FAB background color
fabColor?: string; // FAB icon color
}
```
Suggestions appear when the input field is focused and send messages directly when clicked (no need to press send):
```tsx
import { Lightbulb, HelpCircle, MessageSquare, ArrowLeftRight } from 'lucide-react';
const config = {
suggestions: [
{ icon: <Lightbulb size={15} />, text: 'Explain this further' },
{ icon: <HelpCircle size={15} />, text: 'Give me an example' },
{ icon: <MessageSquare size={15} />, text: 'Possible follow-up questions' },
{ icon: <ArrowLeftRight size={15} />, text: 'Show me another options' },
]
};
```
The component expects your API endpoint to support streaming responses in the OpenAI format:
```typescript
// Request format
{
"model": "your-model",
"messages": [
{ "role": "user", "content": "Hello!" }
],
"stream": true
}
// Response format (Server-Sent Events)
data: {"choices":[{"delta":{"content":"Hello"}}]}
data: {"choices":[{"delta":{"content":" there!"}}]}
data: [DONE]
```
```bash
npm run dev
npm run build
npm run build:lib
npm run preview
npm test
npm run test:ui
npm run test:clean
npm run test:e2e
npm run test:e2e:ui
npm run test:e2e:debug
npm run test:visual
npm run test:report
npm run lint
npm run lint:fix
npm run playwright:install
```
1. **Start Development Server**
```bash
npm run dev
```
This starts the demo application at `http://localhost:5173`
2. **Use Live Theme Editor**
- Click the palette icon in the top-right corner to open the theme editor
- Adjust colors in real-time with color pickers or hex inputs
- See changes instantly applied to the chat component
- Export your custom theme configuration to clipboard
- Reset to default theme anytime
3. **Run Tests During Development**
```bash
npm run test:clean
npm run test:visual
npm run test:e2e
npm run test:e2e:debug
npm run test:report
```
4. **Build Library**
```bash
npm run build:lib
```
This creates the distributable library in the `dist/` folder
This project includes comprehensive visual and functional testing:
- **Visual Tests**: Take screenshots and compare visual appearance
- **Functional Tests**: Test user interactions, API calls, and component behavior
- **Cross-browser**: Tests run on Chrome, Firefox, Safari, and mobile browsers
```bash
npm run test:clean
npm run test:e2e
npm run test:e2e:ui
npm run test:visual
npm run test:report
```
```
data-chatbot/
โโโ src/
โ โโโ lib/
โ โ โโโ components/
โ โ โโโ utils/
โ โ โโโ types.ts
โ โ โโโ index.ts
โ โโโ demo/
โ โ โโโ App.tsx
โ โ โโโ main.tsx
โ โโโ styles/
โโโ tests/
โโโ scripts/
โโโ dist/
```
```tsx
import { ChatAssistant } from 'data-platform-chatbot';
import 'data-platform-chatbot/dist/index.css';
<ChatAssistant />
```
```tsx
<ChatAssistant
config={{
theme: {
primary: '#10b981',
userMessageBg: '#d1fae5',
assistantMessageBg: '#ecfdf5'
}
}}
/>
```
```tsx
<ChatAssistant
config={{
theme: {
primary: 'oklch(42.4% 0.199 265.638)',
userMessageBg: '#eaeaf8',
assistantMessageBg: '#EFF3F5',
borderColor: '#c1c1cd',
textColor: '#222222'
}
}}
/>
```
```tsx
<ChatAssistant
config={{
position: 'bottom-left',
width: 400,
height: 500
}}
/>
```
```tsx
<ChatAssistant
config={{
endpoint: '/v1/chat/completions', // Use proxy endpoint
model: 'gpt-4',
headers: {
'Authorization': 'Bearer your-token',
'X-Custom-Header': 'value'
}
}}
/>
```
In development mode, use the live theme editor to create custom themes:
1. **Open Theme Editor**: Click the palette icon in the top-right corner
2. **Adjust Colors**: Use color pickers or enter hex values directly
3. **See Changes Live**: Watch the chat component update in real-time
4. **Export Theme**: Copy the generated theme configuration
5. **Use in Production**: Apply the exported theme to your component
```tsx
// Example exported theme from live editor
const customTheme = {
"primary": "#ff6b6b",
"background": "#ffffff",
"userMessageBg": "#ffe3e3",
"assistantMessageBg": "#f8f9fa",
"borderColor": "#e9ecef",
"textColor": "#212529",
"fabBg": "#ffffff",
"fabColor": "#ff6b6b"
};
<ChatAssistant config={{ theme: customTheme }} />
```
1. Fork the repository
2. Create a feature branch: `git checkout -b feature/new-feature`
3. Make your changes
4. Run tests: `npm run test:e2e`
5. Commit your changes: `git commit -am 'Add new feature'`
6. Push to the branch: `git push origin feature/new-feature`
7. Submit a pull request
- Follow the existing code style
- Add tests for new features
- Update documentation as needed
- Ensure all tests pass before submitting PR
- Use semantic commit messages
**Playwright tests failing:**
```bash
npx playwright install
npm update @playwright/test
```
**Build issues:**
```bash
rm -rf node_modules package-lock.json
npm install
```
**TypeScript errors:**
```bash
npx tsc --noEmit
```
MIT
For issues and questions:
- Create an issue in the repository
- Check existing documentation
- Review test files for usage examples