UNPKG

@ingridsandev/chatbot-widget

Version:

A framework-agnostic chatbot widget using Web Components

457 lines (354 loc) • 11.9 kB
# Chatbot Widget A framework-agnostic chatbot widget built with Web Components that seamlessly integrates with React, Angular, Vue, and vanilla JavaScript applications. ## Features - šŸš€ **Framework Agnostic**: Works with React, Angular, Vue, and vanilla JavaScript - šŸŽØ **Themeable**: Built-in light/dark themes with custom color support - šŸ“± **Responsive**: Mobile-first design with configurable positioning - šŸ¤– **Multi-Agent**: Support for switching between different AI agents - šŸ’¾ **Persistent**: Automatic chat history and preference storage - ♿ **Accessible**: Full ARIA support and keyboard navigation - šŸ”§ **Configurable**: Extensive API for customization - šŸ“¦ **Lightweight**: Zero dependencies, small bundle size ## Quick Start ### Installation ```bash npm install @your-org/chatbot-widget ``` ### Basic Usage #### Vanilla JavaScript/HTML ```html <!DOCTYPE html> <html> <head> <script type="module" src="path/to/chatbot-widget.js"></script> </head> <body> <chatbot-widget api-endpoint="https://api.example.com/chat" primary-color="#007bff" theme="auto"> </chatbot-widget> </body> </html> ``` #### React ```jsx import React, { useRef, useEffect } from 'react'; import 'chatbot-widget'; function App() { const chatbotRef = useRef(); useEffect(() => { const chatbot = chatbotRef.current; const handleMessage = (event) => { console.log('New message:', event.detail); }; chatbot.addEventListener('messageSend', handleMessage); return () => chatbot.removeEventListener('messageSend', handleMessage); }, []); return ( <div> <chatbot-widget ref={chatbotRef} agents={JSON.stringify([ { id: 'support', name: 'Support Agent', avatar: 'šŸŽ§' } ])} theme="light" position="bottom-right" /> </div> ); } ``` #### Angular ```typescript // app.module.ts import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; @NgModule({ declarations: [AppComponent], imports: [BrowserModule], schemas: [CUSTOM_ELEMENTS_SCHEMA], bootstrap: [AppComponent] }) export class AppModule { } // app.component.ts import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core'; import './chatbot-widget.js'; @Component({ selector: 'app-root', template: ` <chatbot-widget #chatbot api-endpoint="https://api.example.com/chat" theme="dark" (message-sent)="onMessageSent($event)"> </chatbot-widget> ` }) export class AppComponent implements AfterViewInit { @ViewChild('chatbot') chatbot!: ElementRef; ngAfterViewInit() { this.chatbot.nativeElement.addEventListener('message-sent', (event: any) => { console.log('Message sent:', event.detail); }); } onMessageSent(event: any) { console.log('Message sent:', event.detail); } } ``` ## Configuration ### Attributes | Attribute | Type | Default | Description | |-----------|------|---------|-------------| | `api-endpoint` | string | `''` | API endpoint for chat requests | | `theme` | string | `'auto'` | Theme: `'light'`, `'dark'`, `'auto'`, or `'custom'` | | `position` | string | `'bottom-right'` | Widget position: `'bottom-right'`, `'bottom-left'`, `'top-right'`, `'top-left'` | | `primary-color` | string | `'#007bff'` | Primary color for custom theme | | `secondary-color` | string | `'#6c757d'` | Secondary color for custom theme | | `max-height` | string | `'600px'` | Maximum height of chat interface | | `placeholder` | string | `'Type your message...'` | Input placeholder text | | `welcome-message` | string | `'Hello! How can I help you today?'` | Initial welcome message | | `agents` | string | `'[]'` | JSON string of available agents | | `default-agent` | string | `''` | Default selected agent ID | | `auto-open` | boolean | `false` | Whether to open chat automatically | | `persist-chat` | boolean | `true` | Whether to persist chat history | | `persist-preferences` | boolean | `true` | Whether to persist user preferences | ### JavaScript API ```javascript const chatbot = document.querySelector('chatbot-widget'); // Send a message programmatically chatbot.sendMessage('Hello from code!'); // Add a message to the chat chatbot.addMessage({ text: 'System message', sender: 'system', timestamp: Date.now() }); // Clear chat history chatbot.clearChat(); // Open/close the chat chatbot.open(); chatbot.close(); chatbot.toggle(); // Set theme chatbot.setTheme('dark'); // Get current state const isOpen = chatbot.isOpen; const messages = chatbot.getMessages(); const currentAgent = chatbot.getCurrentAgent(); // Set custom configuration chatbot.setConfig({ apiEndpoint: 'https://new-api.example.com/chat', primaryColor: '#ff6b6b', maxHeight: '500px' }); ``` ### Events Listen to these custom events to integrate with your application: ```javascript const chatbot = document.querySelector('chatbot-widget'); // User sent a message chatbot.addEventListener('messageSend', (event) => { console.log('Message:', event.detail.message); console.log('Agent:', event.detail.agent); }); // Received response from API chatbot.addEventListener('messageReceived', (event) => { console.log('Response:', event.detail.message); }); // Chat opened/closed chatbot.addEventListener('chatToggle', (event) => { console.log('Chat state changed:', event.detail.isOpen); }); // Agent changed chatbot.addEventListener('agentSwitch', (event) => { console.log('New agent:', event.detail.agent); }); // Error occurred chatbot.addEventListener('error', (event) => { console.error('Error:', event.detail.error); }); ``` ## Theming ### Built-in Themes - **Light**: Clean, bright theme suitable for most applications - **Dark**: Dark theme for modern applications - **Auto**: Automatically switches based on system preference ### Custom Themes Use the `custom` theme with your own colors: ```html <chatbot-widget theme="custom" primary-color="#ff6b6b" secondary-color="#4ecdc4"> </chatbot-widget> ``` ### CSS Custom Properties For advanced theming, override CSS custom properties: ```css chatbot-widget { --chatbot-primary-color: #your-color; --chatbot-secondary-color: #your-color; --chatbot-background-color: #your-color; --chatbot-text-color: #your-color; --chatbot-border-color: #your-color; --chatbot-shadow: your-shadow; --chatbot-border-radius: your-radius; --chatbot-font-family: your-font; } ``` ## Multi-Agent Support Configure multiple AI agents for different purposes: ```javascript const agents = [ { id: 'support', name: 'Support Agent', description: 'General customer support', avatar: 'šŸŽ§' }, { id: 'sales', name: 'Sales Assistant', description: 'Product information and sales', avatar: 'šŸ’¼' }, { id: 'technical', name: 'Technical Expert', description: 'Technical documentation and help', avatar: 'šŸ”§' } ]; chatbot.setAttribute('agents', JSON.stringify(agents)); chatbot.setAttribute('default-agent', 'support'); ``` ## API Integration The widget sends POST requests to your API endpoint with this format: ```json { "message": "User's message", "agent": "selected-agent-id", "history": [ { "text": "Previous message", "sender": "user", "timestamp": 1234567890 } ], "metadata": { "sessionId": "unique-session-id", "userId": "user-id-if-available" } } ``` Expected response format: ```json { "message": "Assistant's response", "success": true, "metadata": { "responseTime": 150, "model": "gpt-4" } } ``` ## Development ### Building from Source ```bash # Clone the repository git clone https://github.com/ingridsandev/chatbot-widget.git cd chatbot-widget # Install dependencies npm install # Build for production npm run build # Build for development (with source maps) npm run build:dev # Start development server npm run dev ``` ### Testing ```bash # Run all tests npm test # Run tests in watch mode npm run test:watch # Run tests with coverage npm run test:coverage ``` ### Demo Applications & Utility Scripts This repository includes comprehensive insurance application examples demonstrating the chatbot widget integration across multiple frameworks, along with utility scripts for easy management. #### šŸ›”ļø Insurance Apps Showcase Complete insurance applications built with different frameworks: - **šŸ…°ļø Angular Insurance App** - Enterprise-grade TypeScript implementation - **āš›ļø React Insurance App** - Modern React with hooks and functional components - **🟨 Vanilla JS Insurance App** - Framework-free implementation All apps feature the same insurance workflows (claims, products, dashboard) and multi-agent chatbot system. #### šŸš€ Quick Start Scripts Use the utility scripts in the `scripts/` directory to easily run the demo applications: ```bash # Start individual apps ./scripts/start-angular.sh # Angular app on http://localhost:4200/ ./scripts/start-react.sh # React app on http://localhost:3000/ ./scripts/start-vanilla.sh # Vanilla JS app on http://localhost:8080/ # Start all apps simultaneously (opens multiple terminals) ./scripts/start-all.sh # Install dependencies for all apps ./scripts/install-deps.sh # Build all apps for production ./scripts/build-all.sh ``` #### šŸŽØ Demo Showcase Page Open `examples/index.html` in your browser to see a beautiful showcase page with links to all demo applications and detailed feature comparisons. **Windows Users**: Use the `.bat` versions of the scripts: - `scripts/start-angular.bat` - `scripts/start-react.bat` - `scripts/start-vanilla.bat` See `scripts/README.md` for detailed documentation. ### Project Structure ``` src/ ā”œā”€ā”€ components/ # Web Components │ ā”œā”€ā”€ chatbot-widget.js # Main widget component │ ā”œā”€ā”€ chat-interface.js # Chat UI component │ └── agent-selector.js # Agent selection component ā”œā”€ā”€ styles/ # CSS styles │ ā”œā”€ā”€ chatbot.css # Main styles │ └── themes.css # Theme variations └── utils/ # Utility modules ā”œā”€ā”€ event-emitter.js # Event system └── storage.js # Storage utilities examples/ # Framework examples ā”œā”€ā”€ vanilla-example/ # Plain HTML/JS ā”œā”€ā”€ react-example/ # React integration └── angular-example/ # Angular integration tests/ # Test suites ā”œā”€ā”€ chatbot-widget.test.js # Unit tests └── integration.test.js # Integration tests ``` ## Browser Support - Chrome/Edge 63+ - Firefox 63+ - Safari 10.1+ - Mobile browsers with Web Components support For older browsers, include a Web Components polyfill: ```html <script src="https://unpkg.com/@webcomponents/webcomponentsjs@2/webcomponents-loader.js"></script> ``` ## Contributing 1. Fork the repository 2. Create a feature branch: `git checkout -b feature/new-feature` 3. Make your changes and add tests 4. Run tests: `npm test` 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 ## License MIT License - see [LICENSE](LICENSE) file for details. ## Support - šŸ“– [Documentation](https://github.com/ingridsandev/chatbot-widget/wiki) - šŸ› [Issue Tracker](https://github.com/ingridsandev/chatbot-widget/issues) - šŸ’¬ [Discussions](https://github.com/ingridsandev/chatbot-widget/discussions)