Chat Module
Relevant source files
The following files were used as context for generating this wiki page:The Chat Module provides a comprehensive, real-time messaging system for the ElmecV2 application, offering a user experience comparable to modern chat applications like WhatsApp. It is deeply integrated with Supabase for backend services, including database storage, real-time subscriptions, and presence tracking. The module is designed to be robust, supporting text, emojis, file attachments, and voice notes, along with features like message replies, edits, and deletions.
The architecture is centered around the React Context API, which encapsulates all state management, business logic, and communication with the backend. This design ensures a clean separation of concerns, making the UI components primarily responsible for rendering and user input, while the context handles the complex underlying operations. A critical dependency for full functionality is the correct database schema, as many features are directly tied to specific columns in the messages table.
Sources: REPORTE_CHAT_MODULE.md, contexts/ChatContext.tsx
Architecture
The module's architecture follows a standard React pattern, using a central context provider to manage state and logic, which is then consumed by various UI components.
contexts/ChatContext.tsx: The core of the module. It manages the state for chat rooms and messages, handles all interactions with the Supabase API, and sets up real-time subscriptions.app/(tabs)/chat/[roomId].tsx: The main chat room screen. It renders the list of messages for a specific room and provides the UI for sending new messages, including text, files, and other media.app/(tabs)/chat/index.tsx: The chat list screen. It displays all active conversations for the current user, showing message previews and unread counts.hooks/useChat.ts: A simple custom hook to provide easy access to theChatContext.
Sources: REPORTE_CHAT_MODULE.md:195-205, contexts/ChatContext.tsx
High-Level Data Flow
The following diagram illustrates the data flow between the UI, the Chat Context, and the Supabase backend.
State Management (ChatContext.tsx)
The ChatContext is the single source of truth for the chat module. It encapsulates all logic for fetching, sending, and updating chat data.
Key State Properties
| State | Type | Description |
|---|---|---|
chatRooms | ChatRoom[] | An array of all active chat rooms for the logged-in user. |
messages | { [roomId: string]: ChatMessage[] } | An object mapping room IDs to an array of messages for that room. |
typingUsers | { [roomId: string]: TypingUser[] } | An object mapping room IDs to users who are currently typing. |
onlineUsers | string[] | An array of user IDs who are currently online, tracked via Presence. |
loading | boolean | A flag indicating if initial chat data is being loaded. |
error | string | null | Stores any error messages that occur during operations. |
Sources: contexts/ChatContext.tsx:30-58
Core Functions
sendMessage(...): Sends a message, handling optimistic UI updates and communication with Supabase.createChatRoom(...): Creates a new chat room or finds an existing one between two participants.loadChatRooms(): Fetches the initial list of chat rooms for the user.setupRealtimeSubscription(roomId): Subscribes to database changes for a specific chat room.sendTypingIndicator(...): Tracks and sends "is typing" events using Supabase Presence.deleteMessage(...): Performs a soft delete on a message.editMessage(...): Updates the content of an existing message.
Sources: contexts/ChatContext.tsx:37-57
Message Sending Flow (Optimistic Update)
The sendMessage function provides a responsive user experience by using an optimistic update pattern. The message appears in the UI instantly while the actual database operation happens in the background.
This diagram shows how the UI is updated instantly before the database write is confirmed.
Sources: contexts/ChatContext.tsx:406-528
Real-time Functionality
The module relies heavily on Supabase Realtime to keep data synchronized across clients without manual polling.
Message and Room Subscriptions
The context subscribes to postgres_changes on the messages and chat_rooms tables. This allows the app to react instantly to INSERT and UPDATE events.
// Source: contexts/ChatContext.tsx:191-284
const channel = supabase
.channel(`chat_room_${roomId}`)
.on('postgres_changes', {
event: 'INSERT',
schema: 'public',
table: 'messages',
filter: `chat_room_id=eq.${roomId}`
}, async payload => {
// Logic to add new message to state
// and trigger a notification.
})
.on('postgres_changes', {
event: 'UPDATE',
schema: 'public',
table: 'messages',
filter: `chat_room_id=eq.${roomId}`
}, payload => {
// Logic to update an existing message (e.g., edit, read receipt).
})
.subscribe();
Sources: contexts/ChatContext.tsx:191-284, REPORTE_CHAT_MODULE.md:104-123
Presence and Typing Indicators
Supabase Presence is used to track online users and manage "typing..." indicators. The sendTypingIndicator function uses the channel.track() method to broadcast a user's typing status. Other clients in the same channel receive these events and update the UI accordingly.
Sources: contexts/ChatContext.tsx:534-552, REPORTE_CHAT_MODULE.md:125-138
Database Schema
The chat functionality is supported by two primary tables in the PostgreSQL database: chat_rooms and messages.
This ER diagram shows the relationships between users, chat rooms, and messages.
Sources: REPORTE_CHAT_MODULE.md:231-255, INSTRUCCIONES_CHAT_SQL.md:6-18
messages Table Columns
Many of the module's advanced features depend on specific columns in the messages table. The absence of these columns will block functionality.
| Column | Data Type | Description | Feature Enabled |
|---|---|---|---|
id | UUID | Primary key for the message. | Core |
chat_room_id | UUID | Foreign key to chat_rooms. | Core |
sender_id | UUID | Foreign key to users. | Core |
message | TEXT | The main content of the message. | Text Messages |
type | TEXT | The type of message (text, image, audio, file). | Multimedia |
file_url | TEXT | Public URL for any attached file. | Attachments |
is_deleted | BOOLEAN | Flag for soft-deleting messages. | Delete Message |
reply_to | UUID | FK to messages.id. Stores the ID of the message being replied to. | Reply to Message |
file_name | TEXT | The original name of an attached file. | File Metadata |
file_size | INTEGER | The size of an attached file in bytes. | File Metadata |
audio_duration | INTEGER | The duration of a voice note in seconds. | Voice Notes |
edited_at | TIMESTAMP | Timestamp indicating when the message was last edited. | Edit Message |
read_by | JSONB | A JSON object storing the IDs of users who have read the message. | Read Receipts |
Note: Columns in bold were identified as initially missing from the database schema, and their addition is required for full feature parity with the application code.
Sources: INSTRUCCIONES_CHAT_SQL.md:40-46, REPORTE_CHAT_MODULE.md:231-255
Required SQL Migration
To enable all chat features, the following SQL commands must be executed in the Supabase SQL Editor to add the missing columns to the messages table.
-- 1. Reply to messages
ALTER TABLE messages ADD COLUMN IF NOT EXISTS reply_to UUID REFERENCES messages(id);
-- 2. File metadata
ALTER TABLE messages ADD COLUMN IF NOT EXISTS file_name TEXT,
ADD COLUMN IF NOT EXISTS file_size INTEGER;
-- 3. Audio duration
ALTER TABLE messages ADD COLUMN IF NOT EXISTS audio_duration INTEGER;
-- 4. Edit tracking
ALTER TABLE messages ADD COLUMN IF NOT EXISTS edited_at TIMESTAMP;
-- 5. Read receipts
ALTER TABLE messages ADD COLUMN IF NOT EXISTS read_by JSONB DEFAULT '{}'::jsonb;
Sources: INSTRUCCIONES_CHAT_SQL.md:22-46
Testing
The module is accompanied by a comprehensive test suite located in scripts/test-chat-module.js. This script uses the Supabase JavaScript client in a Node.js environment to perform end-to-end tests on the backend functionality.
The test suite validates the following core features:
- CRUD operations for chat rooms and messages.
- Functionality for replying, editing, and soft-deleting messages.
- Sending messages of different types (text, image, file, audio).
- Real-time message reception via Supabase subscriptions.
- Presence tracking for typing indicators.
- File uploads to Supabase Storage.
Sources: scripts/test-chat-module.js, REPORTE_CHAT_MODULE.md:25-28
Conclusion
The ElmecV2 Chat Module is a well-architected, feature-rich system that provides a modern, real-time messaging experience. Its reliance on ChatContext for state management creates a clean and maintainable codebase. The integration with Supabase for real-time events and presence is robust and efficient. However, its full potential is only unlocked when the backend database schema is correctly configured with all necessary columns, highlighting the critical link between the application code and the database structure.