Remove hardcodes and implement WebClient
This commit is contained in:
parent
f25ba8adcd
commit
c316ef0092
11 changed files with 2062 additions and 75 deletions
676
src/GsDChat.Server/wwwroot/app.js
Normal file
676
src/GsDChat.Server/wwwroot/app.js
Normal file
|
|
@ -0,0 +1,676 @@
|
|||
(() => {
|
||||
// Application State
|
||||
const state = {
|
||||
token: localStorage.getItem('gsdchat_token') || null,
|
||||
user: JSON.parse(localStorage.getItem('gsdchat_user') || 'null'),
|
||||
serverInfo: null,
|
||||
activeChannelId: null,
|
||||
channels: [],
|
||||
messages: {}, // channelId -> array
|
||||
users: [],
|
||||
files: [],
|
||||
socket: null,
|
||||
isRegister: false,
|
||||
reconnectTimer: null
|
||||
};
|
||||
|
||||
// DOM Elements
|
||||
const el = {
|
||||
serverTitle: document.getElementById('serverTitle'),
|
||||
connIndicator: document.getElementById('connIndicator'),
|
||||
navTabs: document.querySelectorAll('.nav-tab'),
|
||||
tabViews: document.querySelectorAll('.tab-view'),
|
||||
currentUsername: document.getElementById('currentUsername'),
|
||||
currentUserRole: document.getElementById('currentUserRole'),
|
||||
logoutBtn: document.getElementById('logoutBtn'),
|
||||
userBadge: document.getElementById('userBadge'),
|
||||
|
||||
// Chat View
|
||||
activeChannelName: document.getElementById('activeChannelName'),
|
||||
activeChannelTopic: document.getElementById('activeChannelTopic'),
|
||||
chatMessages: document.getElementById('chatMessages'),
|
||||
messageInput: document.getElementById('messageInput'),
|
||||
sendBtn: document.getElementById('sendBtn'),
|
||||
fileInput: document.getElementById('fileInput'),
|
||||
welcomeMotd: document.getElementById('welcomeMotd'),
|
||||
|
||||
// Channels View
|
||||
channelList: document.getElementById('channelList'),
|
||||
openCreateChannelBtn: document.getElementById('openCreateChannelBtn'),
|
||||
createChannelCard: document.getElementById('createChannelCard'),
|
||||
newChannelName: document.getElementById('newChannelName'),
|
||||
newChannelTopic: document.getElementById('newChannelTopic'),
|
||||
submitCreateChannelBtn: document.getElementById('submitCreateChannelBtn'),
|
||||
cancelCreateChannelBtn: document.getElementById('cancelCreateChannelBtn'),
|
||||
|
||||
// Users View
|
||||
userList: document.getElementById('userList'),
|
||||
userCountBadge: document.getElementById('userCountBadge'),
|
||||
|
||||
// Files View
|
||||
filesList: document.getElementById('filesList'),
|
||||
filesViewUploadInput: document.getElementById('filesViewUploadInput'),
|
||||
|
||||
// Auth Modal
|
||||
authModal: document.getElementById('authModal'),
|
||||
modalServerName: document.getElementById('modalServerName'),
|
||||
modalMotd: document.getElementById('modalMotd'),
|
||||
tabLogin: document.getElementById('tabLogin'),
|
||||
tabRegister: document.getElementById('tabRegister'),
|
||||
authForm: document.getElementById('authForm'),
|
||||
groupServerPassword: document.getElementById('groupServerPassword'),
|
||||
groupInviteToken: document.getElementById('groupInviteToken'),
|
||||
authServerPassword: document.getElementById('authServerPassword'),
|
||||
authUsername: document.getElementById('authUsername'),
|
||||
authPassword: document.getElementById('authPassword'),
|
||||
authInviteToken: document.getElementById('authInviteToken'),
|
||||
authSubmitBtn: document.getElementById('authSubmitBtn'),
|
||||
authError: document.getElementById('authError'),
|
||||
toastContainer: document.getElementById('toastContainer')
|
||||
};
|
||||
|
||||
// ==========================================
|
||||
// Initialization
|
||||
// ==========================================
|
||||
async function init() {
|
||||
setupEventListeners();
|
||||
await fetchServerInfo();
|
||||
|
||||
if (state.token && state.user) {
|
||||
updateUserUI();
|
||||
hideAuthModal();
|
||||
connectWebSocket();
|
||||
} else {
|
||||
showAuthModal();
|
||||
}
|
||||
}
|
||||
|
||||
// ==========================================
|
||||
// REST API Calls
|
||||
// ==========================================
|
||||
async function fetchServerInfo() {
|
||||
try {
|
||||
const res = await fetch('/api/info');
|
||||
if (res.ok) {
|
||||
state.serverInfo = await res.json();
|
||||
el.serverTitle.textContent = state.serverInfo.serverName || 'GsDChat';
|
||||
el.modalServerName.textContent = state.serverInfo.serverName || 'GsDChat';
|
||||
if (state.serverInfo.motd) {
|
||||
el.modalMotd.textContent = state.serverInfo.motd;
|
||||
el.welcomeMotd.textContent = state.serverInfo.motd;
|
||||
}
|
||||
if (state.serverInfo.requiresServerPassword) {
|
||||
el.groupServerPassword.style.display = 'flex';
|
||||
}
|
||||
if (state.serverInfo.registrationMode === 'InviteOnly') {
|
||||
el.groupInviteToken.style.display = 'flex';
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
showToast('Could not reach server info endpoint');
|
||||
}
|
||||
}
|
||||
|
||||
async function handleAuthSubmit() {
|
||||
el.authError.textContent = '';
|
||||
const username = el.authUsername.value.trim();
|
||||
const password = el.authPassword.value;
|
||||
const serverPassword = el.authServerPassword.value;
|
||||
const inviteToken = el.authInviteToken.value.trim();
|
||||
|
||||
if (!username || !password) {
|
||||
el.authError.textContent = 'Please enter username and password.';
|
||||
return;
|
||||
}
|
||||
|
||||
const endpoint = state.isRegister ? '/api/auth/register' : '/api/auth/login';
|
||||
const body = {
|
||||
username,
|
||||
password,
|
||||
serverPassword: serverPassword || null,
|
||||
inviteToken: inviteToken || null
|
||||
};
|
||||
|
||||
try {
|
||||
el.authSubmitBtn.disabled = true;
|
||||
el.authSubmitBtn.textContent = 'Authenticating...';
|
||||
|
||||
const res = await fetch(endpoint, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body)
|
||||
});
|
||||
|
||||
const data = await res.json();
|
||||
if (!res.ok || !data.success) {
|
||||
el.authError.textContent = data.errorMessage || 'Authentication failed.';
|
||||
return;
|
||||
}
|
||||
|
||||
// Success
|
||||
state.token = data.token;
|
||||
state.user = {
|
||||
id: data.userId,
|
||||
username: data.username,
|
||||
role: data.role
|
||||
};
|
||||
|
||||
localStorage.setItem('gsdchat_token', state.token);
|
||||
localStorage.setItem('gsdchat_user', JSON.stringify(state.user));
|
||||
|
||||
updateUserUI();
|
||||
hideAuthModal();
|
||||
connectWebSocket();
|
||||
} catch (err) {
|
||||
el.authError.textContent = 'Connection error. Please try again.';
|
||||
} finally {
|
||||
el.authSubmitBtn.disabled = false;
|
||||
el.authSubmitBtn.textContent = state.isRegister ? 'Register' : 'Login';
|
||||
}
|
||||
}
|
||||
|
||||
// ==========================================
|
||||
// WebSocket Communication
|
||||
// ==========================================
|
||||
function connectWebSocket() {
|
||||
if (state.socket) {
|
||||
state.socket.close();
|
||||
}
|
||||
|
||||
const wsProto = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||
const wsUrl = `${wsProto}//${window.location.host}/ws?token=${encodeURIComponent(state.token)}`;
|
||||
|
||||
try {
|
||||
state.socket = new WebSocket(wsUrl);
|
||||
|
||||
state.socket.onopen = () => {
|
||||
el.connIndicator.classList.add('online');
|
||||
el.connIndicator.title = 'Connected';
|
||||
showToast('Connected to chat server');
|
||||
};
|
||||
|
||||
state.socket.onclose = () => {
|
||||
el.connIndicator.classList.remove('online');
|
||||
el.connIndicator.title = 'Disconnected';
|
||||
// Auto-reconnect after 3 seconds if logged in
|
||||
if (state.token) {
|
||||
clearTimeout(state.reconnectTimer);
|
||||
state.reconnectTimer = setTimeout(connectWebSocket, 3000);
|
||||
}
|
||||
};
|
||||
|
||||
state.socket.onerror = () => {
|
||||
el.connIndicator.classList.remove('online');
|
||||
};
|
||||
|
||||
state.socket.onmessage = (event) => {
|
||||
try {
|
||||
const envelope = JSON.parse(event.data);
|
||||
handleNetworkEnvelope(envelope);
|
||||
} catch (err) {
|
||||
console.error('Failed to parse WebSocket message', err);
|
||||
}
|
||||
};
|
||||
} catch (err) {
|
||||
console.error('WebSocket connection error', err);
|
||||
}
|
||||
}
|
||||
|
||||
function sendEnvelope(type, payload) {
|
||||
if (!state.socket || state.socket.readyState !== WebSocket.OPEN) {
|
||||
showToast('Not connected to server');
|
||||
return;
|
||||
}
|
||||
const envelope = {
|
||||
type: type,
|
||||
payload: JSON.stringify(payload)
|
||||
};
|
||||
state.socket.send(JSON.stringify(envelope));
|
||||
}
|
||||
|
||||
function handleNetworkEnvelope(envelope) {
|
||||
const payload = JSON.parse(envelope.payload || '{}');
|
||||
|
||||
switch (envelope.type) {
|
||||
case 'CHANNEL_LIST_SYNC':
|
||||
state.channels = payload.channels || [];
|
||||
if (payload.activeChannelId) {
|
||||
state.activeChannelId = payload.activeChannelId;
|
||||
}
|
||||
renderChannels();
|
||||
updateActiveChannelHeader();
|
||||
break;
|
||||
|
||||
case 'HISTORY_SYNC':
|
||||
if (payload.channelId) {
|
||||
state.messages[payload.channelId] = payload.messages || [];
|
||||
if (state.activeChannelId === payload.channelId) {
|
||||
renderMessages();
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case 'MESSAGE_BROADCAST':
|
||||
if (payload.message) {
|
||||
const chId = payload.message.channelId;
|
||||
if (!state.messages[chId]) state.messages[chId] = [];
|
||||
state.messages[chId].push(payload.message);
|
||||
if (state.activeChannelId === chId) {
|
||||
appendMessage(payload.message);
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case 'USER_LIST_SYNC':
|
||||
state.users = payload.users || [];
|
||||
renderUsers();
|
||||
break;
|
||||
|
||||
case 'FILE_LIST_SYNC':
|
||||
state.files = payload.files || [];
|
||||
renderFiles();
|
||||
break;
|
||||
|
||||
case 'SYSTEM_NOTICE':
|
||||
if (payload.text) {
|
||||
showToast(payload.text);
|
||||
if (state.activeChannelId) {
|
||||
appendSystemNotice(payload.text);
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case 'COMMAND_RESULT':
|
||||
if (payload.output) {
|
||||
appendSystemNotice(payload.output);
|
||||
}
|
||||
break;
|
||||
|
||||
case 'ERROR':
|
||||
if (payload.message) {
|
||||
showToast(`Error: ${payload.message}`);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// ==========================================
|
||||
// UI Renderers
|
||||
// ==========================================
|
||||
function switchTab(tabName) {
|
||||
el.navTabs.forEach(tab => {
|
||||
tab.classList.toggle('active', tab.dataset.tab === tabName);
|
||||
});
|
||||
el.tabViews.forEach(view => {
|
||||
view.classList.toggle('active', view.id === `view-${tabName}`);
|
||||
});
|
||||
}
|
||||
|
||||
function updateActiveChannelHeader() {
|
||||
const active = state.channels.find(c => c.id === state.activeChannelId);
|
||||
if (active) {
|
||||
el.activeChannelName.textContent = active.name;
|
||||
el.activeChannelTopic.textContent = active.topic ? ` - ${active.topic}` : '';
|
||||
el.messageInput.placeholder = `Message #${active.name}... (or /help)`;
|
||||
}
|
||||
}
|
||||
|
||||
function renderChannels() {
|
||||
el.channelList.innerHTML = '';
|
||||
state.channels.forEach(ch => {
|
||||
const item = document.createElement('div');
|
||||
item.className = 'channel-item' + (ch.id === state.activeChannelId ? ' active' : '');
|
||||
item.innerHTML = `
|
||||
<div class="channel-meta">
|
||||
<span class="channel-title">#${escapeHtml(ch.name)}</span>
|
||||
<span class="channel-desc">${escapeHtml(ch.topic || '')}</span>
|
||||
</div>
|
||||
${ch.id === state.activeChannelId ? '<span class="channel-badge">ACTIVE</span>' : ''}
|
||||
`;
|
||||
item.addEventListener('click', () => {
|
||||
joinChannel(ch.id);
|
||||
switchTab('chat');
|
||||
});
|
||||
el.channelList.appendChild(item);
|
||||
});
|
||||
|
||||
// Show create button for Admin or Owner
|
||||
const isPrivileged = state.user && (state.user.role === 'Owner' || state.user.role === 'Admin');
|
||||
el.openCreateChannelBtn.style.display = isPrivileged ? 'inline-flex' : 'none';
|
||||
}
|
||||
|
||||
function joinChannel(channelId) {
|
||||
state.activeChannelId = channelId;
|
||||
sendEnvelope('JOIN_CHANNEL', { channelId });
|
||||
renderChannels();
|
||||
updateActiveChannelHeader();
|
||||
renderMessages();
|
||||
}
|
||||
|
||||
function renderMessages() {
|
||||
el.chatMessages.innerHTML = '';
|
||||
const msgs = state.messages[state.activeChannelId] || [];
|
||||
if (msgs.length === 0) {
|
||||
el.chatMessages.innerHTML = `
|
||||
<div class="welcome-message">
|
||||
<h3>Welcome to #${escapeHtml(el.activeChannelName.textContent)}</h3>
|
||||
<p>No messages yet. Say hello!</p>
|
||||
</div>
|
||||
`;
|
||||
return;
|
||||
}
|
||||
msgs.forEach(appendMessage);
|
||||
}
|
||||
|
||||
function appendMessage(msg) {
|
||||
const welcome = el.chatMessages.querySelector('.welcome-message');
|
||||
if (welcome) welcome.remove();
|
||||
|
||||
const time = new Date(msg.createdAt).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
|
||||
const roleClass = (msg.senderRole || 'member').toLowerCase();
|
||||
|
||||
const div = document.createElement('div');
|
||||
div.className = 'message-item';
|
||||
|
||||
let contentHtml = escapeHtml(msg.content);
|
||||
if (msg.attachmentId) {
|
||||
const sizeStr = formatBytes(msg.attachmentSizeBytes || 0);
|
||||
contentHtml += `
|
||||
<div>
|
||||
<a class="attachment-card" href="/api/files/${encodeURIComponent(msg.attachmentId)}?token=${encodeURIComponent(state.token)}" target="_blank" download>
|
||||
📎 ${escapeHtml(msg.attachmentName || 'file')} (${sizeStr})
|
||||
</a>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
div.innerHTML = `
|
||||
<div class="message-meta">
|
||||
<span class="message-author">@${escapeHtml(msg.senderUsername)}</span>
|
||||
<span class="role-badge role-${roleClass}">${escapeHtml(msg.senderRole || 'Member')}</span>
|
||||
<span class="message-time">${time}</span>
|
||||
</div>
|
||||
<div class="message-content">${contentHtml}</div>
|
||||
`;
|
||||
|
||||
el.chatMessages.appendChild(div);
|
||||
el.chatMessages.scrollTop = el.chatMessages.scrollHeight;
|
||||
}
|
||||
|
||||
function appendSystemNotice(text) {
|
||||
const div = document.createElement('div');
|
||||
div.className = 'system-notice';
|
||||
div.textContent = text;
|
||||
el.chatMessages.appendChild(div);
|
||||
el.chatMessages.scrollTop = el.chatMessages.scrollHeight;
|
||||
}
|
||||
|
||||
function renderUsers() {
|
||||
el.userList.innerHTML = '';
|
||||
const onlineCount = state.users.filter(u => u.isOnline).length;
|
||||
el.userCountBadge.textContent = `${onlineCount} Online / ${state.users.length} Total`;
|
||||
|
||||
state.users.forEach(u => {
|
||||
const item = document.createElement('div');
|
||||
item.className = 'user-item';
|
||||
const roleClass = (u.role || 'member').toLowerCase();
|
||||
item.innerHTML = `
|
||||
<div class="user-meta">
|
||||
<span class="user-dot ${u.isOnline ? 'online' : ''}"></span>
|
||||
<span style="font-weight:600;">@${escapeHtml(u.username)}</span>
|
||||
</div>
|
||||
<span class="role-badge role-${roleClass}">${escapeHtml(u.role)}</span>
|
||||
`;
|
||||
el.userList.appendChild(item);
|
||||
});
|
||||
}
|
||||
|
||||
function renderFiles() {
|
||||
el.filesList.innerHTML = '';
|
||||
if (state.files.length === 0) {
|
||||
el.filesList.innerHTML = '<div style="color:var(--text-muted); text-align:center; padding:20px;">No shared files yet.</div>';
|
||||
return;
|
||||
}
|
||||
|
||||
state.files.forEach(f => {
|
||||
const item = document.createElement('div');
|
||||
item.className = 'file-item';
|
||||
const sizeStr = formatBytes(f.fileSizeBytes || 0);
|
||||
const dateStr = new Date(f.createdAt).toLocaleDateString();
|
||||
|
||||
item.innerHTML = `
|
||||
<div class="file-meta">
|
||||
<div style="font-weight:600;">📎 ${escapeHtml(f.originalFileName)}</div>
|
||||
<div style="font-size:0.8rem; color:var(--text-muted);">${sizeStr} • shared by @${escapeHtml(f.uploaderUsername)} on ${dateStr}</div>
|
||||
</div>
|
||||
<a class="btn btn-primary btn-sm" href="/api/files/${encodeURIComponent(f.id)}?token=${encodeURIComponent(state.token)}" download>Download</a>
|
||||
`;
|
||||
el.filesList.appendChild(item);
|
||||
});
|
||||
}
|
||||
|
||||
function updateUserUI() {
|
||||
if (state.user) {
|
||||
el.currentUsername.textContent = `@${state.user.username}`;
|
||||
el.currentUserRole.textContent = `[${state.user.role}]`;
|
||||
el.userBadge.style.display = 'flex';
|
||||
el.logoutBtn.style.display = 'inline-flex';
|
||||
} else {
|
||||
el.userBadge.style.display = 'none';
|
||||
el.logoutBtn.style.display = 'none';
|
||||
}
|
||||
}
|
||||
|
||||
function showAuthModal() {
|
||||
el.authModal.style.display = 'flex';
|
||||
}
|
||||
|
||||
function hideAuthModal() {
|
||||
el.authModal.style.display = 'none';
|
||||
}
|
||||
|
||||
function showToast(message) {
|
||||
const toast = document.createElement('div');
|
||||
toast.className = 'toast';
|
||||
toast.textContent = message;
|
||||
el.toastContainer.appendChild(toast);
|
||||
setTimeout(() => toast.remove(), 3500);
|
||||
}
|
||||
|
||||
// ==========================================
|
||||
// Actions
|
||||
// ==========================================
|
||||
function sendMessage() {
|
||||
const text = el.messageInput.value.trim();
|
||||
if (!text) return;
|
||||
el.messageInput.value = '';
|
||||
|
||||
if (text.startsWith('/')) {
|
||||
handleSlashCommand(text);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!state.activeChannelId) {
|
||||
showToast('Select a channel first');
|
||||
return;
|
||||
}
|
||||
|
||||
sendEnvelope('SEND_MESSAGE', {
|
||||
channelId: state.activeChannelId,
|
||||
content: text
|
||||
});
|
||||
}
|
||||
|
||||
function handleSlashCommand(input) {
|
||||
const parts = input.split(' ');
|
||||
const cmd = parts[0].substring(1).toLowerCase();
|
||||
const args = parts.slice(1).join(' ').trim();
|
||||
|
||||
if (cmd === 'join') {
|
||||
const ch = state.channels.find(c => c.name.toLowerCase() === args.replace('#', '').toLowerCase());
|
||||
if (ch) joinChannel(ch.id);
|
||||
else showToast(`Channel ${args} not found`);
|
||||
return;
|
||||
}
|
||||
|
||||
if (cmd === 'create') {
|
||||
const cParts = args.split(' ');
|
||||
createChannel(cParts[0], cParts.slice(1).join(' '));
|
||||
return;
|
||||
}
|
||||
|
||||
sendEnvelope('EXECUTE_COMMAND', {
|
||||
command: cmd,
|
||||
args: args,
|
||||
channelId: state.activeChannelId || ''
|
||||
});
|
||||
}
|
||||
|
||||
function createChannel(name, topic) {
|
||||
if (!name) {
|
||||
showToast('Channel name required');
|
||||
return;
|
||||
}
|
||||
sendEnvelope('CREATE_CHANNEL', { name, topic: topic || '' });
|
||||
el.createChannelCard.style.display = 'none';
|
||||
el.newChannelName.value = '';
|
||||
el.newChannelTopic.value = '';
|
||||
}
|
||||
|
||||
async function uploadFile(file) {
|
||||
if (!file) return;
|
||||
if (!state.activeChannelId) {
|
||||
showToast('Please join a channel to share files');
|
||||
return;
|
||||
}
|
||||
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
formData.append('channelId', state.activeChannelId);
|
||||
|
||||
showToast(`Uploading ${file.name}...`);
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/files/upload', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${state.token}`
|
||||
},
|
||||
body: formData
|
||||
});
|
||||
|
||||
const data = await res.json();
|
||||
if (res.ok && data.success) {
|
||||
showToast(`Uploaded ${file.name} successfully!`);
|
||||
} else {
|
||||
showToast(`Upload failed: ${data.errorMessage || 'Server error'}`);
|
||||
}
|
||||
} catch (err) {
|
||||
showToast(`Upload failed: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
function logout() {
|
||||
state.token = null;
|
||||
state.user = null;
|
||||
localStorage.removeItem('gsdchat_token');
|
||||
localStorage.removeItem('gsdchat_user');
|
||||
if (state.socket) state.socket.close();
|
||||
updateUserUI();
|
||||
showAuthModal();
|
||||
}
|
||||
|
||||
// ==========================================
|
||||
// Event Listeners
|
||||
// ==========================================
|
||||
function setupEventListeners() {
|
||||
// Navigation Tabs
|
||||
el.navTabs.forEach(tab => {
|
||||
tab.addEventListener('click', () => switchTab(tab.dataset.tab));
|
||||
});
|
||||
|
||||
// Auth Tabs
|
||||
el.tabLogin.addEventListener('click', () => {
|
||||
state.isRegister = false;
|
||||
el.tabLogin.classList.add('active');
|
||||
el.tabRegister.classList.remove('active');
|
||||
el.authSubmitBtn.textContent = 'Login';
|
||||
el.authError.textContent = '';
|
||||
});
|
||||
|
||||
el.tabRegister.addEventListener('click', () => {
|
||||
state.isRegister = true;
|
||||
el.tabRegister.classList.add('active');
|
||||
el.tabLogin.classList.remove('active');
|
||||
el.authSubmitBtn.textContent = 'Register';
|
||||
el.authError.textContent = '';
|
||||
});
|
||||
|
||||
el.authForm.addEventListener('submit', (e) => {
|
||||
e.preventDefault();
|
||||
handleAuthSubmit();
|
||||
});
|
||||
|
||||
// Chat Input
|
||||
el.sendBtn.addEventListener('click', sendMessage);
|
||||
el.messageInput.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
sendMessage();
|
||||
}
|
||||
});
|
||||
|
||||
// File Uploads
|
||||
el.fileInput.addEventListener('change', (e) => {
|
||||
if (e.target.files.length > 0) {
|
||||
uploadFile(e.target.files[0]);
|
||||
e.target.value = '';
|
||||
}
|
||||
});
|
||||
|
||||
el.filesViewUploadInput.addEventListener('change', (e) => {
|
||||
if (e.target.files.length > 0) {
|
||||
uploadFile(e.target.files[0]);
|
||||
e.target.value = '';
|
||||
}
|
||||
});
|
||||
|
||||
// Channels Create Form
|
||||
el.openCreateChannelBtn.addEventListener('click', () => {
|
||||
el.createChannelCard.style.display = 'block';
|
||||
el.newChannelName.focus();
|
||||
});
|
||||
|
||||
el.cancelCreateChannelBtn.addEventListener('click', () => {
|
||||
el.createChannelCard.style.display = 'none';
|
||||
});
|
||||
|
||||
el.submitCreateChannelBtn.addEventListener('click', () => {
|
||||
createChannel(el.newChannelName.value.trim(), el.newChannelTopic.value.trim());
|
||||
});
|
||||
|
||||
// Logout
|
||||
el.logoutBtn.addEventListener('click', logout);
|
||||
}
|
||||
|
||||
// ==========================================
|
||||
// Helper Functions
|
||||
// ==========================================
|
||||
function escapeHtml(str) {
|
||||
if (!str) return '';
|
||||
const div = document.createElement('div');
|
||||
div.textContent = str;
|
||||
return div.innerHTML;
|
||||
}
|
||||
|
||||
function formatBytes(bytes) {
|
||||
if (bytes === 0) 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(2)) + ' ' + sizes[i];
|
||||
}
|
||||
|
||||
// Start app
|
||||
window.addEventListener('DOMContentLoaded', init);
|
||||
})();
|
||||
Loading…
Add table
Add a link
Reference in a new issue