// =================================================== // InfinityChat - Secure Real-Time Messaging // Vanilla JavaScript Frontend // =================================================== (function() { 'use strict'; // ==================================== // State Management // ==================================== const State = { token: localStorage.getItem('token'), user: null, ws: null, wsState: 'disconnected', // disconnected | connecting | connected | reconnecting messages: new Map(), // id -> message object messageOrder: [], // ordered IDs for rendering cursor: null, // oldest message ID currently loaded hasMore: true, replyTo: null, // message being replied to pendingFile: null, // uploaded file awaiting send typingUsers: new Map(), onlineUsers: new Map(), isAtBottom: true, theme: localStorage.getItem('theme') || 'light', customColors: { self: localStorage.getItem('custom-self') || '#2563EB', other: localStorage.getItem('custom-other') || '#F3F4F6', text: localStorage.getItem('custom-text') || '#111827' } }; // ==================================== // DOM Elements Cache // ==================================== const DOM = { // Screens authScreen: document.getElementById('auth-screen'), chatScreen: document.getElementById('chat-screen'), // Auth loginForm: document.getElementById('login-form'), signupForm: document.getElementById('signup-form'), authTabs: document.querySelectorAll('.auth-tab'), authError: document.getElementById('auth-error'), authErrorText: document.getElementById('auth-error-text'), authLoading: document.getElementById('auth-loading'), // Chat Header headerDisplayName: document.getElementById('header-display-name'), headerAvatar: document.getElementById('header-avatar'), headerAvatarPlaceholder: document.getElementById('header-avatar-placeholder'), headerStatus: document.getElementById('header-status'), onlineBadge: document.getElementById('online-badge'), // Connection connectionStatus: document.getElementById('connection-status'), connectionText: document.getElementById('connection-text'), // Messages messagesList: document.getElementById('messages-list'), messagesScroll: document.getElementById('messages-scroll'), emptyState: document.getElementById('empty-state'), loadOlderBtn: document.getElementById('load-older-btn'), scrollBottomBtn: document.getElementById('scroll-bottom-btn'), // Typing typingIndicator: document.getElementById('typing-indicator'), typingText: document.getElementById('typing-text'), // Reply replyPreview: document.getElementById('reply-preview'), replyUser: document.getElementById('reply-user'), replyText: document.getElementById('reply-text'), // Compose composeForm: document.getElementById('compose-form'), messageInput: document.getElementById('message-input'), sendBtn: document.getElementById('send-btn'), attachBtn: document.getElementById('attach-btn'), emojiBtn: document.getElementById('emoji-btn'), fileInput: document.getElementById('file-input'), // Upload uploadPreview: document.getElementById('upload-preview'), uploadFilename: document.getElementById('upload-filename'), cancelUpload: document.getElementById('cancel-upload'), uploadProgress: document.getElementById('upload-progress'), progressFill: document.getElementById('progress-fill'), progressText: document.getElementById('progress-text'), // Modals settingsModal: document.getElementById('settings-modal'), onlineModal: document.getElementById('online-modal'), emojiPicker: document.getElementById('emoji-picker'), emojiGrid: document.getElementById('emoji-grid'), // Settings settingsDisplayName: document.getElementById('settings-display-name'), settingsUsername: document.getElementById('settings-username'), settingsAvatarPreview: document.getElementById('settings-avatar-preview'), settingsAvatarImg: document.getElementById('settings-avatar-img'), avatarInput: document.getElementById('avatar-input'), themeOptions: document.querySelectorAll('.theme-option'), customThemeSettings: document.getElementById('custom-theme-settings'), // Toast toastContainer: document.getElementById('toast-container') }; const API_BASE = window.location.origin; // ==================================== // Theme Management // ==================================== function applyTheme(theme) { document.documentElement.setAttribute('data-theme', theme); State.theme = theme; localStorage.setItem('theme', theme); if (theme === 'custom') { document.documentElement.style.setProperty('--bubble-self', State.customColors.self); document.documentElement.style.setProperty('--bubble-other', State.customColors.other); document.documentElement.style.setProperty('--bubble-other-text', State.customColors.text); document.documentElement.style.setProperty('--bubble-self-text', isLightColor(State.customColors.self) ? '#111827' : '#FFFFFF'); } } function isLightColor(hex) { const r = parseInt(hex.slice(1,3), 16); const g = parseInt(hex.slice(3,5), 16); const b = parseInt(hex.slice(5,7), 16); return (0.299 * r + 0.587 * g + 0.114 * b) > 150; } applyTheme(State.theme); // ==================================== // Toast Notifications // ==================================== function showToast(message, type = 'info') { const toast = document.createElement('div'); toast.className = `toast toast-${type}`; let icon = 'info-circle'; if (type === 'success') icon = 'check-circle'; if (type === 'error') icon = 'exclamation-circle'; if (type === 'warning') icon = 'exclamation-triangle'; toast.innerHTML = `${message}`; DOM.toastContainer.appendChild(toast); setTimeout(() => toast.remove(), 4000); } // ==================================== // Authentication // ==================================== DOM.authTabs.forEach(tab => { tab.addEventListener('click', () => { const target = tab.dataset.tab; DOM.authTabs.forEach(t => t.classList.remove('active')); tab.classList.add('active'); DOM.loginForm.classList.toggle('active', target === 'login'); DOM.signupForm.classList.toggle('active', target === 'signup'); DOM.authError.style.display = 'none'; }); }); DOM.loginForm.addEventListener('submit', async (e) => { e.preventDefault(); const username = document.getElementById('login-username').value.trim(); const password = document.getElementById('login-password').value; await login(username, password); }); DOM.signupForm.addEventListener('submit', async (e) => { e.preventDefault(); const username = document.getElementById('signup-username').value.trim(); const display = document.getElementById('signup-display').value.trim() || username; const password = document.getElementById('signup-password').value; await signup(username, password, display); }); async function login(username, password) { showAuthLoading(); try { const res = await fetch(`${API_BASE}/api/auth/login?username=${encodeURIComponent(username)}&password=${encodeURIComponent(password)}`, { method: 'POST' }); const data = await res.json(); if (!res.ok) throw new Error(data.detail || 'Login failed'); handleAuthSuccess(data); } catch (err) { showAuthError(err.message); } finally { hideAuthLoading(); } } async function signup(username, password, display) { showAuthLoading(); try { const res = await fetch(`${API_BASE}/api/auth/signup?username=${encodeURIComponent(username)}&password=${encodeURIComponent(password)}&display_name=${encodeURIComponent(display)}`, { method: 'POST' }); const data = await res.json(); if (!res.ok) throw new Error(data.detail || 'Signup failed'); handleAuthSuccess(data); } catch (err) { showAuthError(err.message); } finally { hideAuthLoading(); } } function handleAuthSuccess(data) { State.token = data.token; State.user = data.user; localStorage.setItem('token', State.token); showChat(); connectWebSocket(); } function showAuthLoading() { DOM.authLoading.classList.remove('hidden'); DOM.authError.style.display = 'none'; } function hideAuthLoading() { DOM.authLoading.classList.add('hidden'); } function showAuthError(msg) { DOM.authErrorText.textContent = msg; DOM.authError.style.display = 'flex'; } // ==================================== // WebSocket Connection // ==================================== function connectWebSocket() { if (State.ws && State.ws.readyState === WebSocket.OPEN) return; if (!State.token) return; State.wsState = 'connecting'; updateConnectionUI(); const proto = location.protocol === 'https:' ? 'wss:' : 'ws:'; const url = `${proto}//${location.host}/ws?token=${encodeURIComponent(State.token)}`; State.ws = new WebSocket(url); State.ws.onopen = () => { State.wsState = 'connected'; updateConnectionUI(); loadMessages(); requestOnlineUsers(); }; State.ws.onmessage = (event) => handleWSMessage(JSON.parse(event.data)); State.ws.onclose = () => { if (State.wsState === 'connected') { State.wsState = 'reconnecting'; updateConnectionUI(); setTimeout(connectWebSocket, 3000); } else { State.wsState = 'disconnected'; updateConnectionUI(); } }; State.ws.onerror = () => { State.wsState = 'disconnected'; updateConnectionUI(); }; } function updateConnectionUI() { const status = DOM.connectionStatus; const text = DOM.connectionText; status.className = 'connection-status'; switch (State.wsState) { case 'connected': status.classList.add('connected'); text.textContent = 'Connected'; break; case 'connecting': case 'reconnecting': status.classList.add('reconnecting'); text.textContent = State.wsState === 'reconnecting' ? 'Reconnecting...' : 'Connecting...'; break; default: status.classList.add('disconnected'); text.textContent = 'Disconnected - trying to reconnect...'; break; } } // ==================================== // WebSocket Message Handler // ==================================== function handleWSMessage(msg) { switch (msg.type) { case 'connection_established': State.user = { id: msg.user_id, username: msg.username, display_name: msg.display_name, avatar_path: msg.avatar_path }; msg.online_users.forEach(u => State.onlineUsers.set(u.id, u)); updateOnlineBadge(); updateHeaderInfo(); break; case 'new_message': handleNewMessage(msg.message); break; case 'messages_loaded': handleMessagesLoaded(msg.messages, msg.has_more); State.hasMore = msg.has_more; if (msg.next_cursor) State.cursor = msg.next_cursor; DOM.loadOlderBtn.classList.toggle('hidden', !msg.has_more); break; case 'user_status': if (msg.status === 'online') { State.onlineUsers.set(msg.user_id, { id: msg.user_id, username: msg.username, display_name: msg.display_name, avatar_path: msg.avatar_path }); } else { State.onlineUsers.delete(msg.user_id); } updateOnlineBadge(); break; case 'typing_indicator': if (msg.is_typing) { State.typingUsers.set(msg.user_id, msg); } else { State.typingUsers.delete(msg.user_id); } updateTypingIndicator(); break; case 'message_edited': handleMessageEdit(msg.message_id, msg.content, msg.editor_id); break; case 'message_deleted': handleMessageDelete(msg.message_id); break; case 'message_read': handleMessageRead(msg.message_id, msg.reader_username); break; case 'online_users': State.onlineUsers.clear(); msg.users.forEach(u => State.onlineUsers.set(u.id, u)); updateOnlineBadge(); break; case 'error': showToast(msg.message, 'error'); break; } } // ==================================== // Message Handling // ==================================== function handleNewMessage(message) { if (State.messages.has(message.id)) return; State.messages.set(message.id, message); State.messageOrder.push(message.id); renderMessage(message); scrollToBottom(); // Mark as read if visible if (document.visibilityState === 'visible') { sendMarkRead(message.id); } // Browser notification if tab not focused if (document.visibilityState !== 'visible' && Notification.permission === 'granted') { const sender = message.sender_display_name || message.sender_username; const body = message.content || (message.file_path ? 'Sent a file' : 'New message'); new Notification(`📨 ${sender}`, { body, icon: '/static/icon.png' }); } } function handleMessagesLoaded(msgs, hasMore) { msgs.forEach(msg => { if (!State.messages.has(msg.id)) { State.messages.set(msg.id, msg); State.messageOrder.unshift(msg.id); } }); renderAllMessages(); // Keep scroll position } function handleMessageEdit(messageId, newContent, editorId) { const msg = State.messages.get(messageId); if (msg) { msg.content = newContent; msg.is_edited = true; updateMessageBubble(messageId); } } function handleMessageDelete(messageId) { const msg = State.messages.get(messageId); if (msg) { msg.is_deleted = true; updateMessageBubble(messageId); } } function handleMessageRead(messageId, readerUsername) { const msg = State.messages.get(messageId); if (msg && msg.sender_id === State.user.id) { msg.status = 'read'; updateMessageBubble(messageId); } } // ==================================== // Message Rendering // ==================================== function renderMessage(msg) { if (State.messagesList.querySelector(`[data-id="${msg.id}"]`)) return; const wrapper = document.createElement('div'); wrapper.className = `message-wrapper ${msg.sender_id === State.user.id ? 'self' : 'other'}`; wrapper.dataset.id = msg.id; wrapper.innerHTML = buildMessageHTML(msg); State.messagesList.appendChild(wrapper); } function buildMessageHTML(msg) { if (msg.is_deleted) { return `
This message was deleted
`; } const isSelf = msg.sender_id === State.user?.id; let html = ''; // Reply indicator if (msg.reply_to_id && State.messages.has(msg.reply_to_id)) { const reply = State.messages.get(msg.reply_to_id); html += `
${reply.sender_username}: ${truncate(reply.content, 50)}
`; } // Bubble content html += `
`; html += `
${escapeHtml(msg.content)}
`; // Attachment if (msg.file_path) { html += buildAttachmentHTML(msg); } // Meta html += `
${formatTime(msg.timestamp_ms)}`; if (msg.is_edited) html += `edited`; if (isSelf) { const checkIcon = msg.status === 'read' ? '' : ''; html += `${checkIcon}`; } html += `
`; // Actions html += `
`; if (isSelf) { html += ` `; } html += `
`; html += `
`; return html; } function buildAttachmentHTML(msg) { const url = `${API_BASE}/api/download/${encodeURIComponent(msg.file_path)}?token=${encodeURIComponent(State.token)}`; if (msg.file_type?.startsWith('image/')) { return `
${msg.file_name}
`; } if (msg.file_type?.startsWith('video/')) { return `
`; } if (msg.file_type?.startsWith('audio/')) { return `
`; } return `
${msg.file_name || 'File'}
${formatFileSize(msg.file_size)}
`; } function updateMessageBubble(messageId) { const existing = State.messagesList.querySelector(`[data-id="${messageId}"]`); if (!existing) return; const msg = State.messages.get(messageId); if (!msg) return; existing.innerHTML = buildMessageHTML(msg); } function renderAllMessages() { State.messagesList.innerHTML = ''; if (State.messageOrder.length === 0) { State.emptyState.style.display = 'flex'; } else { State.emptyState.style.display = 'none'; State.messageOrder.forEach(id => { const msg = State.messages.get(id); if (msg) renderMessage(msg); }); } } // ==================================== // Sending Messages // ==================================== DOM.composeForm.addEventListener('submit', (e) => { e.preventDefault(); sendMessage(); }); function sendMessage() { const content = DOM.messageInput.value.trim(); if (!content && !State.pendingFile) return; if (!State.ws || State.ws.readyState !== WebSocket.OPEN) return; const payload = { type: 'send_message', content: content, reply_to_id: State.replyTo ? State.replyTo.id : null, client_id: generateClientId() }; if (State.pendingFile) { payload.file_path = State.pendingFile.file_path; payload.file_type = State.pendingFile.file_type; payload.file_name = State.pendingFile.file_name; payload.file_size = State.pendingFile.file_size; } State.ws.send(JSON.stringify(payload)); DOM.messageInput.value = ''; clearReply(); clearPendingFile(); autoResizeTextarea(); sendTyping(false); } DOM.sendBtn.disabled = true; DOM.messageInput.addEventListener('input', () => { const hasContent = DOM.messageInput.value.trim().length > 0 || State.pendingFile !== null; DOM.sendBtn.disabled = !hasContent; if (hasContent) sendTyping(true); autoResizeTextarea(); }); // ==================================== // Typing Indicator // ==================================== let typingTimer = null; function sendTyping(isTyping) { if (isTyping) { clearTimeout(typingTimer); if (State.ws?.readyState === WebSocket.OPEN) { State.ws.send(JSON.stringify({ type: 'typing', is_typing: true })); } typingTimer = setTimeout(() => sendTyping(false), 2000); } else { clearTimeout(typingTimer); if (State.ws?.readyState === WebSocket.OPEN) { State.ws.send(JSON.stringify({ type: 'typing', is_typing: false })); } } } function updateTypingIndicator() { const users = Array.from(State.typingUsers.values()).filter(u => u.user_id !== State.user.id); DOM.typingIndicator.classList.toggle('hidden', users.length === 0); if (users.length > 0) { DOM.typingText.textContent = users.map(u => u.display_name).join(', ') + ' typing...'; } } // ==================================== // Reply // ==================================== function replyTo(messageId) { const msg = State.messages.get(messageId); if (!msg) return; State.replyTo = msg; DOM.replyUser.textContent = msg.sender_username; DOM.replyText.textContent = truncate(msg.content, 50); DOM.replyPreview.classList.remove('hidden'); DOM.messageInput.focus(); } function clearReply() { State.replyTo = null; DOM.replyPreview.classList.add('hidden'); } document.addEventListener('click', (e) => { if (e.target.id === 'cancel-reply') clearReply(); }); // ==================================== // Edit & Delete // ==================================== function editMessage(messageId) { const msg = State.messages.get(messageId); if (!msg) return; const newContent = prompt('Edit message:', msg.content); if (newContent !== null && newContent.trim() !== '') { State.ws.send(JSON.stringify({ type: 'edit_message', message_id: messageId, content: newContent })); } } function deleteMessage(messageId) { if (confirm('Delete this message permanently?')) { State.ws.send(JSON.stringify({ type: 'delete_message', message_id: messageId })); } } // ==================================== // File Upload (Chunked) // ==================================== DOM.attachBtn.addEventListener('click', () => DOM.fileInput.click()); DOM.fileInput.addEventListener('change', handleFileSelect); async function handleFileSelect(e) { const file = e.target.files[0]; if (!file) return; await uploadFileChunked(file); DOM.fileInput.value = ''; } async function uploadFileChunked(file) { const CHUNK_SIZE = 5 * 1024 * 1024; // 5MB const totalChunks = Math.ceil(file.size / CHUNK_SIZE); const uploadId = generateClientId(); DOM.uploadProgress.classList.remove('hidden'); updateProgress(0, file.name); for (let i = 0; i < totalChunks; i++) { const start = i * CHUNK_SIZE; const end = Math.min(start + CHUNK_SIZE, file.size); const blob = file.slice(start, end); const formData = new FormData(); formData.append('file', blob); const url = `${API_BASE}/api/upload/chunk?` + `chunk_index=${i}&total_chunks=${totalChunks}` + `&file_name=${encodeURIComponent(file.name)}` + `&file_type=${encodeURIComponent(file.type || 'application/octet-stream')}` + `&file_size=${file.size}&upload_id=${uploadId}`; const res = await fetch(url, { method: 'POST', body: formData, headers: { 'X-Auth-Token': State.token } }); if (!res.ok) throw new Error('Upload failed'); const data = await res.json(); if (data.status === 'complete') { State.pendingFile = { file_path: data.file_path, file_type: data.file_type, file_name: data.file_name, file_size: data.file_size }; showUploadPreview(data.file_name); DOM.uploadProgress.classList.add('hidden'); return; } updateProgress(((i + 1) / totalChunks) * 100, file.name); } DOM.uploadProgress.classList.add('hidden'); } function updateProgress(percent, filename) { DOM.progressFill.style.width = `${percent}%`; DOM.progressText.textContent = `${Math.round(percent)}%`; DOM.uploadFilename.textContent = filename; } function showUploadPreview(filename) { DOM.uploadPreview.classList.remove('hidden'); DOM.uploadFilename.textContent = filename; DOM.sendBtn.disabled = false; } function clearPendingFile() { State.pendingFile = null; DOM.uploadPreview.classList.add('hidden'); } document.getElementById('cancel-upload').addEventListener('click', clearPendingFile); // ==================================== // Messages Loading & Pagination // ==================================== function loadMessages() { if (!State.ws || State.ws.readyState !== WebSocket.OPEN) return; State.ws.send(JSON.stringify({ type: 'load_messages', limit: 50 })); } DOM.loadOlderBtn.addEventListener('click', () => { if (State.cursor && State.hasMore) { State.ws.send(JSON.stringify({ type: 'load_messages', cursor: State.cursor, limit: 50 })); } }); // Scroll detection for load more and auto-scroll behavior DOM.messagesScroll.addEventListener('scroll', () => { const { scrollTop, scrollHeight, clientHeight } = DOM.messagesScroll; State.isAtBottom = scrollHeight - scrollTop - clientHeight < 60; DOM.scrollBottomBtn.classList.toggle('hidden', State.isAtBottom); }); DOM.scrollBottomBtn.addEventListener('click', scrollToBottom); function scrollToBottom() { DOM.messagesScroll.scrollTop = DOM.messagesScroll.scrollHeight; } // ==================================== // Online Users Modal // ==================================== function requestOnlineUsers() { if (State.ws?.readyState === WebSocket.OPEN) { State.ws.send(JSON.stringify({ type: 'get_online_users' })); } } function updateOnlineBadge() { DOM.onlineBadge.textContent = State.onlineUsers.size; } // ==================================== // Settings Modal // ==================================== document.getElementById('settings-btn').addEventListener('click', openSettings); document.getElementById('save-settings').addEventListener('click', saveSettings); function openSettings() { DOM.settingsDisplayName.value = State.user?.display_name || ''; DOM.settingsUsername.value = State.user?.username || ''; if (State.user?.avatar_path) { DOM.settingsAvatarImg.src = `${API_BASE}/api/download/${encodeURIComponent(State.user.avatar_path)}?token=${encodeURIComponent(State.token)}`; DOM.settingsAvatarImg.classList.remove('hidden'); DOM.settingsAvatarPreview.classList.add('hidden'); } else { DOM.settingsAvatarImg.classList.add('hidden'); DOM.settingsAvatarPreview.classList.remove('hidden'); } DOM.themeOptions.forEach(opt => opt.classList.toggle('active', opt.dataset.theme === State.theme)); DOM.customThemeSettings.classList.toggle('hidden', State.theme !== 'custom'); DOM.settingsModal.classList.remove('hidden'); } async function saveSettings() { const newName = DOM.settingsDisplayName.value.trim(); if (newName && newName !== State.user?.display_name) { const res = await fetch(`${API_BASE}/api/profile?display_name=${encodeURIComponent(newName)}`, { method: 'PATCH', headers: { 'X-Auth-Token': State.token } }); if (res.ok) { State.user.display_name = newName; DOM.headerDisplayName.textContent = newName; showToast('Profile updated', 'success'); } } DOM.settingsModal.classList.add('hidden'); } // ==================================== // Theme Switching // ==================================== DOM.themeOptions.forEach(opt => { opt.addEventListener('click', () => { DOM.themeOptions.forEach(o => o.classList.remove('active')); opt.classList.add('active'); applyTheme(opt.dataset.theme); DOM.customThemeSettings.classList.toggle('hidden', opt.dataset.theme !== 'custom'); }); }); // ==================================== // Utility Functions // ==================================== function generateClientId() { return Date.now().toString(36) + Math.random().toString(36).substr(2, 9); } function truncate(str, n) { if (!str) return ''; return str.length > n ? str.substr(0, n - 1) + '…' : str; } function escapeHtml(text) { const div = document.createElement('div'); div.textContent = text; return div.innerHTML; } function formatTime(ms) { const date = new Date(ms); const now = new Date(); const diff = now - date; if (diff < 60000) return 'Just now'; if (diff < 3600000) return Math.floor(diff / 60000) + 'm ago'; if (date.toDateString() === now.toDateString()) return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }); return date.toLocaleDateString([], { month: 'short', day: 'numeric' }) + ' ' + date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }); } function formatFileSize(bytes) { if (!bytes) return '0 B'; const k = 1024; const sizes = ['B', 'KB', 'MB', 'GB']; const i = Math.floor(Math.log(bytes) / Math.log(k)); return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i]; } function autoResizeTextarea() { DOM.messageInput.style.height = 'auto'; DOM.messageInput.style.height = Math.min(DOM.messageInput.scrollHeight, 120) + 'px'; } // Expose public methods window.InfinityChat = { replyTo, editMessage, deleteMessage }; // ==================================== // Initialization // ==================================== async function init() { if (State.token) { const res = await fetch(`${API_BASE}/api/auth/verify`, { headers: { 'X-Auth-Token': State.token } }); if (res.ok) { const data = await res.json(); State.user = data.user; showChat(); connectWebSocket(); return; } } showAuth(); } function showAuth() { DOM.authScreen.classList.add('active'); DOM.chatScreen.classList.remove('active'); } function showChat() { DOM.authScreen.classList.remove('active'); DOM.chatScreen.classList.add('active'); updateHeaderInfo(); } function updateHeaderInfo() { if (State.user) { DOM.headerDisplayName.textContent = State.user.display_name; } } // Close modals on backdrop click document.querySelectorAll('.modal-backdrop').forEach(backdrop => { backdrop.addEventListener('click', () => { const modal = backdrop.closest('.modal'); modal.classList.add('hidden'); }); }); // Request notification permission if (window.Notification && Notification.permission === 'default') { Notification.requestPermission(); } // Handle online/offline DOM.onlineBtn.addEventListener('click', () => { requestOnlineUsers(); DOM.onlineModal.classList.remove('hidden'); }); init(); })();