Chat Module (linuxfront-v2-logistics/js/chat.js) 📡
This module implements a real-time chat widget for customers and agents. It manages configuration, WebSocket connections, HTTP fallbacks, UI interactions, and stores session data locally. It leverages toastr for notifications and DOMPurify for message sanitization.
Configuration ⚙️
Defines global settings for notifications and server endpoints. Injected PHP variables provide user and customer context.
// Toastr notification options
toastr.options = {
closeButton: true,
progressBar: true,
positionClass: 'toast-top-right',
timeOut: 5000
};
// Core config object
var config = {
apiUrl: 'https://trynew.techlogistics.com:2053',
wsUrl: 'wss://trynew.techlogistics.com:2053',
userId: <?php echo json_encode($user_id); ?>,
customerEmail: <?php echo json_encode($customer_email); ?>,
customerId: <?php echo json_encode($customer_id); ?>,
locationCode: <?php echo json_encode($company_code); ?>,
defaultTraining: 'Intro'
};
console.log(config);
- apiUrl/wsUrl: Base URLs for REST and WebSocket.
- userId, customerEmail, customerId, locationCode: Injected from server.
- defaultTraining: Initial chat “training” context.
UI Elements 🎨
All interactive elements are looked up by ID and stored in this.elements.
| Element | ID | Purpose |
|---|---|---|
| Chat container | chatContainer | Wraps entire chat widget |
| Messages panel | chatMessages | Displays message bubbles |
| Training label | chatTraining | Shows current training context |
| Typing indicator | typingIndicator | Shows “agent/bot is typing” animation |
| Text input | messageInput | User’s message input |
| Send button | sendButton | Triggers message send |
| File input (hidden) | fileInput | Selects file to upload |
| File button | fileButton | Opens file picker |
| Assistance button | assistanceButton | Requests human assistance |
| Chat icon | chatIcon | Opens chat widget |
| Connection status | connectionStatus | Displays WS status |
| Upload progress label | uploadProgress | Shows file upload status |
| Close chat button | closeChat | Hides chat widget |
| Retry button | retryButton | Attempts WS reconnection |
ChatManager Class 🚀
ChatManager orchestrates the chat lifecycle:
- Loads/saves setup from
localStorage - Manages WebSocket connection with auto-reconnect
- Handles HTTP fallbacks for messages & uploads
- Renders messages and file links
- Attaches UI event listeners
function ChatManager() {
this.setup = this.loadSetup();
this.ws = null;
this.displayedMessages = new Set();
this.lastMessageId = 0;
this.reconnectAttempts = 0;
this.maxReconnectAttempts = 5;
this.baseReconnectDelay = 1000;
this.isInitialized = false;
this.elements = { /* ...UI elements... */ };
this.init();
}
Key Methods
-
loadSetup()
Loads chat session data fromlocalStorageor falls back to defaults. -
saveSetup()
Persiststhis.setupback tolocalStorage. -
getFileIcon(ext) 📁
Returns an icon URL for a given file extension. -
connectWebSocket() 🔄
Establishes the WebSocket, handles:onopen: resets retries, updates status, starts heartbeatonmessage: processesmessage,typing,processing,systemeventsonclose: clears heartbeat, updates status, shows retry, triggers exponential backoffonerror: logs errors
-
displayMessage(data) 📝
Renders text or file messages into the chat panel, sanitizes content with DOMPurify, updates scroll. -
sendMessage(message, sender, needsAssistance, originalName)
Sends a chat message viaPOST /api/chat. Attaches metadata: user, chatId, URL, training, customer info. -
uploadFile(file) 📤
Uploads a file viaPOST /api/upload, then sends a “File: …” chat message. -
fetchMessages()
Retrieves missed messages viaGET /api/messages?chatId&lastId. -
initializeChat()
Bootstraps a session by fetching existing chats viaGET /api/chats?userId. Starts a new chat if none exist. -
retryFetch(url, options, retries, delay)
Generic fetch wrapper with retry/backoff logic. -
debounce(func, wait)
Returns a debounced version offunc. -
init()
- Clears stale data when
userIdchanges - Configures toastr
- Binds UI events: send, enter key, typing indicator, file upload, assistance, open/close chat, retry
- Clears stale data when
document.addEventListener('DOMContentLoaded', function() {
new ChatManager();
});
API Endpoints 🛠️
{
"title": "Get User Chats",
"description": "List existing chat sessions for a user.",
"method": "GET",
"baseUrl": "https://trynew.techlogistics.com:2053",
"endpoint": "/api/chats",
"headers": [
{ "key": "Content-Type", "value": "application/json", "required": false }
],
"queryParams": [
{ "key": "userId", "value": "User’s unique ID", "required": true }
],
"pathParams": [],
"bodyType": "none",
"requestBody": "",
"formData": [],
"responses": {
"200": {
"description": "Array of chat objects",
"body": "[{ \"id\": \"123\", \"user_id\": \"u1\", \"created_at\": \"…\" }]"
},
"4xx": {
"description": "Client error",
"body": "{ \"error\": \"Invalid userId\" }"
},
"5xx": {
"description": "Server error",
"body": "{ \"error\": \"Internal error\" }"
}
}
}
{
"title": "Start or Send Chat Message",
"description": "Creates or appends a message to a chat session.",
"method": "POST",
"baseUrl": "https://trynew.techlogistics.com:2053",
"endpoint": "/api/chat",
"headers": [
{ "key": "Content-Type", "value": "application/json", "required": true }
],
"queryParams": [],
"pathParams": [],
"bodyType": "json",
"requestBody": "{\n \"message\":\"Hello\",\n \"userId\":\"u1\",\n \"chatId\":\"123\",\n \"sender\":\"user\",\n \"needsAssistance\":false,\n \"page_url\":\"https://…\",\n \"training\":\"Intro\",\n \"customer_id\":\"c1\",\n \"location_code\":\"LAX\",\n \"customer_email\":\"[email protected]\"\n}",
"formData": [],
"responses": {
"200": {
"description": "Returns chatId if newly created",
"body": "{ \"chatId\": \"123\" }"
},
"4xx": {
"description": "Validation error",
"body": "{ \"error\": \"Missing fields\" }"
},
"5xx": {
"description": "Server error",
"body": "{ \"error\": \"Internal error\" }"
}
}
}
{
"title": "Fetch Chat Messages",
"description": "Retrieve messages since last ID for a chat.",
"method": "GET",
"baseUrl": "https://trynew.techlogistics.com:2053",
"endpoint": "/api/messages",
"headers": [
{ "key": "Content-Type", "value": "application/json", "required": false }
],
"queryParams": [
{ "key": "chatId", "value": "Chat session ID", "required": true },
{ "key": "lastId", "value": "Last message ID received", "required": true }
],
"pathParams": [],
"bodyType": "none",
"requestBody": "",
"formData": [],
"responses": {
"200": {
"description": "Array of message objects",
"body": "[{ \"id\":1, \"sender\":\"bot\", \"message\":\"Hi\",\"created_at\":\"…\" }]"
},
"4xx": {
"description": "Client error",
"body": "{ \"error\": \"Invalid chatId\" }"
},
"5xx": {
"description": "Server error",
"body": "{ \"error\": \"Internal error\" }"
}
}
}
{
"title": "Upload File",
"description": "Uploads a file and returns its URL.",
"method": "POST",
"baseUrl": "https://trynew.techlogistics.com:2053",
"endpoint": "/api/upload",
"headers": [],
"queryParams": [],
"pathParams": [],
"bodyType": "form",
"requestBody": "",
"formData": [
{ "key": "file", "value": "Binary file data", "required": true }
],
"responses": {
"200": {
"description": "Returns filePath and originalName",
"body": "{ \"filePath\": \"/uploads/doc.pdf\", \"originalName\": \"doc.pdf\" }"
},
"4xx": {
"description": "Invalid file",
"body": "{ \"error\": \"Unsupported format\" }"
},
"5xx": {
"description": "Server error",
"body": "{ \"error\": \"Upload failed\" }"
}
}
}
WebSocket Workflow 🔄
sequenceDiagram
participant User
participant Frontend
participant WS
User->>Frontend: Click chat icon
Frontend->>WS: CONNECT wss://…?userId=…
WS-->>Frontend: OPEN event
Frontend->>Frontend: fetchMessages() if chatId exists
loop Heartbeat every 80s
Frontend->>WS: { type: 'heartbeat' }
end
User->>Frontend: Type & send message
Frontend->>WS: { type: 'message', ... }
WS-->>Frontend: { type: 'message', message: '…' }
Frontend->>UI: displayMessage()
WS-->>Frontend: CLOSE / ERROR
Frontend->>Frontend: retry with backoff
File Icon Mapping 📁
Local Storage Usage 💾
- lastUserId: Tracks last loaded
userId. - chatSetup: Stores
{ userId, customerEmail, customerId, locationCode, chatId, training }. - Clears outdated setup when user changes.
Security & Sanitization 🔒
- DOMPurify.sanitize() cleans all incoming/outgoing message HTML.
- toastr displays user-friendly error and progress notifications.
This comprehensive module abstracts real-time chat operations, gracefully degrades to HTTP when needed, and ensures a smooth UX with robust error handling and state persistence.