initial
This commit is contained in:
commit
584abdb00e
13 changed files with 2815 additions and 0 deletions
2
.gitignore
vendored
Normal file
2
.gitignore
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
.env
|
||||
node_modules
|
||||
21
index.js
Normal file
21
index.js
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
import express from "express";
|
||||
import path from "path";
|
||||
import { fileURLToPath } from "url";
|
||||
|
||||
const app = express();
|
||||
const PORT = process.env.PORT || 3100;
|
||||
|
||||
// Resolve __dirname in ES modules
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
|
||||
// Serve static assets from the public folder
|
||||
app.use(express.static(path.join(__dirname, "public")));
|
||||
|
||||
// Start static file server
|
||||
app.listen(PORT, () => {
|
||||
console.log(`==================================================`);
|
||||
console.log(` Pandora Chat Static Server is running!`);
|
||||
console.log(` URL: http://localhost:${PORT}`);
|
||||
console.log(`==================================================`);
|
||||
});
|
||||
1036
package-lock.json
generated
Normal file
1036
package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load diff
19
package.json
Normal file
19
package.json
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
{
|
||||
"name": "pandora",
|
||||
"version": "1.0.0",
|
||||
"type": "module",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"start": "node index.js",
|
||||
"test": "echo \"Error: no test specified\" && exit 1"
|
||||
},
|
||||
"keywords": [],
|
||||
"author": "",
|
||||
"license": "ISC",
|
||||
"description": "",
|
||||
"dependencies": {
|
||||
"axios": "^1.18.1",
|
||||
"dotenv": "^17.4.2",
|
||||
"express": "^5.2.1"
|
||||
}
|
||||
}
|
||||
263
public/app.js
Normal file
263
public/app.js
Normal file
|
|
@ -0,0 +1,263 @@
|
|||
import { config } from "./config.js";
|
||||
import { waha } from "./waha.js";
|
||||
import { ui, elements } from "./ui.js";
|
||||
import { websocket } from "./websocket.js";
|
||||
import { compensateMessageOrdering, formatTime } from "./utils.js";
|
||||
|
||||
let chatsState = [];
|
||||
let activeChatState = null;
|
||||
|
||||
// Initialize app when DOM is ready
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
setupEventListeners();
|
||||
fetchChats();
|
||||
checkWahaStatus();
|
||||
initWebSocket();
|
||||
});
|
||||
|
||||
function setupEventListeners() {
|
||||
elements.refreshChatsBtn.addEventListener('click', () => {
|
||||
elements.refreshChatsBtn.classList.add('spinning');
|
||||
fetchChats().finally(() => {
|
||||
setTimeout(() => {
|
||||
elements.refreshChatsBtn.classList.remove('spinning');
|
||||
}, 600);
|
||||
});
|
||||
});
|
||||
|
||||
elements.chatSearch.addEventListener('input', (e) => {
|
||||
const query = e.target.value.toLowerCase();
|
||||
const filtered = chatsState.filter(chat =>
|
||||
chat.name.toLowerCase().includes(query)
|
||||
);
|
||||
ui.renderChatList(filtered, activeChatState, selectChat);
|
||||
});
|
||||
|
||||
elements.messageForm.addEventListener('submit', (e) => {
|
||||
e.preventDefault();
|
||||
sendMessage();
|
||||
});
|
||||
|
||||
elements.backToSidebarBtn.addEventListener('click', () => {
|
||||
elements.sidebar.classList.remove('hidden');
|
||||
elements.activeChatContainer.classList.add('hidden');
|
||||
});
|
||||
|
||||
elements.settingsIconBtn.addEventListener('click', openSettings);
|
||||
elements.closeSettingsBtn.addEventListener('click', () => ui.toggleModal(false));
|
||||
elements.cancelSettingsBtn.addEventListener('click', () => ui.toggleModal(false));
|
||||
elements.saveSettingsBtn.addEventListener('click', saveSettings);
|
||||
}
|
||||
|
||||
function initWebSocket() {
|
||||
websocket.connect((data) => {
|
||||
console.log('[WS] Received event:', data.event, data);
|
||||
const ev = data.event;
|
||||
if (ev === 'message' || ev === 'message.any' || ev === 'message.ack') {
|
||||
handleIncomingMessage(data.payload);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function normalizeChatId(raw) {
|
||||
if (!raw) return null;
|
||||
if (typeof raw === 'object') {
|
||||
return raw._serialized || raw.user || JSON.stringify(raw);
|
||||
}
|
||||
return raw;
|
||||
}
|
||||
|
||||
function handleIncomingMessage(msg) {
|
||||
if (!msg) return;
|
||||
|
||||
console.log('[WS] handleIncomingMessage payload:', msg);
|
||||
|
||||
const rawChatId = msg.chatId || msg.from || (msg.chat && msg.chat.id);
|
||||
const msgChatId = normalizeChatId(rawChatId);
|
||||
if (!msgChatId) {
|
||||
console.warn('[WS] Could not resolve chatId from payload:', msg);
|
||||
return;
|
||||
}
|
||||
|
||||
console.log('[WS] Resolved msgChatId:', msgChatId, '| activeChatState:', activeChatState?.id);
|
||||
|
||||
if (activeChatState && activeChatState.id === msgChatId) {
|
||||
const msgId = normalizeChatId(msg.id) || msg.id;
|
||||
const exists = document.getElementById(msgId);
|
||||
if (!exists) {
|
||||
ui.appendSingleMessage({ ...msg, chatId: msgChatId }, activeChatState.name);
|
||||
ui.scrollToBottom();
|
||||
}
|
||||
}
|
||||
|
||||
const chatIndex = chatsState.findIndex(c => c.id === msgChatId);
|
||||
if (chatIndex !== -1) {
|
||||
const chat = chatsState[chatIndex];
|
||||
chat.lastMessage = msg.body || msg.text || 'Media message';
|
||||
chat.timestamp = msg.timestamp ? (msg.timestamp * 1000) : Date.now();
|
||||
|
||||
if (!msg.fromMe && (!activeChatState || activeChatState.id !== msgChatId)) {
|
||||
chat.unreadCount = (chat.unreadCount || 0) + 1;
|
||||
}
|
||||
|
||||
chatsState.sort((a, b) => {
|
||||
const tA = new Date(a.timestamp).getTime();
|
||||
const tB = new Date(b.timestamp).getTime();
|
||||
return tB - tA;
|
||||
});
|
||||
|
||||
ui.renderChatList(chatsState, activeChatState, selectChat);
|
||||
} else {
|
||||
fetchChats();
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchChats() {
|
||||
const userInfo = await waha.getMyInfo();
|
||||
elements.loggedUserName.textContent = userInfo.pushName;
|
||||
elements.userIcon.innerText = userInfo.pushName[0];
|
||||
elements.chatsLoader.classList.remove('hidden');
|
||||
try {
|
||||
chatsState = await waha.getChats();
|
||||
ui.renderChatList(chatsState, activeChatState, selectChat);
|
||||
} catch (error) {
|
||||
console.error('Failed to load chats:', error);
|
||||
elements.chatList.innerHTML = `
|
||||
<li class="loading-chats" style="color: #f87171; text-align: center; padding: 20px;">
|
||||
<p>Connection to WAHA failed.</p>
|
||||
<p style="font-size: 0.75rem; color: var(--text-muted); margin-top: 8px;">
|
||||
Ensure WAHA server is running and CORS is enabled, or click Settings to configure.
|
||||
</p>
|
||||
</li>
|
||||
`;
|
||||
} finally {
|
||||
elements.chatsLoader.classList.add('hidden');
|
||||
}
|
||||
}
|
||||
|
||||
async function selectChat(chat) {
|
||||
activeChatState = chat;
|
||||
|
||||
chat.unreadCount = 0;
|
||||
|
||||
ui.renderChatList(chatsState, activeChatState, selectChat);
|
||||
|
||||
ui.toggleChatState(true);
|
||||
elements.activeChatName.textContent = chat.name;
|
||||
elements.activeChatAvatar.textContent = chat.name ? chat.name.substring(0, 1).toUpperCase() : '?';
|
||||
|
||||
elements.messagesContainer.innerHTML = '<div class="loading-chats"><div class="spinner"></div><span>Loading messages...</span></div>';
|
||||
|
||||
if (window.innerWidth <= 768) {
|
||||
elements.sidebar.classList.add('hidden');
|
||||
}
|
||||
|
||||
try {
|
||||
const rawMessages = await waha.getChatMessages(chat.id);
|
||||
const processedMessages = compensateMessageOrdering(rawMessages);
|
||||
ui.renderMessages(processedMessages, chat.name);
|
||||
} catch (error) {
|
||||
console.error('Failed to load messages:', error);
|
||||
elements.messagesContainer.innerHTML = '<div class="loading-chats">Error loading messages</div>';
|
||||
}
|
||||
}
|
||||
|
||||
async function sendMessage() {
|
||||
const text = elements.messageInput.value.trim();
|
||||
if (!text || !activeChatState) return;
|
||||
|
||||
elements.messageInput.value = '';
|
||||
|
||||
const tempMsg = {
|
||||
id: 'temp-' + Date.now(),
|
||||
body: text,
|
||||
fromMe: true,
|
||||
sender: 'me',
|
||||
timestamp: new Date().toISOString(),
|
||||
status: 'sending'
|
||||
};
|
||||
|
||||
ui.appendSingleMessage(tempMsg, activeChatState.name);
|
||||
ui.scrollToBottom();
|
||||
|
||||
try {
|
||||
try {
|
||||
await waha.startTyping(activeChatState.id);
|
||||
const delay = Math.min(4000, Math.max(1000, text.length * 50));
|
||||
await new Promise(resolve => setTimeout(resolve, delay));
|
||||
} catch (e) {
|
||||
console.warn('Presence start failed:', e);
|
||||
}
|
||||
|
||||
try {
|
||||
await waha.stopTyping(activeChatState.id);
|
||||
} catch (e) {
|
||||
console.warn('Presence stop failed:', e);
|
||||
}
|
||||
|
||||
try {
|
||||
if (!activeChatState.id.endsWith('@lid')) {
|
||||
await waha.readChat(activeChatState.id);
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn('readChat failed (non-fatal):', e.message);
|
||||
}
|
||||
|
||||
const responseData = await waha.sendTextMessage(activeChatState.id, text);
|
||||
|
||||
const tempBubble = document.getElementById(tempMsg.id);
|
||||
if (tempBubble) {
|
||||
if (responseData && responseData.id) {
|
||||
tempBubble.id = responseData.id;
|
||||
}
|
||||
const meta = tempBubble.querySelector('.message-meta');
|
||||
meta.innerHTML = `<span>${formatTime(new Date())}</span><i data-lucide="check" style="width:14px; height:14px;"></i>`;
|
||||
lucide.createIcons();
|
||||
}
|
||||
|
||||
activeChatState.lastMessage = text;
|
||||
activeChatState.timestamp = new Date();
|
||||
|
||||
chatsState.sort((a, b) => {
|
||||
const tA = new Date(a.timestamp).getTime();
|
||||
const tB = new Date(b.timestamp).getTime();
|
||||
return tB - tA;
|
||||
});
|
||||
ui.renderChatList(chatsState, activeChatState, selectChat);
|
||||
} catch (error) {
|
||||
console.error('Failed to send message:', error);
|
||||
const tempBubble = document.getElementById(tempMsg.id);
|
||||
if (tempBubble) {
|
||||
const meta = tempBubble.querySelector('.message-meta');
|
||||
meta.innerHTML = `<span style="color: #ef4444;">Failed to send</span>`;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function openSettings() {
|
||||
elements.inputWahaUrl.value = config.wahaUrl;
|
||||
elements.inputSession.value = config.session;
|
||||
elements.inputApiKey.value = config.apiKey;
|
||||
ui.toggleModal(true);
|
||||
}
|
||||
|
||||
function saveSettings() {
|
||||
config.save(
|
||||
elements.inputWahaUrl.value,
|
||||
elements.inputSession.value,
|
||||
elements.inputApiKey.value
|
||||
);
|
||||
ui.toggleModal(false);
|
||||
fetchChats();
|
||||
checkWahaStatus();
|
||||
initWebSocket();
|
||||
}
|
||||
|
||||
async function checkWahaStatus() {
|
||||
try {
|
||||
const data = await waha.getVersion();
|
||||
ui.updateConnectionStatus(true, `WAHA Connected: v${data.version || 'OK'}`);
|
||||
} catch (e) {
|
||||
ui.updateConnectionStatus(false, 'WAHA Server Offline');
|
||||
}
|
||||
}
|
||||
17
public/config.js
Normal file
17
public/config.js
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
// Client Configuration State & Storage Manager
|
||||
|
||||
export const config = {
|
||||
wahaUrl: localStorage.getItem('waha_url') || 'http://inspiran.beetal-castor.ts.net:3100',
|
||||
session: localStorage.getItem('waha_session') || 'session_01kxc62bk5fs8vh4v127k88a7j',
|
||||
apiKey: localStorage.getItem('waha_api_key') || '',
|
||||
|
||||
save(url, session, apiKey) {
|
||||
this.wahaUrl = url.trim().replace(/\/$/, "");
|
||||
this.session = session.trim();
|
||||
this.apiKey = apiKey.trim();
|
||||
|
||||
localStorage.setItem('waha_url', this.wahaUrl);
|
||||
localStorage.setItem('waha_session', this.session);
|
||||
localStorage.setItem('waha_api_key', this.apiKey);
|
||||
}
|
||||
};
|
||||
147
public/index.html
Normal file
147
public/index.html
Normal file
|
|
@ -0,0 +1,147 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Pandora</title>
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
|
||||
<link rel="stylesheet" href="style.css">
|
||||
<script src="https://unpkg.com/lucide@latest"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div class="app-container">
|
||||
<!-- Sidebar -->
|
||||
<aside class="sidebar">
|
||||
<header class="sidebar-header">
|
||||
<div class="user-profile">
|
||||
<div id="pandora-user-icon" class="avatar user-avatar">P</div>
|
||||
<div class="user-info">
|
||||
<h3 id="pandora-username">Pandora User</h3>
|
||||
<span class="status-indicator online">Online</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="header-actions">
|
||||
<button class="icon-btn" title="New Chat"><i data-lucide="message-square-plus"></i></button>
|
||||
<button class="icon-btn" id="refresh-chats-btn" title="Refresh Chats"><i data-lucide="refresh-cw"></i></button>
|
||||
<button class="icon-btn" title="Settings"><i data-lucide="settings"></i></button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div class="search-container">
|
||||
<div class="search-wrapper">
|
||||
<i data-lucide="search" class="search-icon"></i>
|
||||
<input type="text" id="chat-search" placeholder="Search or start new chat...">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="chat-list-container">
|
||||
<div class="chat-list-header">
|
||||
<span>Recent Chats</span>
|
||||
<span class="badge" id="chat-count">0</span>
|
||||
</div>
|
||||
<div class="loading-chats" id="chats-loader">
|
||||
<div class="spinner"></div>
|
||||
<span>Loading chats...</span>
|
||||
</div>
|
||||
<ul class="chat-list" id="chat-list">
|
||||
<!-- Chats will be dynamically injected here -->
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="sidebar-footer">
|
||||
<div class="api-status-badge">
|
||||
<span class="pulse-dot"></span>
|
||||
<span id="backend-status-text">Backend connected</span>
|
||||
</div>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<!-- Main Chat Area -->
|
||||
<main class="chat-area">
|
||||
<!-- No Chat Selected State -->
|
||||
<div class="no-chat-state" id="no-chat-state">
|
||||
<div class="empty-state-content">
|
||||
<div class="empty-state-icon">
|
||||
<i data-lucide="message-square"></i>
|
||||
</div>
|
||||
<h2>Welcome to Pandora Chat</h2>
|
||||
<p>Select a contact from the sidebar to view the conversation or start a new chat. Your chats are synced directly with the WAHA API backend.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Active Chat State -->
|
||||
<div class="active-chat-container hidden" id="active-chat-container">
|
||||
<header class="chat-header">
|
||||
<div class="active-contact-info">
|
||||
<button class="icon-btn back-btn" id="back-to-sidebar"><i data-lucide="arrow-left"></i></button>
|
||||
<div class="avatar active-avatar" id="active-chat-avatar">C</div>
|
||||
<div>
|
||||
<h3 id="active-chat-name">Contact Name</h3>
|
||||
<span class="contact-status" id="active-chat-status">Active now</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="chat-actions">
|
||||
<button class="icon-btn" title="Search in conversation"><i data-lucide="search"></i></button>
|
||||
<button class="icon-btn" title="Call"><i data-lucide="phone"></i></button>
|
||||
<button class="icon-btn" title="Video Call"><i data-lucide="video"></i></button>
|
||||
<button class="icon-btn" title="More Options"><i data-lucide="more-vertical"></i></button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<!-- Messages Area -->
|
||||
<div class="messages-container" id="messages-container">
|
||||
<!-- Messages will be dynamically injected here -->
|
||||
</div>
|
||||
|
||||
<!-- Input Panel -->
|
||||
<footer class="chat-input-panel">
|
||||
<div class="input-actions-left">
|
||||
<button class="icon-btn" title="Attach file"><i data-lucide="paperclip"></i></button>
|
||||
<button class="icon-btn" title="Add emoji"><i data-lucide="smile"></i></button>
|
||||
</div>
|
||||
<form class="input-form" id="message-form">
|
||||
<input type="text" id="message-input" placeholder="Type a message..." autocomplete="off">
|
||||
<button type="submit" class="send-btn" id="send-button">
|
||||
<i data-lucide="send"></i>
|
||||
</button>
|
||||
</form>
|
||||
</footer>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
|
||||
<!-- Settings Modal -->
|
||||
<div class="modal-overlay hidden" id="settings-modal">
|
||||
<div class="modal-content">
|
||||
<header class="modal-header">
|
||||
<h2>WAHA Connection Settings</h2>
|
||||
<button class="icon-btn close-modal-btn" id="close-settings"><i data-lucide="x"></i></button>
|
||||
</header>
|
||||
<div class="modal-body">
|
||||
<div class="form-group">
|
||||
<label for="settings-waha-url">WAHA Server URL</label>
|
||||
<input type="text" id="settings-waha-url" placeholder="http://localhost:3100">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="settings-session">Session ID</label>
|
||||
<input type="text" id="settings-session" placeholder="session_01...">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="settings-api-key">API Key (X-API-KEY)</label>
|
||||
<input type="password" id="settings-api-key" placeholder="Enter API Key">
|
||||
</div>
|
||||
<p class="settings-warning">⚠️ Note: Requests are sent directly from your browser to the WAHA server. Make sure CORS is enabled on your WAHA instance.</p>
|
||||
</div>
|
||||
<footer class="modal-footer">
|
||||
<button class="btn secondary-btn" id="cancel-settings">Cancel</button>
|
||||
<button class="btn primary-btn" id="save-settings">Save Config</button>
|
||||
</footer>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Client-side script loaded as ES Module -->
|
||||
<script type="module" src="app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
769
public/style.css
Normal file
769
public/style.css
Normal file
|
|
@ -0,0 +1,769 @@
|
|||
:root {
|
||||
--bg-main: #090d16;
|
||||
--sidebar-bg: rgba(17, 24, 39, 0.75);
|
||||
--chat-bg: rgba(15, 23, 42, 0.6);
|
||||
--border-color: rgba(255, 255, 255, 0.08);
|
||||
--border-hover: rgba(255, 255, 255, 0.15);
|
||||
--text-primary: #f8fafc;
|
||||
--text-secondary: #94a3b8;
|
||||
--text-muted: #64748b;
|
||||
--accent: #6366f1;
|
||||
--accent-gradient: linear-gradient(135deg, #6366f1 0%, #a855f7 100%);
|
||||
--accent-hover: #4f46e5;
|
||||
--online-color: #10b981;
|
||||
--bubble-incoming: rgba(30, 41, 59, 0.85);
|
||||
--bubble-outgoing: linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%);
|
||||
--input-bg: rgba(15, 23, 42, 0.8);
|
||||
--shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
|
||||
--shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
|
||||
--shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.3), 0 4px 6px -2px rgba(0, 0, 0, 0.1);
|
||||
--glass-blur: blur(20px);
|
||||
}
|
||||
|
||||
* {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
|
||||
}
|
||||
|
||||
body {
|
||||
background-color: var(--bg-main);
|
||||
color: var(--text-primary);
|
||||
height: 100vh;
|
||||
overflow: hidden;
|
||||
background-image:
|
||||
radial-gradient(at 0% 0%, rgba(99, 102, 241, 0.12) 0px, transparent 50%),
|
||||
radial-gradient(at 100% 100%, rgba(168, 85, 247, 0.12) 0px, transparent 50%);
|
||||
}
|
||||
|
||||
.app-container {
|
||||
display: flex;
|
||||
width: 100vw;
|
||||
height: 100vh;
|
||||
overflow: hidden;
|
||||
backdrop-filter: var(--glass-blur);
|
||||
}
|
||||
|
||||
/* Sidebar Styling */
|
||||
.sidebar {
|
||||
width: 380px;
|
||||
background-color: var(--sidebar-bg);
|
||||
border-right: 1px solid var(--border-color);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
flex-shrink: 0;
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
|
||||
.sidebar-header {
|
||||
padding: 20px;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
border-bottom: 1px solid var(--border-color);
|
||||
}
|
||||
|
||||
.user-profile {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.avatar {
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
border-radius: 12px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-weight: 700;
|
||||
font-size: 1.1rem;
|
||||
color: white;
|
||||
background: var(--accent-gradient);
|
||||
box-shadow: var(--shadow-md);
|
||||
position: relative;
|
||||
border: 1px solid rgba(255, 255, 255, 0.1);
|
||||
}
|
||||
|
||||
.user-avatar {
|
||||
background: linear-gradient(135deg, #10b981 0%, #059669 100%);
|
||||
}
|
||||
|
||||
.user-info h3 {
|
||||
font-size: 0.95rem;
|
||||
font-weight: 600;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.status-indicator {
|
||||
font-size: 0.75rem;
|
||||
color: var(--text-secondary);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.status-indicator::before {
|
||||
content: '';
|
||||
display: inline-block;
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
border-radius: 50%;
|
||||
background-color: var(--online-color);
|
||||
}
|
||||
|
||||
.header-actions {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.icon-btn {
|
||||
width: 38px;
|
||||
height: 38px;
|
||||
border-radius: 10px;
|
||||
border: 1px solid var(--border-color);
|
||||
background: rgba(255, 255, 255, 0.03);
|
||||
color: var(--text-secondary);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
|
||||
}
|
||||
|
||||
.icon-btn:hover {
|
||||
background: rgba(255, 255, 255, 0.08);
|
||||
color: var(--text-primary);
|
||||
border-color: var(--border-hover);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.icon-btn:active {
|
||||
transform: translateY(0);
|
||||
}
|
||||
|
||||
/* Search Bar */
|
||||
.search-container {
|
||||
padding: 16px 20px;
|
||||
}
|
||||
|
||||
.search-wrapper {
|
||||
position: relative;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.search-icon {
|
||||
position: absolute;
|
||||
left: 14px;
|
||||
color: var(--text-muted);
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
#chat-search {
|
||||
width: 100%;
|
||||
padding: 12px 14px 12px 42px;
|
||||
border-radius: 10px;
|
||||
border: 1px solid var(--border-color);
|
||||
background: rgba(15, 23, 42, 0.6);
|
||||
color: var(--text-primary);
|
||||
font-size: 0.9rem;
|
||||
transition: all 0.25s ease;
|
||||
}
|
||||
|
||||
#chat-search:focus {
|
||||
outline: none;
|
||||
border-color: var(--accent);
|
||||
background: rgba(15, 23, 42, 0.9);
|
||||
box-shadow: 0 0 0 2px rgba(99, 102, 241, 0.2);
|
||||
}
|
||||
|
||||
/* Chat List container */
|
||||
.chat-list-container {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow-y: auto;
|
||||
padding: 0 10px 10px 10px;
|
||||
}
|
||||
|
||||
.chat-list-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 10px 10px 14px 10px;
|
||||
font-size: 0.8rem;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.05em;
|
||||
color: var(--text-muted);
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.badge {
|
||||
background: var(--accent-gradient);
|
||||
color: white;
|
||||
font-size: 0.75rem;
|
||||
padding: 2px 8px;
|
||||
border-radius: 12px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.chat-list {
|
||||
list-style: none;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.chat-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 12px;
|
||||
border-radius: 12px;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease;
|
||||
border: 1px solid transparent;
|
||||
}
|
||||
|
||||
.chat-item:hover {
|
||||
background: rgba(255, 255, 255, 0.04);
|
||||
}
|
||||
|
||||
.chat-item.active {
|
||||
background: rgba(99, 102, 241, 0.15);
|
||||
border-color: rgba(99, 102, 241, 0.25);
|
||||
}
|
||||
|
||||
.chat-item-info {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.chat-item-meta {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.chat-item-name {
|
||||
font-size: 0.95rem;
|
||||
font-weight: 600;
|
||||
color: var(--text-primary);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.chat-item-time {
|
||||
font-size: 0.75rem;
|
||||
color: var(--text-muted);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.chat-item-preview {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.chat-item-msg {
|
||||
font-size: 0.82rem;
|
||||
color: var(--text-secondary);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.chat-item .unread-badge {
|
||||
background: var(--accent);
|
||||
color: white;
|
||||
font-size: 0.7rem;
|
||||
min-width: 18px;
|
||||
height: 18px;
|
||||
border-radius: 9px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-weight: 700;
|
||||
padding: 0 4px;
|
||||
}
|
||||
|
||||
.loading-chats {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 12px;
|
||||
padding: 40px 20px;
|
||||
color: var(--text-secondary);
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.spinner {
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
border: 2px solid rgba(255, 255, 255, 0.1);
|
||||
border-top-color: var(--accent);
|
||||
border-radius: 50%;
|
||||
animation: spin 0.8s linear infinite;
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
to { transform: rotate(360deg); }
|
||||
}
|
||||
|
||||
/* Sidebar Footer */
|
||||
.sidebar-footer {
|
||||
padding: 14px 20px;
|
||||
border-top: 1px solid var(--border-color);
|
||||
background: rgba(10, 15, 26, 0.4);
|
||||
}
|
||||
|
||||
.api-status-badge {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-size: 0.75rem;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.pulse-dot {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
background-color: var(--online-color);
|
||||
border-radius: 50%;
|
||||
box-shadow: 0 0 0 0 rgba(16, 185, 129, 0.7);
|
||||
animation: pulse 1.8s infinite;
|
||||
}
|
||||
|
||||
@keyframes pulse {
|
||||
0% {
|
||||
transform: scale(0.95);
|
||||
box-shadow: 0 0 0 0 rgba(16, 185, 129, 0.7);
|
||||
}
|
||||
70% {
|
||||
transform: scale(1);
|
||||
box-shadow: 0 0 0 6px rgba(16, 185, 129, 0);
|
||||
}
|
||||
100% {
|
||||
transform: scale(0.95);
|
||||
box-shadow: 0 0 0 0 rgba(16, 185, 129, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/* Main Chat Area */
|
||||
.chat-area {
|
||||
flex: 1;
|
||||
background-color: var(--chat-bg);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
/* Empty State */
|
||||
.no-chat-state {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 40px;
|
||||
text-align: center;
|
||||
background: radial-gradient(circle at center, rgba(30, 41, 59, 0.2) 0%, transparent 70%);
|
||||
}
|
||||
|
||||
.empty-state-content {
|
||||
max-width: 420px;
|
||||
}
|
||||
|
||||
.empty-state-icon {
|
||||
width: 80px;
|
||||
height: 80px;
|
||||
border-radius: 24px;
|
||||
background: rgba(255, 255, 255, 0.03);
|
||||
border: 1px solid var(--border-color);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
margin: 0 auto 24px auto;
|
||||
color: var(--accent);
|
||||
font-size: 2rem;
|
||||
}
|
||||
|
||||
.empty-state-content h2 {
|
||||
font-size: 1.5rem;
|
||||
font-weight: 700;
|
||||
margin-bottom: 12px;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.empty-state-content p {
|
||||
font-size: 0.9rem;
|
||||
color: var(--text-secondary);
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
/* Active Chat Interface */
|
||||
.active-chat-container {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.chat-header {
|
||||
padding: 16px 24px;
|
||||
border-bottom: 1px solid var(--border-color);
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
background: rgba(15, 23, 42, 0.3);
|
||||
}
|
||||
|
||||
.active-contact-info {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 14px;
|
||||
}
|
||||
|
||||
.active-avatar {
|
||||
width: 42px;
|
||||
height: 42px;
|
||||
border-radius: 12px;
|
||||
}
|
||||
|
||||
.active-contact-info h3 {
|
||||
font-size: 1rem;
|
||||
font-weight: 600;
|
||||
margin-bottom: 2px;
|
||||
}
|
||||
|
||||
.contact-status {
|
||||
font-size: 0.75rem;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.chat-actions {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.back-btn {
|
||||
display: none;
|
||||
}
|
||||
|
||||
/* Messages Area */
|
||||
.messages-container {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
padding: 24px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
background-image:
|
||||
radial-gradient(circle at 10% 20%, rgba(99, 102, 241, 0.03) 0%, transparent 40%),
|
||||
radial-gradient(circle at 90% 80%, rgba(168, 85, 247, 0.03) 0%, transparent 40%);
|
||||
}
|
||||
|
||||
.message-group {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
max-width: 65%;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.message-group.incoming {
|
||||
align-self: flex-start;
|
||||
}
|
||||
|
||||
.message-group.outgoing {
|
||||
align-self: flex-end;
|
||||
}
|
||||
|
||||
.message-sender {
|
||||
font-size: 0.75rem;
|
||||
font-weight: 600;
|
||||
color: var(--text-muted);
|
||||
margin-left: 12px;
|
||||
margin-bottom: 2px;
|
||||
}
|
||||
|
||||
.message-bubble {
|
||||
padding: 12px 16px;
|
||||
border-radius: 18px;
|
||||
font-size: 0.92rem;
|
||||
line-height: 1.5;
|
||||
position: relative;
|
||||
word-break: break-word;
|
||||
box-shadow: var(--shadow-sm);
|
||||
}
|
||||
|
||||
.message-group.incoming .message-bubble {
|
||||
background-color: var(--bubble-incoming);
|
||||
color: var(--text-primary);
|
||||
border-top-left-radius: 4px;
|
||||
border: 1px solid var(--border-color);
|
||||
}
|
||||
|
||||
.message-group.outgoing .message-bubble {
|
||||
background: var(--bubble-outgoing);
|
||||
color: white;
|
||||
border-top-right-radius: 4px;
|
||||
}
|
||||
|
||||
.message-meta {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
gap: 4px;
|
||||
font-size: 0.7rem;
|
||||
color: rgba(255, 255, 255, 0.65);
|
||||
margin-top: 4px;
|
||||
}
|
||||
|
||||
.message-group.incoming .message-meta {
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
/* Chat Input Panel */
|
||||
.chat-input-panel {
|
||||
padding: 20px 24px;
|
||||
background: var(--input-bg);
|
||||
border-top: 1px solid var(--border-color);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.input-actions-left {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.input-form {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
#message-input {
|
||||
flex: 1;
|
||||
padding: 12px 18px;
|
||||
background: rgba(255, 255, 255, 0.04);
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: 12px;
|
||||
color: var(--text-primary);
|
||||
font-size: 0.95rem;
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
|
||||
#message-input:focus {
|
||||
outline: none;
|
||||
border-color: var(--accent);
|
||||
background: rgba(255, 255, 255, 0.06);
|
||||
box-shadow: 0 0 0 2px rgba(99, 102, 241, 0.1);
|
||||
}
|
||||
|
||||
.send-btn {
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
border-radius: 12px;
|
||||
background: var(--accent-gradient);
|
||||
border: none;
|
||||
color: white;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
cursor: pointer;
|
||||
box-shadow: var(--shadow-md);
|
||||
transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
|
||||
}
|
||||
|
||||
.send-btn:hover {
|
||||
transform: scale(1.05) translateY(-1px);
|
||||
box-shadow: 0 6px 20px rgba(99, 102, 241, 0.4);
|
||||
}
|
||||
|
||||
.send-btn:active {
|
||||
transform: scale(0.98) translateY(0);
|
||||
}
|
||||
|
||||
.send-btn i {
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
}
|
||||
|
||||
/* Scrollbars styling */
|
||||
::-webkit-scrollbar {
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-thumb {
|
||||
background: rgba(255, 255, 255, 0.08);
|
||||
border-radius: 10px;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-thumb:hover {
|
||||
background: rgba(255, 255, 255, 0.16);
|
||||
}
|
||||
|
||||
/* Helper classes */
|
||||
.hidden {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
/* Responsive design */
|
||||
@media (max-width: 768px) {
|
||||
.app-container {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.sidebar {
|
||||
width: 100%;
|
||||
position: absolute;
|
||||
left: 0;
|
||||
top: 0;
|
||||
height: 100%;
|
||||
z-index: 10;
|
||||
}
|
||||
|
||||
.sidebar.hidden {
|
||||
transform: translateX(-100%);
|
||||
display: flex !important; /* overrides standard .hidden */
|
||||
}
|
||||
|
||||
.chat-area {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.back-btn {
|
||||
display: flex;
|
||||
margin-right: 8px;
|
||||
}
|
||||
}
|
||||
|
||||
/* Modal Styling */
|
||||
.modal-overlay {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100vw;
|
||||
height: 100vh;
|
||||
background: rgba(0, 0, 0, 0.6);
|
||||
backdrop-filter: blur(8px);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 100;
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
|
||||
.modal-content {
|
||||
background: rgba(30, 41, 59, 0.85);
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: 16px;
|
||||
width: 90%;
|
||||
max-width: 480px;
|
||||
padding: 24px;
|
||||
box-shadow: var(--shadow-lg);
|
||||
backdrop-filter: var(--glass-blur);
|
||||
}
|
||||
|
||||
.modal-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.modal-header h2 {
|
||||
font-size: 1.2rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.modal-body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.form-group {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.form-group label {
|
||||
font-size: 0.82rem;
|
||||
color: var(--text-secondary);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.form-group input {
|
||||
padding: 10px 12px;
|
||||
border-radius: 8px;
|
||||
border: 1px solid var(--border-color);
|
||||
background: rgba(15, 23, 42, 0.5);
|
||||
color: var(--text-primary);
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.form-group input:focus {
|
||||
outline: none;
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
.settings-warning {
|
||||
font-size: 0.75rem;
|
||||
color: var(--text-muted);
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.modal-footer {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 12px;
|
||||
margin-top: 24px;
|
||||
}
|
||||
|
||||
.btn {
|
||||
padding: 10px 18px;
|
||||
border-radius: 8px;
|
||||
font-size: 0.9rem;
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
border: none;
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
|
||||
.primary-btn {
|
||||
background: var(--accent-gradient);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.primary-btn:hover {
|
||||
transform: translateY(-1px);
|
||||
box-shadow: 0 4px 12px rgba(99, 102, 241, 0.3);
|
||||
}
|
||||
|
||||
.secondary-btn {
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
color: var(--text-primary);
|
||||
border: 1px solid var(--border-color);
|
||||
}
|
||||
|
||||
.secondary-btn:hover {
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
}
|
||||
|
||||
198
public/ui.js
Normal file
198
public/ui.js
Normal file
|
|
@ -0,0 +1,198 @@
|
|||
import { formatTime } from "./utils.js";
|
||||
|
||||
// DOM Selector Cache
|
||||
export const elements = {
|
||||
chatList: document.getElementById('chat-list'),
|
||||
chatsLoader: document.getElementById('chats-loader'),
|
||||
chatCountBadge: document.getElementById('chat-count'),
|
||||
chatSearch: document.getElementById('chat-search'),
|
||||
refreshChatsBtn: document.getElementById('refresh-chats-btn'),
|
||||
backendStatusText: document.getElementById('backend-status-text'),
|
||||
apiStatusIndicator: document.querySelector('.pulse-dot'),
|
||||
noChatState: document.getElementById('no-chat-state'),
|
||||
activeChatContainer: document.getElementById('active-chat-container'),
|
||||
activeChatName: document.getElementById('active-chat-name'),
|
||||
activeChatAvatar: document.getElementById('active-chat-avatar'),
|
||||
messagesContainer: document.getElementById('messages-container'),
|
||||
messageForm: document.getElementById('message-form'),
|
||||
messageInput: document.getElementById('message-input'),
|
||||
backToSidebarBtn: document.getElementById('back-to-sidebar'),
|
||||
sidebar: document.querySelector('.sidebar'),
|
||||
settingsModal: document.getElementById('settings-modal'),
|
||||
settingsIconBtn: document.querySelector('.header-actions button[title="Settings"]'),
|
||||
closeSettingsBtn: document.getElementById('close-settings'),
|
||||
cancelSettingsBtn: document.getElementById('cancel-settings'),
|
||||
saveSettingsBtn: document.getElementById('save-settings'),
|
||||
inputWahaUrl: document.getElementById('settings-waha-url'),
|
||||
inputSession: document.getElementById('settings-session'),
|
||||
inputApiKey: document.getElementById('settings-api-key'),
|
||||
loggedUserName: document.getElementById('pandora-username'),
|
||||
userIcon: document.getElementById('pandora-user-icon')
|
||||
};
|
||||
|
||||
export const ui = {
|
||||
/**
|
||||
* Show or hide Settings connection modal
|
||||
*/
|
||||
toggleModal(show) {
|
||||
if (show) {
|
||||
elements.settingsModal.classList.remove('hidden');
|
||||
} else {
|
||||
elements.settingsModal.classList.add('hidden');
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Switch view state when a contact chat is opened or closed
|
||||
*/
|
||||
toggleChatState(hasActive) {
|
||||
if (hasActive) {
|
||||
elements.noChatState.classList.add('hidden');
|
||||
elements.activeChatContainer.classList.remove('hidden');
|
||||
} else {
|
||||
elements.noChatState.classList.remove('hidden');
|
||||
elements.activeChatContainer.classList.add('hidden');
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Scroll message list automatically to bottom
|
||||
*/
|
||||
scrollToBottom() {
|
||||
elements.messagesContainer.scrollTop = elements.messagesContainer.scrollHeight;
|
||||
},
|
||||
|
||||
/**
|
||||
* Update connection status badge in sidebar footer
|
||||
*/
|
||||
updateConnectionStatus(isConnected, text) {
|
||||
elements.backendStatusText.textContent = text;
|
||||
if (isConnected) {
|
||||
elements.apiStatusIndicator.style.backgroundColor = 'var(--online-color)';
|
||||
elements.apiStatusIndicator.style.animation = 'pulse 1.8s infinite';
|
||||
} else {
|
||||
elements.apiStatusIndicator.style.backgroundColor = '#ef4444';
|
||||
elements.apiStatusIndicator.style.animation = 'none';
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Render sidebar contact chats list
|
||||
*/
|
||||
renderChatList(chats, activeChat, onChatSelect) {
|
||||
elements.chatList.innerHTML = '';
|
||||
elements.chatCountBadge.textContent = chats.length;
|
||||
|
||||
if (chats.length === 0) {
|
||||
elements.chatList.innerHTML = `<li class="loading-chats">No chats found</li>`;
|
||||
return;
|
||||
}
|
||||
|
||||
chats.forEach(chat => {
|
||||
const li = document.createElement('li');
|
||||
li.className = `chat-item ${activeChat && activeChat.id === chat.id ? 'active' : ''}`;
|
||||
li.dataset.id = chat.id;
|
||||
|
||||
const initials = chat.name ? chat.name.substring(0, 1).toUpperCase() : '?';
|
||||
const hasUnread = chat.unreadCount && chat.unreadCount > 0;
|
||||
const timeStr = formatTime(chat.timestamp || new Date());
|
||||
|
||||
li.innerHTML = `
|
||||
<div class="avatar">${initials}</div>
|
||||
<div class="chat-item-info">
|
||||
<div class="chat-item-meta">
|
||||
<span class="chat-item-name">${chat.name}</span>
|
||||
<span class="chat-item-time">${timeStr}</span>
|
||||
</div>
|
||||
<div class="chat-item-preview">
|
||||
<span class="chat-item-msg">${chat.lastMessage || 'No messages yet'}</span>
|
||||
${hasUnread ? `<span class="unread-badge">${chat.unreadCount}</span>` : ''}
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
li.addEventListener('click', () => onChatSelect(chat));
|
||||
elements.chatList.appendChild(li);
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Render chat message log inside chat view container
|
||||
*/
|
||||
renderMessages(messages, activeChatName) {
|
||||
elements.messagesContainer.innerHTML = '';
|
||||
|
||||
if (messages.length === 0) {
|
||||
elements.messagesContainer.innerHTML = '<div class="loading-chats">No messages. Say hello!</div>';
|
||||
return;
|
||||
}
|
||||
|
||||
messages.forEach(msg => {
|
||||
const isOutgoing = msg.fromMe || msg.sender === 'me';
|
||||
const groupDiv = document.createElement('div');
|
||||
groupDiv.className = `message-group ${isOutgoing ? 'outgoing' : 'incoming'}`;
|
||||
groupDiv.id = msg.id;
|
||||
|
||||
const senderName = isOutgoing ? 'Me' : (msg.senderName || activeChatName);
|
||||
const timeStr = formatTime(msg.timestamp || new Date());
|
||||
|
||||
let statusCheck = '';
|
||||
if (isOutgoing) {
|
||||
if (msg.status === 'read') {
|
||||
statusCheck = '<i data-lucide="check-check" style="color: var(--online-color); width:14px; height:14px;"></i>';
|
||||
} else if (msg.status === 'delivered') {
|
||||
statusCheck = '<i data-lucide="check-check" style="width:14px; height:14px;"></i>';
|
||||
} else {
|
||||
statusCheck = '<i data-lucide="check" style="width:14px; height:14px;"></i>';
|
||||
}
|
||||
}
|
||||
|
||||
groupDiv.innerHTML = `
|
||||
${!isOutgoing ? `<span class="message-sender">${senderName}</span>` : ''}
|
||||
<div class="message-bubble">
|
||||
${msg.body || msg.text}
|
||||
<div class="message-meta">
|
||||
<span>${timeStr}</span>
|
||||
${statusCheck}
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
elements.messagesContainer.appendChild(groupDiv);
|
||||
});
|
||||
|
||||
lucide.createIcons();
|
||||
this.scrollToBottom();
|
||||
},
|
||||
|
||||
/**
|
||||
* Append a single message (used for optimistic updates immediately upon sending)
|
||||
*/
|
||||
appendSingleMessage(msg, activeChatName) {
|
||||
if (elements.messagesContainer.querySelector('.loading-chats')) {
|
||||
elements.messagesContainer.innerHTML = '';
|
||||
}
|
||||
|
||||
const isOutgoing = msg.fromMe || msg.sender === 'me';
|
||||
const groupDiv = document.createElement('div');
|
||||
groupDiv.className = `message-group ${isOutgoing ? 'outgoing' : 'incoming'}`;
|
||||
groupDiv.id = msg.id;
|
||||
|
||||
const senderName = isOutgoing ? 'Me' : activeChatName;
|
||||
const timeStr = formatTime(msg.timestamp || new Date());
|
||||
|
||||
groupDiv.innerHTML = `
|
||||
${!isOutgoing ? `<span class="message-sender">${senderName}</span>` : ''}
|
||||
<div class="message-bubble">
|
||||
${msg.body || msg.text}
|
||||
<div class="message-meta">
|
||||
<span>${timeStr}</span>
|
||||
<i data-lucide="clock" style="width:12px; height:12px; opacity:0.6;"></i>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
elements.messagesContainer.appendChild(groupDiv);
|
||||
lucide.createIcons();
|
||||
}
|
||||
};
|
||||
81
public/utils.js
Normal file
81
public/utils.js
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
// Helper utilities and algorithms
|
||||
|
||||
/**
|
||||
* Format timestamps (supports Unix epoch seconds/ms, strings and ISO dates)
|
||||
* @param {string|number|Date} dateVal
|
||||
* @returns {string} Formatted HH:MM AM/PM string
|
||||
*/
|
||||
export function formatTime(dateVal) {
|
||||
if (!dateVal) return '';
|
||||
let date;
|
||||
if (typeof dateVal === 'number') {
|
||||
date = new Date(dateVal < 10000000000 ? dateVal * 1000 : dateVal);
|
||||
} else if (typeof dateVal === 'string' && /^\d+$/.test(dateVal)) {
|
||||
const num = parseInt(dateVal, 10);
|
||||
date = new Date(num < 10000000000 ? num * 1000 : num);
|
||||
} else {
|
||||
date = new Date(dateVal);
|
||||
}
|
||||
|
||||
let hours = date.getHours();
|
||||
let minutes = date.getMinutes();
|
||||
const ampm = hours >= 12 ? 'PM' : 'AM';
|
||||
hours = hours % 12;
|
||||
hours = hours ? hours : 12;
|
||||
minutes = minutes < 10 ? '0' + minutes : minutes;
|
||||
return `${hours}:${minutes} ${ampm}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adjust outgoing messages backdated behind incoming messages due to clock drift.
|
||||
* Uses a 30-second sliding bubble-sort window.
|
||||
* @param {Array} messages List of raw messages from WAHA
|
||||
* @returns {Array} Compensated chronological message array
|
||||
*/
|
||||
export function compensateMessageOrdering(messages) {
|
||||
if (!Array.isArray(messages)) return [];
|
||||
|
||||
// Convert timestamps to numeric milliseconds for stable comparison
|
||||
const msgs = messages.map(m => {
|
||||
let t = m.timestamp;
|
||||
if (typeof t === 'number') {
|
||||
if (t < 10000000000) t = t * 1000;
|
||||
} else {
|
||||
t = new Date(t).getTime();
|
||||
}
|
||||
return { ...m, _time: t };
|
||||
});
|
||||
|
||||
// Initial chronological sort
|
||||
msgs.sort((a, b) => a._time - b._time);
|
||||
|
||||
// Apply drift bubble adjustments
|
||||
let changed = true;
|
||||
while (changed) {
|
||||
changed = false;
|
||||
for (let i = 0; i < msgs.length - 1; i++) {
|
||||
const current = msgs[i];
|
||||
const next = msgs[i + 1];
|
||||
const timeDiff = next._time - current._time;
|
||||
|
||||
// Swap if an outgoing message is sorted before an incoming message within a 30-sec window
|
||||
if (current.fromMe && !next.fromMe && timeDiff >= 0 && timeDiff <= 30000) {
|
||||
msgs[i] = next;
|
||||
msgs[i + 1] = current;
|
||||
|
||||
// Advance the outgoing message's timestamp to be exactly 1 second after the incoming one
|
||||
current._time = next._time + 1000;
|
||||
if (typeof current.timestamp === 'number') {
|
||||
current.timestamp = Math.floor(current._time / 1000);
|
||||
} else {
|
||||
current.timestamp = new Date(current._time).toISOString();
|
||||
}
|
||||
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Clean up temporary property
|
||||
return msgs.map(({ _time, ...m }) => m);
|
||||
}
|
||||
92
public/waha.js
Normal file
92
public/waha.js
Normal file
|
|
@ -0,0 +1,92 @@
|
|||
import { config } from "./config.js";
|
||||
|
||||
async function request(path, options = {}) {
|
||||
const url = `${config.wahaUrl}${path}`;
|
||||
const headers = {
|
||||
'Content-Type': 'application/json',
|
||||
'accept': '*/*',
|
||||
...options.headers
|
||||
};
|
||||
if (config.apiKey) {
|
||||
headers['X-Api-Key'] = config.apiKey;
|
||||
}
|
||||
|
||||
console.log(`[WAHA] ${options.method || 'GET'} ${url}`, options.body ? JSON.parse(options.body) : '');
|
||||
|
||||
const response = await fetch(url, { ...options, headers });
|
||||
if (!response.ok) {
|
||||
let errorDetail = '';
|
||||
try {
|
||||
const errBody = await response.json();
|
||||
errorDetail = JSON.stringify(errBody);
|
||||
console.error(`[WAHA] Error response body:`, errBody);
|
||||
} catch (_) {
|
||||
errorDetail = await response.text().catch(() => '');
|
||||
}
|
||||
throw new Error(`WAHA API returned ${response.status}: ${response.statusText} — ${errorDetail}`);
|
||||
}
|
||||
return response.json();
|
||||
}
|
||||
|
||||
export const waha = {
|
||||
async getVersion() {
|
||||
return request('/api/version');
|
||||
},
|
||||
|
||||
async getChats() {
|
||||
const data = await request(`/api/${config.session}/chats`);
|
||||
return data.map(chat => {
|
||||
let chatId = chat.id;
|
||||
if (chatId && typeof chatId === "object") {
|
||||
chatId = chatId._serialized || chatId.user || JSON.stringify(chatId);
|
||||
}
|
||||
return {
|
||||
id: chatId || chat.chatId || chat.name,
|
||||
name: chat.name || "Unknown Contact",
|
||||
unreadCount: chat.unreadCount || 0,
|
||||
lastMessage: chat.lastMessage?.body || chat.lastMessageText || "Click to open chat",
|
||||
timestamp: chat.lastMessage?.timestamp || new Date()
|
||||
};
|
||||
});
|
||||
},
|
||||
|
||||
async getChatMessages(chatId) {
|
||||
return request(`/api/${config.session}/chats/${chatId}/messages?downloadMedia=false&limit=40`);
|
||||
},
|
||||
|
||||
async readChat(chatId) {
|
||||
return request('/api/sendSeen', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ chatId, session: config.session })
|
||||
});
|
||||
},
|
||||
|
||||
async getMyInfo() {
|
||||
return request(`/api/sessions/${config.session}/me`);
|
||||
},
|
||||
|
||||
async startTyping(chatId) {
|
||||
return request('/api/startTyping', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ chatId, session: config.session })
|
||||
});
|
||||
},
|
||||
|
||||
async stopTyping(chatId) {
|
||||
return request('/api/stopTyping', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ chatId, session: config.session })
|
||||
});
|
||||
},
|
||||
|
||||
async sendTextMessage(chatId, text) {
|
||||
return request('/api/sendText', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
chatId,
|
||||
text,
|
||||
session: config.session
|
||||
})
|
||||
});
|
||||
}
|
||||
};
|
||||
93
public/websocket.js
Normal file
93
public/websocket.js
Normal file
|
|
@ -0,0 +1,93 @@
|
|||
import { config } from "./config.js";
|
||||
|
||||
let socket = null;
|
||||
let reconnectTimer = null;
|
||||
let currentOnMessageCallback = null;
|
||||
|
||||
export const websocket = {
|
||||
connect(onMessageCallback) {
|
||||
currentOnMessageCallback = onMessageCallback;
|
||||
|
||||
this.disconnect(false);
|
||||
|
||||
const httpUrl = config.wahaUrl;
|
||||
if (!httpUrl) {
|
||||
console.warn('[WS] Config wahaUrl is empty. Cannot connect.');
|
||||
return;
|
||||
}
|
||||
|
||||
let wsUrl = httpUrl.replace(/^http:/i, 'ws:').replace(/^https:/i, 'wss:');
|
||||
wsUrl = wsUrl.replace(/\/$/, '') + '/ws';
|
||||
|
||||
const apiKey = config.apiKey;
|
||||
const session = config.session;
|
||||
const events = ['session.status', 'message', 'message.any'];
|
||||
|
||||
const queryParams = new URLSearchParams();
|
||||
if (apiKey) {
|
||||
queryParams.append('x-api-key', apiKey);
|
||||
}
|
||||
queryParams.append('session', session);
|
||||
events.forEach(event => queryParams.append('events', event));
|
||||
|
||||
const fullWsUrl = `${wsUrl}?${queryParams.toString()}`;
|
||||
console.log('[WS] Connecting to:', fullWsUrl);
|
||||
|
||||
try {
|
||||
socket = new WebSocket(fullWsUrl);
|
||||
|
||||
socket.onopen = () => {
|
||||
console.log('[WS] Connection successfully established');
|
||||
if (reconnectTimer) {
|
||||
clearTimeout(reconnectTimer);
|
||||
reconnectTimer = null;
|
||||
}
|
||||
};
|
||||
|
||||
socket.onmessage = (event) => {
|
||||
try {
|
||||
const data = JSON.parse(event.data);
|
||||
if (currentOnMessageCallback) {
|
||||
currentOnMessageCallback(data);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('[WS] Failed to parse message JSON:', e);
|
||||
}
|
||||
};
|
||||
|
||||
socket.onerror = (error) => {
|
||||
console.error('[WS] WebSocket Error occurred:', error);
|
||||
};
|
||||
|
||||
socket.onclose = (event) => {
|
||||
console.log(`[WS] Connection closed (code: ${event.code}). Reconnecting in 5 seconds...`);
|
||||
socket = null;
|
||||
|
||||
reconnectTimer = setTimeout(() => {
|
||||
this.connect(currentOnMessageCallback);
|
||||
}, 5000);
|
||||
};
|
||||
} catch (e) {
|
||||
console.error('[WS] Failed to initialize WebSocket client:', e);
|
||||
}
|
||||
},
|
||||
|
||||
disconnect(clearCallback = true) {
|
||||
if (reconnectTimer) {
|
||||
clearTimeout(reconnectTimer);
|
||||
reconnectTimer = null;
|
||||
}
|
||||
if (clearCallback) {
|
||||
currentOnMessageCallback = null;
|
||||
}
|
||||
if (socket) {
|
||||
socket.onclose = null;
|
||||
socket.onerror = null;
|
||||
socket.onopen = null;
|
||||
socket.onmessage = null;
|
||||
socket.close();
|
||||
socket = null;
|
||||
console.log('[WS] Connection closed explicitly');
|
||||
}
|
||||
}
|
||||
};
|
||||
77
wahaService.js
Normal file
77
wahaService.js
Normal file
|
|
@ -0,0 +1,77 @@
|
|||
import axios from "axios";
|
||||
|
||||
const session = "session_01kxc62bk5fs8vh4v127k88a7j";
|
||||
const wahaBaseUrl = "http://inspiran.beetal-castor.ts.net:3100";
|
||||
const apiKey = process.env.WAHA_API_KEY;
|
||||
|
||||
const client = axios.create({
|
||||
baseURL: wahaBaseUrl,
|
||||
headers: {
|
||||
"X-API-KEY": apiKey,
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
});
|
||||
|
||||
export const wahaService = {
|
||||
getConfigStatus() {
|
||||
return {
|
||||
wahaBaseUrl,
|
||||
session,
|
||||
hasApiKey: !!apiKey
|
||||
};
|
||||
},
|
||||
|
||||
async getChats() {
|
||||
const response = await client.get(`/api/${session}/chats`, { timeout: 5000 });
|
||||
|
||||
if (!Array.isArray(response.data)) {
|
||||
throw new Error("Invalid chats response format from WAHA API");
|
||||
}
|
||||
|
||||
return response.data.map(chat => {
|
||||
let chatId = chat.id;
|
||||
if (chatId && typeof chatId === "object") {
|
||||
chatId = chatId._serialized || chatId.user || JSON.stringify(chatId);
|
||||
}
|
||||
return {
|
||||
id: chatId || chat.chatId || chat.name,
|
||||
name: chat.name || "Unknown Contact",
|
||||
unreadCount: chat.unreadCount || 0,
|
||||
lastMessage: chat.lastMessage?.body || chat.lastMessageText || "Click to open chat",
|
||||
timestamp: chat.lastMessage?.timestamp || new Date()
|
||||
};
|
||||
});
|
||||
},
|
||||
|
||||
async getChatMessages(chatId) {
|
||||
const response = await client.get(`/api/${session}/chats/${chatId}/messages?downloadMedia=false&merge=true&limit=10`);
|
||||
return response.data;
|
||||
},
|
||||
|
||||
async getMyInfo(chatId) {
|
||||
const response = await client.get(`/api/${session}/me`);
|
||||
return response.data;
|
||||
},
|
||||
|
||||
async startTyping(chatId) {
|
||||
await client.post("/api/startTyping", {
|
||||
chatId,
|
||||
session
|
||||
}, { timeout: 3000 });
|
||||
},
|
||||
|
||||
async stopTyping(chatId) {
|
||||
await client.post("/api/stopTyping", {
|
||||
chatId,
|
||||
session
|
||||
}, { timeout: 2000 });
|
||||
},
|
||||
|
||||
async sendTextMessage(chatId, text) {
|
||||
const response = await client.post("/api/sendText", {
|
||||
chatId,
|
||||
text
|
||||
});
|
||||
return response.data;
|
||||
}
|
||||
};
|
||||
Loading…
Add table
Add a link
Reference in a new issue