Documentation

Chat Box Application

Chat Box Application

Real-time chat interface with contact list, message history, and modern UI design.

Route: /admin/apps/chat

Overview

The Chat Box application provides a complete messaging interface with real-time capabilities, contact management, and group chat functionality. It features a modern design with smooth animations and responsive layout.

Features

Core Chat Features

  • Real-time Messaging - Instant message delivery and updates
  • Contact List - Manage and organize contacts
  • Message History - Persistent message storage and retrieval
  • Online Status - Show user online/offline status
  • Message Types - Text, emoji, file attachments, images
  • Group Chats - Create and manage group conversations
  • Message Search - Search through conversation history
  • Typing Indicators - Show when someone is typing
  • Message Reactions - React to messages with emojis
  • Message Threading - Reply to specific messages

UI/UX Features

  • Responsive Design - Works on all devices
  • Dark/Light Mode - Automatic theme switching
  • Smooth Animations - Fluid transitions and interactions
  • Modern Interface - Clean, professional design
  • Accessibility - WCAG compliant with proper ARIA labels
  • Touch Support - Optimized for touch devices

Interface Layout

Chat Sidebar

The left sidebar contains:

  • Search Bar - Search contacts and conversations
  • Contact List - Scrollable list of contacts with avatars
  • Online Status - Visual indicators for online/offline status
  • Unread Counts - Badge showing unread message counts
  • Group Chats - Access to group conversations

Chat Area

The main content area shows:

  • Chat Header - Contact info, online status, call/video buttons
  • Message List - Scrollable conversation history
  • Message Input - Text input with emoji picker and file upload
  • Message Actions - Reply, forward, delete, react options

Message Types

Different message types are supported:

  • Text Messages - Plain text with formatting
  • Emoji Messages - Emoji reactions and standalone emojis
  • File Attachments - Images, documents, videos
  • System Messages - Join/leave notifications, status updates
  • Code Messages - Syntax highlighted code snippets

Contact Management

Contact List Features

  • Avatar Display - User avatars with fallback initials
  • Status Indicators - Online, offline, away, busy status
  • Last Message Preview - Show last message in conversation
  • Timestamp - When the last message was sent
  • Unread Count - Number of unread messages
  • Search & Filter - Find contacts quickly

Contact Actions

  • Start Conversation - Click to open chat
  • View Profile - Access contact information
  • Block/Unblock - Manage contact permissions
  • Delete Contact - Remove from contact list
  • Mute Notifications - Silence specific conversations

Message Features

Message Composition

  • Rich Text Input - Format text with bold, italic, etc.
  • Emoji Picker - Easy access to emoji library
  • File Upload - Drag and drop file attachments
  • Voice Messages - Record and send voice notes
  • Message Drafts - Auto-save draft messages
  • Send Options - Send now, schedule, or save as draft

Message Actions

  • Reply - Reply to specific messages
  • Forward - Forward messages to other contacts
  • Copy - Copy message text to clipboard
  • Delete - Delete messages (for self or all)
  • React - Add emoji reactions to messages
  • Edit - Edit sent messages (if enabled)

Message History

  • Infinite Scroll - Load older messages as needed
  • Search Messages - Find specific messages in conversation
  • Message Threading - Follow reply chains
  • Export Chat - Download conversation history
  • Message Status - Sent, delivered, read indicators

Group Chat Features

Group Management

  • Create Groups - Start new group conversations
  • Add Members - Invite contacts to groups
  • Remove Members - Remove users from groups
  • Group Settings - Manage group name, description, avatar
  • Admin Controls - Designate group administrators
  • Leave Group - Exit group conversations

Group Features

  • Group Info - View member list and group details
  • Group Notifications - Manage notification settings
  • Group Search - Search within group messages
  • Group Media - Shared files and media gallery
  • Group Events - Create and manage group events

Integration Examples

Backend Integration

// Chat Controller
class ChatController extends Controller
{
    public function index()
    {
        $conversations = Conversation::with(['participants', 'lastMessage'])
            ->whereHas('participants', function($query) {
                $query->where('user_id', auth()->id());
            })
            ->latest('updated_at')
            ->get();

        return view('admin.apps.chat', compact('conversations'));
    }

    public function getMessages($conversationId)
    {
        $messages = Message::with(['sender', 'attachments'])
            ->where('conversation_id', $conversationId)
            ->latest()
            ->paginate(50);

        return response()->json($messages);
    }

    public function sendMessage(Request $request)
    {
        $request->validate([
            'conversation_id' => 'required|exists:conversations,id',
            'content' => 'required|string',
            'type' => 'in:text,image,file,emoji'
        ]);

        $message = Message::create([
            'conversation_id' => $request->conversation_id,
            'sender_id' => auth()->id(),
            'content' => $request->content,
            'type' => $request->type
        ]);

        // Broadcast to other participants
        broadcast(new MessageSent($message));

        return response()->json($message);
    }
}

Livewire Integration

// Chat Livewire Component
class ChatBox extends Component
{
    public $conversations = [];
    public $activeConversation = null;
    public $messages = [];
    public $newMessage = '';
    public $search = '';

    public function mount()
    {
        $this->loadConversations();
    }

    public function loadConversations()
    {
        $this->conversations = Conversation::with(['participants', 'lastMessage'])
            ->whereHas('participants', function($query) {
                $query->where('user_id', auth()->id());
            })
            ->latest('updated_at')
            ->get();
    }

    public function selectConversation($conversationId)
    {
        $this->activeConversation = $conversationId;
        $this->loadMessages();
    }

    public function loadMessages()
    {
        if ($this->activeConversation) {
            $this->messages = Message::with(['sender', 'attachments'])
                ->where('conversation_id', $this->activeConversation)
                ->latest()
                ->take(50)
                ->get()
                ->reverse()
                ->values();
        }
    }

    public function sendMessage()
    {
        if (empty($this->newMessage)) return;

        $message = Message::create([
            'conversation_id' => $this->activeConversation,
            'sender_id' => auth()->id(),
            'content' => $this->newMessage,
            'type' => 'text'
        ]);

        $this->newMessage = '';
        $this->loadMessages();

        // Broadcast to other participants
        broadcast(new MessageSent($message));
    }

    public function render()
    {
        return view('livewire.chat-box');
    }
}

Real-time Integration with Laravel Echo

// Message Broadcasting
class MessageSent implements ShouldBroadcast
{
    public $message;

    public function __construct(Message $message)
    {
        $this->message = $message;
    }

    public function broadcastOn()
    {
        return new PrivateChannel('conversation.' . $this->message->conversation_id);
    }

    public function broadcastWith()
    {
        return [
            'id' => $this->message->id,
            'content' => $this->message->content,
            'sender' => $this->message->sender->name,
            'created_at' => $this->message->created_at->toISOString()
        ];
    }
}
// Frontend Real-time Integration
import Echo from 'laravel-echo';
import Pusher from 'pusher-js';

window.Pusher = Pusher;

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: process.env.MIX_PUSHER_APP_KEY,
    cluster: process.env.MIX_PUSHER_APP_CLUSTER,
    forceTLS: true
});

// Listen for new messages
window.Echo.private(`conversation.${conversationId}`)
    .listen('MessageSent', (e) => {
        addMessageToChat(e.message);
    });

// Listen for typing indicators
window.Echo.private(`conversation.${conversationId}`)
    .listen('UserTyping', (e) => {
        showTypingIndicator(e.user);
    });

Customization

Styling

// Custom chat styles
.chat-container {
    .chat-sidebar {
        background: var(--bg-sidebar);
        border-right: 1px solid var(--border-color);

        .contact-item {
            &:hover {
                background: var(--bg-hover);
            }

            &.active {
                background: var(--primary-color);
                color: white;
            }
        }
    }

    .chat-area {
        .message-list {
            .message {
                &.sent {
                    background: var(--primary-color);
                    color: white;
                    margin-left: auto;
                }

                &.received {
                    background: var(--bg-card);
                    color: var(--text-color);
                }
            }
        }

        .message-input {
            border-top: 1px solid var(--border-color);

            .input-group {
                .form-control {
                    border: none;
                    background: transparent;

                    &:focus {
                        box-shadow: none;
                    }
                }
            }
        }
    }
}

JavaScript Functionality

// Chat functionality
class ChatBox {
    constructor() {
        this.activeConversation = null;
        this.messages = [];
        this.initEventListeners();
        this.initRealTime();
    }

    initEventListeners() {
        // Send message on Enter key
        document.getElementById('messageInput').addEventListener('keypress', (e) => {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                this.sendMessage();
            }
        });

        // Send button click
        document.getElementById('sendBtn').addEventListener('click', () => {
            this.sendMessage();
        });

        // Contact selection
        document.querySelectorAll('.contact-item').forEach(item => {
            item.addEventListener('click', (e) => {
                const conversationId = e.currentTarget.dataset.conversationId;
                this.selectConversation(conversationId);
            });
        });
    }

    sendMessage() {
        const input = document.getElementById('messageInput');
        const content = input.value.trim();

        if (!content || !this.activeConversation) return;

        // Add message to UI immediately
        this.addMessageToUI({
            content: content,
            sender: 'me',
            timestamp: new Date().toLocaleTimeString()
        });

        // Send to server
        fetch('/api/chat/send', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
            },
            body: JSON.stringify({
                conversation_id: this.activeConversation,
                content: content
            })
        });

        input.value = '';
    }

    addMessageToUI(message) {
        const messageList = document.getElementById('messageList');
        const messageElement = this.createMessageElement(message);
        messageList.appendChild(messageElement);
        messageList.scrollTop = messageList.scrollHeight;
    }

    createMessageElement(message) {
        const div = document.createElement('div');
        div.className = `message ${message.sender === 'me' ? 'sent' : 'received'}`;
        div.innerHTML = `
            <div class="message-content">
                <p>${message.content}</p>
                <small class="message-time">${message.timestamp}</small>
            </div>
        `;
        return div;
    }
}

Best Practices

  1. Performance: Implement message pagination and lazy loading
  2. Security: Validate all messages and sanitize content
  3. UX: Provide clear feedback for all user actions
  4. Mobile: Ensure touch-friendly interface on mobile devices
  5. Accessibility: Use proper ARIA labels and keyboard navigation
  6. Real-time: Handle connection issues and provide fallbacks
  7. Privacy: Implement proper message encryption for sensitive data

Production Deployment

The Chat Box application is ready for production use in both static HTML and Laravel Livewire editions. For production deployment:

  1. Real-time Setup - Configure Pusher, Redis, or WebSocket server
  2. Database Setup - Create necessary tables for messages and conversations
  3. File Storage - Configure attachment storage
  4. Security - Implement proper authentication and authorization
  5. Performance - Set up caching and message archiving
  6. Monitoring - Monitor message delivery and system performance