Chat UI
The <chat-ui> component is an interactive custom element that provides a complete chat interface with message display, input field, and programmable response handling. It features a modern design with customizable gradients, timestamps, smooth scrolling, and full programmatic control over message flow.
Installation
To use the <chat-ui> component, first ensure you have installed the essential-components package in your project.
npm install essential-components
Import
Import the component in your JavaScript or TypeScript file:
import "essential-components/src/chat-ui";
Usage
After importing, you can use the <chat-ui> component in your HTML or JSX. The component works out of the box with manual response control for maximum flexibility.
Basic Example
<chat-ui></chat-ui>
With Custom Title and Placeholder
<chat-ui title="Support Chat" placeholder="How can we help you today?">
</chat-ui>
With Custom Colors and Gradients
<chat-ui
title="AI Assistant"
primary-gradient="linear-gradient(135deg, #f093fb 0%, #f5576c 100%)"
primary-color="#f093fb"
bot-message-bg="#ffeaa7"
bot-message-color="#2d3436"
>
</chat-ui>
Live Example
Features
- 💬 Real-time Messaging: Interactive chat interface with instant message display
- 🎯 Manual Control: Full programmatic control over bot responses (no auto-responses)
- 📩 Message API: Get user messages and send bot responses programmatically
- 🎨 Customizable Colors: Fully customizable gradients and color schemes
- 📞 Event Handling: Callbacks and events for user message processing
- ⏰ Timestamps: Each message includes a timestamp showing when it was sent
- 📱 Modern Design: Beautiful customizable gradient themes with rounded corners and shadows
- 🔄 Smooth Scrolling: Auto-scrolls to latest messages
- ⌨️ Keyboard Support: Send messages with Enter key
- 📱 Responsive Layout: Adapts to different container sizes
- 🎨 Message Types: Distinct styling for user and bot messages
- 🧹 Message Management: Clear messages and retrieve message history
Attributes
| Attribute | Type | Default | Description |
|---|---|---|---|
title | String | Chat | The title displayed in the chat header |
placeholder | String | Type your message... | Placeholder text for the input field |
primary-gradient | String | linear-gradient(135deg, #667eea 0%, #764ba2 100%) | Gradient for header, send button, user messages |
primary-color | String | #667eea | Primary color for input focus border |
bot-message-bg | String | #f1f3f4 | Background color for bot messages |
bot-message-color | String | #333 | Text color for bot messages |
Programmatic API
Getting Messages
const chatUI = document.querySelector("chat-ui");
const lastMessage = chatUI.getLastUserMessage();
console.log(lastMessage?.text);
const userMessages = chatUI.getUserMessages();
const allMessages = chatUI.getAllMessages();
Sending Messages
// Send a bot response manually
chatUI.sendBotResponse("Hello! How can I help you?");
// Add a user message programmatically (optional)
chatUI.addMessage("User message", "user");
Message Management
chatUI.clearMessages();
Event Handling
Method 1: Using Callbacks
chatUI.setUserMessageCallback((message, chatInstance) => {
console.log("User said:", message.text);
const response = analyzeMessage(message.text);
chatInstance.sendBotResponse(response);
});
Method 2: Using Event Listeners
chatUI.addEventListener("user-message", (event) => {
const message = event.detail.message;
const chatInstance = event.detail.chatUI;
console.log("User message:", message.text);
chatInstance.sendBotResponse("Thanks for your message!");
});
Message Object Structure
Each message object contains:
{
id: 1640995200000, // Timestamp-based unique ID
text: "Hello world", // Message content
type: "user", // "user" or "bot"
timestamp: Date // Date object
}
Message Types
The component supports two types of messages:
User Messages
- Aligned to the right
- Uses
primary-gradientbackground - White text
- Timestamp aligned right
Bot Messages
- Aligned to the left
- Uses
bot-message-bgbackground - Uses
bot-message-colortext - Timestamp aligned left
Styling and Customization
Built-in Color Schemes
The component supports complete visual customization through attributes:
<!-- Blue Purple (Default) -->
<chat-ui
primary-gradient="linear-gradient(135deg, #667eea 0%, #764ba2 100%)"
></chat-ui>
Design Elements
- Custom Gradients: Any CSS gradient for headers and user messages
- Flexible Colors: Separate controls for bot message styling
- Card Design: Rounded corners with subtle shadows
- Typography: System font stack for optimal readability
- Spacing: Consistent padding and margins throughout
Layout
- Fixed Height: 500px total height
- Flexible Width: Max-width of 400px, responsive to container
- Scrollable Messages: 340px message area with custom scrollbar
- Fixed Input: Always visible at bottom
Advanced Usage Examples
Simple Bot with Keyword Responses
const chatUI = document.querySelector("chat-ui");
chatUI.setUserMessageCallback((message, chatInstance) => {
const text = message.text.toLowerCase();
let response = "";
if (text.includes("hello")) {
response = "Hello! Nice to meet you! 👋";
} else if (text.includes("help")) {
response = "I'm here to help! What do you need?";
} else if (text.includes("time")) {
response = `The current time is ${new Date().toLocaleTimeString()}.`;
} else {
response = "That's interesting! Tell me more.";
}
setTimeout(() => {
chatInstance.sendBotResponse(response);
}, 500);
});
Sentiment Analysis Bot
chatUI.setUserMessageCallback((message, chatInstance) => {
const sentiment = analyzeSentiment(message.text);
const response = `I detect a ${sentiment} sentiment in your message. How can I help?`;
setTimeout(() => {
chatInstance.sendBotResponse(response);
}, 600);
});
function analyzeSentiment(text) {
const positiveWords = ["good", "great", "awesome", "love", "happy"];
const negativeWords = ["bad", "terrible", "hate", "sad", "angry"];
const lowerText = text.toLowerCase();
const hasPositive = positiveWords.some((word) => lowerText.includes(word));
const hasNegative = negativeWords.some((word) => lowerText.includes(word));
if (hasPositive && !hasNegative) return "positive";
if (hasNegative && !hasPositive) return "negative";
return "neutral";
}
Integration with External APIs
chatUI.setUserMessageCallback(async (message, chatInstance) => {
const typingMessage = chatInstance.sendBotResponse("🤔 Thinking...");
try {
// Call your API
const response = await fetch("/api/chat", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ message: message.text }),
});
const data = await response.json();
chatInstance.clearMessages(); // Remove "Thinking..." message
chatInstance.sendBotResponse(data.reply);
} catch (error) {
chatInstance.sendBotResponse(
"Sorry, I'm having trouble connecting right now."
);
}
});
Behavior
Message Flow
- User Input: Type message and press Enter or click Send
- Message Display: User message appears on the right with timestamp
- Event Trigger:
user-messageevent fires and callback is called - Manual Response: Your code decides how to respond
- Auto Scroll: Chat automatically scrolls to show latest messages
Input Handling
- Enter Key: Sends the message when pressed
- Send Button: Click to send message
- Empty Messages: Prevents sending empty or whitespace-only messages
- Input Clearing: Input field clears after sending
No Auto-Responses
Unlike basic chat components, this component does not automatically generate responses. This gives you complete control over the conversation flow and allows for:
- Custom AI integration
- API-based responses
- Complex conversation logic
- Manual moderation
- Real-time human responses
Browser Support
This component works in all modern browsers that support:
Accessibility
The component includes several accessibility features:
- Semantic HTML: Uses proper input and button elements
- Keyboard Navigation: Full keyboard support for interaction
- Focus Management: Proper focus handling for input field
- Screen Reader Support: Meaningful text content and structure
- Color Contrast: High contrast ratios for readability
- Custom Events: Proper event bubbling for assistive technologies
Use Cases
Perfect for:
- AI Chatbots: Integrate with OpenAI, Claude, or custom AI services
- Customer Support: Real-time human or automated support
- Interactive Applications: Conversational interfaces for apps
- Educational Tools: Language learning, tutorials, Q&A systems
- Portfolio Projects: Demonstrate advanced web component skills
- API Demonstrations: Show AI/ML service integrations
- Prototype Development: Quick chat UI for testing concepts
Performance
The component is optimized for performance:
- Lightweight: Minimal JavaScript footprint
- Efficient Rendering: Only re-renders when messages change
- Memory Management: Proper event listener cleanup
- Smooth Animations: Hardware-accelerated transitions
- Manual Control: No unnecessary auto-response timers