Fix TUI screen wrapping, channel selection/creation, and online members presence

This commit is contained in:
tyuXX 2026-10-11 17:21:54 +00:00
parent cbc24e7672
commit 25696db42c
12 changed files with 582 additions and 109 deletions

View file

@ -12,6 +12,13 @@ public class Program
{ {
public static async Task Main(string[] args) public static async Task Main(string[] args)
{ {
try
{
Console.OutputEncoding = System.Text.Encoding.UTF8;
Console.InputEncoding = System.Text.Encoding.UTF8;
}
catch { }
string? serverUrl = null; string? serverUrl = null;
string? username = null; string? username = null;
string? password = null; string? password = null;

View file

@ -45,6 +45,7 @@ public class ConsoleUi
Console.Clear(); Console.Clear();
} }
bool hadStatus = false;
try try
{ {
while (_running && !cancellationToken.IsCancellationRequested) while (_running && !cancellationToken.IsCancellationRequested)
@ -52,7 +53,14 @@ public class ConsoleUi
// Dynamic server screens update check // Dynamic server screens update check
UpdateDynamicScreens(); UpdateDynamicScreens();
if (_state.NeedsRedraw || DateTime.UtcNow < _state.StatusMessageUntil) bool hasStatus = DateTime.UtcNow < _state.StatusMessageUntil;
if (hadStatus && !hasStatus)
{
_state.NeedsRedraw = true;
}
hadStatus = hasStatus;
if (_state.NeedsRedraw)
{ {
Draw(); Draw();
_state.NeedsRedraw = false; _state.NeedsRedraw = false;
@ -71,27 +79,27 @@ public class ConsoleUi
// Check Screen Swapping Function Keys // Check Screen Swapping Function Keys
if (key.Key == ConsoleKey.F1) if (key.Key == ConsoleKey.F1)
{ {
_state.ActiveScreenId = "F1_Chat"; if (_state.ActiveScreenId != "F1_Chat") { _state.ActiveScreenId = "F1_Chat"; Console.Clear(); }
_state.NeedsRedraw = true; _state.NeedsRedraw = true;
} }
else if (key.Key == ConsoleKey.F2) else if (key.Key == ConsoleKey.F2)
{ {
_state.ActiveScreenId = "F2_Channels"; if (_state.ActiveScreenId != "F2_Channels") { _state.ActiveScreenId = "F2_Channels"; Console.Clear(); }
_state.NeedsRedraw = true; _state.NeedsRedraw = true;
} }
else if (key.Key == ConsoleKey.F3) else if (key.Key == ConsoleKey.F3)
{ {
_state.ActiveScreenId = "F3_Users"; if (_state.ActiveScreenId != "F3_Users") { _state.ActiveScreenId = "F3_Users"; Console.Clear(); }
_state.NeedsRedraw = true; _state.NeedsRedraw = true;
} }
else if (key.Key == ConsoleKey.F4) else if (key.Key == ConsoleKey.F4)
{ {
_state.ActiveScreenId = "F4_Files"; if (_state.ActiveScreenId != "F4_Files") { _state.ActiveScreenId = "F4_Files"; Console.Clear(); }
_state.NeedsRedraw = true; _state.NeedsRedraw = true;
} }
else if (key.Key == ConsoleKey.F5 && _screens.ContainsKey("F5_Custom")) else if (key.Key == ConsoleKey.F5 && _screens.ContainsKey("F5_Custom"))
{ {
_state.ActiveScreenId = "F5_Custom"; if (_state.ActiveScreenId != "F5_Custom") { _state.ActiveScreenId = "F5_Custom"; Console.Clear(); }
_state.NeedsRedraw = true; _state.NeedsRedraw = true;
} }
else else
@ -144,10 +152,23 @@ public class ConsoleUi
return _screens.Values.FirstOrDefault(); return _screens.Values.FirstOrDefault();
} }
private static (int Width, int Height) GetWindowDimensions()
{
try
{
int w = Console.WindowWidth > 10 ? Console.WindowWidth : 80;
int h = Console.WindowHeight > 10 ? Console.WindowHeight : 24;
return (w, h);
}
catch
{
return (80, 24);
}
}
private void Draw() private void Draw()
{ {
int width = Console.WindowWidth > 10 ? Console.WindowWidth : 80; var (width, height) = GetWindowDimensions();
int height = Console.WindowHeight > 10 ? Console.WindowHeight : 24;
var sb = new StringBuilder(); var sb = new StringBuilder();
sb.Append(Ansi.CursorHome); sb.Append(Ansi.CursorHome);
@ -187,12 +208,12 @@ public class ConsoleUi
} }
sb.AppendLine(); sb.AppendLine();
sb.AppendLine(new string('═', Math.Max(0, width))); sb.AppendLine(new string('═', Math.Max(0, width - 1)));
} }
private void RenderBottomStatusBar(StringBuilder sb, int width) private void RenderBottomStatusBar(StringBuilder sb, int width)
{ {
sb.AppendLine(new string('─', Math.Max(0, width))); sb.AppendLine(new string('─', Math.Max(0, width - 1)));
string connStatus = _state.IsConnected string connStatus = _state.IsConnected
? $"{Ansi.BrightGreen}● Online{Ansi.Reset}" ? $"{Ansi.BrightGreen}● Online{Ansi.Reset}"

View file

@ -28,7 +28,7 @@ public class ChannelsScreen : IScreen
public void Render(int width, int height, StringBuilder sb) public void Render(int width, int height, StringBuilder sb)
{ {
sb.AppendLine($" {Ansi.Bold}{Ansi.Yellow}Channel Browser{Ansi.Reset} {Ansi.Gray}(Press ENTER to join, 'C' to create, 'D' to delete){Ansi.Reset}"); sb.AppendLine($" {Ansi.Bold}{Ansi.Yellow}Channel Browser{Ansi.Reset} {Ansi.Gray}(Press ENTER to join, 'C' to create, 'D' to delete){Ansi.Reset}");
sb.AppendLine(new string('─', Math.Max(0, width))); sb.AppendLine(new string('─', Math.Max(0, width - 1)));
if (_state.Channels.Count == 0) if (_state.Channels.Count == 0)
{ {
@ -60,7 +60,7 @@ public class ChannelsScreen : IScreen
} }
} }
sb.AppendLine(new string('─', Math.Max(0, width))); sb.AppendLine(new string('─', Math.Max(0, width - 1)));
if (_isCreating) if (_isCreating)
{ {
@ -88,6 +88,8 @@ public class ChannelsScreen : IScreen
string name = parts[0]; string name = parts[0];
string topic = parts.Length > 1 ? parts[1] : string.Empty; string topic = parts.Length > 1 ? parts[1] : string.Empty;
await _connection.CreateChannelAsync(name, topic); await _connection.CreateChannelAsync(name, topic);
_state.ActiveScreenId = "F1_Chat";
_state.SetStatus($"Created and joined #{name}");
} }
_state.NeedsRedraw = true; _state.NeedsRedraw = true;
} }

View file

@ -31,9 +31,11 @@ public class ChatScreen : IScreen
string topic = ch != null && !string.IsNullOrEmpty(ch.Topic) ? $" - {ch.Topic}" : ""; string topic = ch != null && !string.IsNullOrEmpty(ch.Topic) ? $" - {ch.Topic}" : "";
// Header line // Header line
string header = $" {Ansi.Bold}{Ansi.Cyan}{chName}{Ansi.Reset}{Ansi.Gray}{topic}{Ansi.Reset}"; int onlineCount = _state.Users.Count(u => u.IsOnline);
string onlineTag = $" {Ansi.Gray}({Ansi.BrightGreen}● {onlineCount} online{Ansi.Gray}){Ansi.Reset}";
string header = $" {Ansi.Bold}{Ansi.Cyan}{chName}{Ansi.Reset}{Ansi.Gray}{topic}{Ansi.Reset}{onlineTag}";
sb.AppendLine(PadOrTruncate(header, width)); sb.AppendLine(PadOrTruncate(header, width));
sb.AppendLine(new string('─', Math.Max(0, width))); sb.AppendLine(new string('─', Math.Max(0, width - 1)));
// Messages area: height minus (Header: 2, Footer/Input: 3, Tab bar & status: 3) = height - 8 // Messages area: height minus (Header: 2, Footer/Input: 3, Tab bar & status: 3) = height - 8
int msgAreaHeight = Math.Max(3, height - 8); int msgAreaHeight = Math.Max(3, height - 8);
@ -85,7 +87,7 @@ public class ChatScreen : IScreen
} }
// Divider // Divider
sb.AppendLine(new string('─', Math.Max(0, width))); sb.AppendLine(new string('─', Math.Max(0, width - 1)));
// Input Line // Input Line
string prompt = $" {Ansi.Cyan}[{chName}] > {Ansi.Reset}"; string prompt = $" {Ansi.Cyan}[{chName}] > {Ansi.Reset}";

View file

@ -25,13 +25,13 @@ public class DynamicModScreen : IScreen
public void Render(int width, int height, StringBuilder sb) public void Render(int width, int height, StringBuilder sb)
{ {
sb.AppendLine($" {Ansi.Bold}{Ansi.Magenta}{_definition.Title}{Ansi.Reset} {Ansi.Gray}({_definition.Description}){Ansi.Reset}"); sb.AppendLine($" {Ansi.Bold}{Ansi.Magenta}{_definition.Title}{Ansi.Reset} {Ansi.Gray}({_definition.Description}){Ansi.Reset}");
sb.AppendLine(new string('─', Math.Max(0, width))); sb.AppendLine(new string('─', Math.Max(0, width - 1)));
foreach (var panel in _definition.Panels) foreach (var panel in _definition.Panels)
{ {
if (panel.ShowBorder) if (panel.ShowBorder)
{ {
sb.AppendLine($" ┌─ {Ansi.Cyan}{panel.BorderTitle ?? panel.Name}{Ansi.Reset} " + new string('─', Math.Max(0, width - (panel.BorderTitle ?? panel.Name).Length - 6))); sb.AppendLine($" ┌─ {Ansi.Cyan}{panel.BorderTitle ?? panel.Name}{Ansi.Reset} " + new string('─', Math.Max(0, width - 1 - (panel.BorderTitle ?? panel.Name).Length - 6)));
} }
if (!string.IsNullOrEmpty(panel.ContentTemplate)) if (!string.IsNullOrEmpty(panel.ContentTemplate))
@ -45,11 +45,11 @@ public class DynamicModScreen : IScreen
if (panel.ShowBorder) if (panel.ShowBorder)
{ {
sb.AppendLine(" └" + new string('─', Math.Max(0, width - 3))); sb.AppendLine(" └" + new string('─', Math.Max(0, width - 1 - 3)));
} }
} }
sb.AppendLine(new string('─', Math.Max(0, width))); sb.AppendLine(new string('─', Math.Max(0, width - 1)));
sb.AppendLine($" {Ansi.Gray}Dynamic screen rendered from server layout schema.{Ansi.Reset}"); sb.AppendLine($" {Ansi.Gray}Dynamic screen rendered from server layout schema.{Ansi.Reset}");
} }

View file

@ -28,7 +28,7 @@ public class FilesScreen : IScreen
public void Render(int width, int height, StringBuilder sb) public void Render(int width, int height, StringBuilder sb)
{ {
sb.AppendLine($" {Ansi.Bold}{Ansi.Cyan}Shared Files Browser{Ansi.Reset} {Ansi.Gray}(Press 'D' to download, 'U' to upload){Ansi.Reset}"); sb.AppendLine($" {Ansi.Bold}{Ansi.Cyan}Shared Files Browser{Ansi.Reset} {Ansi.Gray}(Press 'D' to download, 'U' to upload){Ansi.Reset}");
sb.AppendLine(new string('─', Math.Max(0, width))); sb.AppendLine(new string('─', Math.Max(0, width - 1)));
if (_state.Files.Count == 0) if (_state.Files.Count == 0)
{ {
@ -61,7 +61,7 @@ public class FilesScreen : IScreen
} }
} }
sb.AppendLine(new string('─', Math.Max(0, width))); sb.AppendLine(new string('─', Math.Max(0, width - 1)));
if (_isUploading) if (_isUploading)
{ {

View file

@ -24,7 +24,7 @@ public class UsersScreen : IScreen
{ {
int onlineCount = _state.Users.Count(u => u.IsOnline); int onlineCount = _state.Users.Count(u => u.IsOnline);
sb.AppendLine($" {Ansi.Bold}{Ansi.Cyan}Community Directory{Ansi.Reset} {Ansi.Gray}({onlineCount} Online / {_state.Users.Count} Total){Ansi.Reset}"); sb.AppendLine($" {Ansi.Bold}{Ansi.Cyan}Community Directory{Ansi.Reset} {Ansi.Gray}({onlineCount} Online / {_state.Users.Count} Total){Ansi.Reset}");
sb.AppendLine(new string('─', Math.Max(0, width))); sb.AppendLine(new string('─', Math.Max(0, width - 1)));
if (_state.Users.Count == 0) if (_state.Users.Count == 0)
{ {
@ -56,7 +56,7 @@ public class UsersScreen : IScreen
sb.AppendLine($"{prefix}{statusDot} {userDisplay} {roleBadge}"); sb.AppendLine($"{prefix}{statusDot} {userDisplay} {roleBadge}");
} }
sb.AppendLine(new string('─', Math.Max(0, width))); sb.AppendLine(new string('─', Math.Max(0, width - 1)));
sb.AppendLine($" {Ansi.Gray}[↑/↓] Scroll Directory{Ansi.Reset}"); sb.AppendLine($" {Ansi.Gray}[↑/↓] Scroll Directory{Ansi.Reset}");
} }

View file

@ -80,6 +80,16 @@ public class ChatWebSocketManager
var files = await _db.GetRecentFilesAsync(100); var files = await _db.GetRecentFilesAsync(100);
await client.SendMessageAsync(MessageTypes.FileListSync, new FileListSyncPacket { Files = files }, cancellationToken); await client.SendMessageAsync(MessageTypes.FileListSync, new FileListSyncPacket { Files = files }, cancellationToken);
// Send Initial User List
var initialUsers = await _db.GetAllUsersAsync();
var onlineIds = new HashSet<string>(_clients.Values.Select(c => c.User.Id), StringComparer.OrdinalIgnoreCase);
var onlineNames = new HashSet<string>(_clients.Values.Select(c => c.User.Username), StringComparer.OrdinalIgnoreCase);
foreach (var u in initialUsers)
{
u.IsOnline = onlineIds.Contains(u.Id) || onlineNames.Contains(u.Username);
}
await client.SendMessageAsync(MessageTypes.UserListSync, new UserListSyncPacket { Users = initialUsers }, cancellationToken);
// Broadcast Presence Update // Broadcast Presence Update
await BroadcastUserListAsync(); await BroadcastUserListAsync();
await BroadcastSystemNoticeAsync($"[+] {user.Username} connected.", "Info"); await BroadcastSystemNoticeAsync($"[+] {user.Username} connected.", "Info");
@ -194,6 +204,11 @@ public class ChatWebSocketManager
} }
break; break;
case MessageTypes.UserListSync:
case "GET_USERS":
await BroadcastUserListAsync();
break;
case MessageTypes.Ping: case MessageTypes.Ping:
await client.SendMessageAsync(MessageTypes.Pong, new { }, ct); await client.SendMessageAsync(MessageTypes.Pong, new { }, ct);
break; break;
@ -305,7 +320,13 @@ public class ChatWebSocketManager
return; return;
} }
client.ActiveChannelId = channel.Id;
await BroadcastChannelListAsync(); await BroadcastChannelListAsync();
await client.SendMessageAsync(MessageTypes.HistorySync, new HistorySyncPacket
{
ChannelId = channel.Id,
Messages = new()
}, ct);
await BroadcastSystemNoticeAsync($"Channel #{cleanName} was created by {client.User.Username}.", "Success"); await BroadcastSystemNoticeAsync($"Channel #{cleanName} was created by {client.User.Username}.", "Success");
} }
@ -371,6 +392,22 @@ public class ChatWebSocketManager
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket { Success = true, Output = $"Users:\n{userListStr}" }, ct); await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket { Success = true, Output = $"Users:\n{userListStr}" }, ct);
break; break;
case "delete":
string channelToDelete = (packet.Args ?? string.Empty).Trim().TrimStart('#');
if (string.IsNullOrEmpty(channelToDelete))
{
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket { Success = false, Output = "Usage: /delete <channel_name>" }, ct);
break;
}
var chToDelete = await _db.GetChannelByNameAsync(channelToDelete);
if (chToDelete == null)
{
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket { Success = false, Output = $"Channel #{channelToDelete} not found." }, ct);
break;
}
await HandleDeleteChannelAsync(client, chToDelete.Id, ct);
break;
default: default:
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket { Success = false, Output = $"Unknown command '/{cmd}'. Type /help for available commands." }, ct); await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket { Success = false, Output = $"Unknown command '/{cmd}'. Type /help for available commands." }, ct);
break; break;
@ -397,11 +434,12 @@ public class ChatWebSocketManager
public async Task BroadcastUserListAsync() public async Task BroadcastUserListAsync()
{ {
var allUsers = await _db.GetAllUsersAsync(); var allUsers = await _db.GetAllUsersAsync();
var onlineUserIds = new HashSet<string>(_clients.Values.Select(c => c.User.Id)); var onlineUserIds = new HashSet<string>(_clients.Values.Select(c => c.User.Id), StringComparer.OrdinalIgnoreCase);
var onlineUsernames = new HashSet<string>(_clients.Values.Select(c => c.User.Username), StringComparer.OrdinalIgnoreCase);
foreach (var u in allUsers) foreach (var u in allUsers)
{ {
u.IsOnline = onlineUserIds.Contains(u.Id); u.IsOnline = onlineUserIds.Contains(u.Id) || onlineUsernames.Contains(u.Username);
} }
await BroadcastToAllAsync(MessageTypes.UserListSync, new UserListSyncPacket { Users = allUsers }); await BroadcastToAllAsync(MessageTypes.UserListSync, new UserListSyncPacket { Users = allUsers });

View file

@ -166,6 +166,127 @@ html, body {
padding: 10px 16px; padding: 10px 16px;
background-color: rgba(19, 27, 46, 0.7); background-color: rgba(19, 27, 46, 0.7);
border-bottom: 1px solid var(--border-color); border-bottom: 1px solid var(--border-color);
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
}
.chat-header-actions {
display: flex;
align-items: center;
gap: 8px;
}
.btn-outline-members {
background: rgba(30, 41, 59, 0.6);
border: 1px solid var(--border-color);
color: var(--text-main);
padding: 4px 10px;
border-radius: 6px;
font-size: 0.82rem;
font-weight: 600;
cursor: pointer;
display: inline-flex;
align-items: center;
gap: 6px;
transition: all 0.15s;
}
.btn-outline-members:hover {
border-color: var(--accent);
background: rgba(56, 189, 248, 0.1);
color: var(--accent);
}
.chat-content-container {
display: flex;
flex: 1;
min-height: 0;
overflow: hidden;
position: relative;
}
.chat-main-area {
display: flex;
flex-direction: column;
flex: 1;
min-width: 0;
height: 100%;
}
.chat-members-sidebar {
width: 230px;
background-color: rgba(15, 23, 42, 0.75);
border-left: 1px solid var(--border-color);
display: flex;
flex-direction: column;
flex-shrink: 0;
height: 100%;
transition: transform 0.2s ease, width 0.2s ease, opacity 0.2s ease;
}
.chat-members-sidebar.closed {
display: none;
}
.members-sidebar-header {
padding: 12px 14px;
font-size: 0.8rem;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.05em;
color: var(--text-muted);
border-bottom: 1px solid var(--border-color);
display: flex;
justify-content: space-between;
align-items: center;
}
.member-count-badge {
background-color: rgba(34, 197, 94, 0.15);
color: #22c55e;
font-size: 0.75rem;
padding: 2px 7px;
border-radius: 999px;
font-weight: 600;
}
.chat-online-users-list {
flex: 1;
overflow-y: auto;
padding: 8px 10px;
display: flex;
flex-direction: column;
gap: 4px;
}
.chat-member-item {
display: flex;
align-items: center;
justify-content: space-between;
padding: 6px 8px;
border-radius: 6px;
font-size: 0.88rem;
transition: background 0.15s;
}
.chat-member-item:hover {
background-color: rgba(255, 255, 255, 0.04);
}
.chat-member-meta {
display: flex;
align-items: center;
gap: 8px;
min-width: 0;
}
.chat-member-name {
font-weight: 500;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
} }
.channel-info { .channel-info {
@ -700,6 +821,17 @@ html, body {
.user-badge { .user-badge {
display: none; display: none;
} }
.chat-members-sidebar {
position: absolute;
right: 0;
top: 0;
bottom: 0;
z-index: 50;
width: 200px;
background-color: #0b1120;
box-shadow: -4px 0 20px rgba(0, 0, 0, 0.7);
}
} }
/* Drag & Drop Overlay */ /* Drag & Drop Overlay */

View file

@ -33,6 +33,11 @@
sendBtn: document.getElementById('sendBtn'), sendBtn: document.getElementById('sendBtn'),
fileInput: document.getElementById('fileInput'), fileInput: document.getElementById('fileInput'),
welcomeMotd: document.getElementById('welcomeMotd'), welcomeMotd: document.getElementById('welcomeMotd'),
toggleMembersBtn: document.getElementById('toggleMembersBtn'),
chatMembersSidebar: document.getElementById('chatMembersSidebar'),
chatOnlineUsersList: document.getElementById('chatOnlineUsersList'),
chatOnlineCountBadge: document.getElementById('chatOnlineCountBadge'),
chatHeaderOnlineCount: document.getElementById('chatHeaderOnlineCount'),
// Channels View // Channels View
channelList: document.getElementById('channelList'), channelList: document.getElementById('channelList'),
@ -70,10 +75,20 @@
dropOverlay: document.getElementById('dropOverlay') dropOverlay: document.getElementById('dropOverlay')
}; };
function initElements() {
for (const key in el) {
if (!el[key] && typeof key === 'string') {
const found = document.getElementById(key);
if (found) el[key] = found;
}
}
}
// ========================================== // ==========================================
// Initialization // Initialization
// ========================================== // ==========================================
async function init() { async function init() {
initElements();
setupEventListeners(); setupEventListeners();
await fetchServerInfo(); await fetchServerInfo();
@ -323,6 +338,19 @@
el.tabViews.forEach(view => { el.tabViews.forEach(view => {
view.classList.toggle('active', view.id === `view-${tabName}`); view.classList.toggle('active', view.id === `view-${tabName}`);
}); });
if (tabName === 'users') {
renderUsers();
if (state.socket && state.socket.readyState === WebSocket.OPEN) {
sendEnvelope('USER_LIST_SYNC', {});
}
} else if (tabName === 'channels') {
renderChannels();
} else if (tabName === 'files') {
renderFiles();
} else if (tabName === 'chat') {
renderMessages();
}
} }
function updateActiveChannelHeader() { function updateActiveChannelHeader() {
@ -331,7 +359,7 @@
const chId = active.id || active.Id; const chId = active.id || active.Id;
const chName = active.name || active.Name || 'general'; const chName = active.name || active.Name || 'general';
const chTopic = active.topic || active.Topic || ''; const chTopic = active.topic || active.Topic || '';
if (el.channelSelectDropdown) { if (el.channelSelectDropdown && el.channelSelectDropdown.value !== chId) {
el.channelSelectDropdown.value = chId; el.channelSelectDropdown.value = chId;
} }
el.activeChannelTopic.textContent = chTopic ? ` - ${chTopic}` : ''; el.activeChannelTopic.textContent = chTopic ? ` - ${chTopic}` : '';
@ -340,11 +368,8 @@
} }
function renderChannels() { function renderChannels() {
if (el.channelList) {
el.channelList.innerHTML = ''; el.channelList.innerHTML = '';
if (el.channelSelectDropdown) {
el.channelSelectDropdown.innerHTML = '';
}
state.channels.forEach(ch => { state.channels.forEach(ch => {
const chId = ch.id || ch.Id; const chId = ch.id || ch.Id;
const chName = ch.name || ch.Name; const chName = ch.name || ch.Name;
@ -366,24 +391,43 @@
switchTab('chat'); switchTab('chat');
}); });
el.channelList.appendChild(item); el.channelList.appendChild(item);
});
}
// In-chat dropdown option // In-chat dropdown option: only rebuild if list changed
if (el.channelSelectDropdown) { if (el.channelSelectDropdown) {
const currentOpts = Array.from(el.channelSelectDropdown.options).map(o => o.value);
const newIds = state.channels.map(c => c.id || c.Id);
const needsRebuild = currentOpts.length !== newIds.length || !newIds.every((id, idx) => id === currentOpts[idx]);
if (needsRebuild) {
el.channelSelectDropdown.innerHTML = '';
state.channels.forEach(ch => {
const chId = ch.id || ch.Id;
const chName = ch.name || ch.Name;
const opt = document.createElement('option'); const opt = document.createElement('option');
opt.value = chId; opt.value = chId;
opt.textContent = `#${chName}`; opt.textContent = `#${chName}`;
opt.selected = isActive; if (chId === state.activeChannelId) opt.selected = true;
el.channelSelectDropdown.appendChild(opt); el.channelSelectDropdown.appendChild(opt);
}
}); });
}
if (state.activeChannelId) {
el.channelSelectDropdown.value = state.activeChannelId;
}
}
// Show create button for Admin, Owner, or if allowed for members // Show create button for Admin, Owner, or if allowed for members
const isPrivileged = state.user && (state.user.role === 'Owner' || state.user.role === 'Admin'); const isPrivileged = state.user && (state.user.role === 'Owner' || state.user.role === 'Admin');
const allowMemberChannels = state.serverInfo && state.serverInfo.allowMemberChannelCreation; const allowMemberChannels = state.serverInfo && state.serverInfo.allowMemberChannelCreation;
if (el.openCreateChannelBtn) {
el.openCreateChannelBtn.style.display = (isPrivileged || allowMemberChannels) ? 'inline-flex' : 'none'; el.openCreateChannelBtn.style.display = (isPrivileged || allowMemberChannels) ? 'inline-flex' : 'none';
} }
}
function joinChannel(channelId) { function joinChannel(channelId) {
if (!channelId) return;
state.activeChannelId = channelId; state.activeChannelId = channelId;
sendEnvelope('JOIN_CHANNEL', { channelId }); sendEnvelope('JOIN_CHANNEL', { channelId });
renderChannels(); renderChannels();
@ -499,18 +543,94 @@
el.chatMessages.scrollTop = el.chatMessages.scrollHeight; el.chatMessages.scrollTop = el.chatMessages.scrollHeight;
} }
function renderUsers() { function checkIsOnline(u) {
el.userList.innerHTML = ''; if (!u) return false;
const onlineCount = state.users.filter(u => u.isOnline ?? u.IsOnline).length; const val = u.isOnline !== undefined ? u.isOnline : u.IsOnline;
el.userCountBadge.textContent = `${onlineCount} Online / ${state.users.length} Total`; return val === true || val === 'true' || val === 1 || val === '1';
}
state.users.forEach(u => { function renderUsers() {
initElements();
const onlineUsers = state.users.filter(checkIsOnline);
const onlineCount = onlineUsers.length;
const totalCount = state.users.length;
// 1. Update in-chat members sidebar and header badge
if (el.chatOnlineCountBadge) {
el.chatOnlineCountBadge.textContent = onlineCount;
}
if (el.chatHeaderOnlineCount) {
el.chatHeaderOnlineCount.textContent = onlineCount;
}
if (el.chatOnlineUsersList) {
el.chatOnlineUsersList.innerHTML = '';
if (onlineUsers.length === 0) {
el.chatOnlineUsersList.innerHTML = '<div style="color:var(--text-muted); font-size:0.8rem; padding:12px 6px; text-align:center;">No members currently online</div>';
} else {
const roleOrder = { owner: 1, admin: 2, member: 3 };
const sortedOnline = [...onlineUsers].sort((a, b) => {
const aRole = (a.role || a.Role || 'member').toLowerCase();
const bRole = (b.role || b.Role || 'member').toLowerCase();
const orderDiff = (roleOrder[aRole] || 99) - (roleOrder[bRole] || 99);
if (orderDiff !== 0) return orderDiff;
const aName = (a.username || a.Username || '').toLowerCase();
const bName = (b.username || b.Username || '').toLowerCase();
return aName.localeCompare(bName);
});
sortedOnline.forEach(u => {
const item = document.createElement('div');
item.className = 'chat-member-item';
const username = u.username || u.Username || 'User';
const role = u.role || u.Role || 'Member';
const roleClass = role.toLowerCase();
item.innerHTML = `
<div class="chat-member-meta">
<span class="user-dot online"></span>
<span class="chat-member-name" title="@${escapeHtml(username)}">@${escapeHtml(username)}</span>
</div>
<span class="role-badge role-${roleClass}" style="font-size:0.65rem; padding:1px 6px;">${escapeHtml(role)}</span>
`;
el.chatOnlineUsersList.appendChild(item);
});
}
}
// 2. Update dedicated Community Members tab (#view-users)
if (el.userCountBadge) {
el.userCountBadge.textContent = `${onlineCount} Online / ${totalCount} Total`;
}
if (el.userList) {
el.userList.innerHTML = '';
if (state.users.length === 0) {
el.userList.innerHTML = '<div style="color:var(--text-muted); text-align:center; padding:20px;">No registered members found.</div>';
return;
}
const roleOrder = { owner: 1, admin: 2, member: 3 };
const sortedAll = [...state.users].sort((a, b) => {
const aOnline = checkIsOnline(a) ? 1 : 0;
const bOnline = checkIsOnline(b) ? 1 : 0;
if (bOnline !== aOnline) return bOnline - aOnline;
const aRole = (a.role || a.Role || 'member').toLowerCase();
const bRole = (b.role || b.Role || 'member').toLowerCase();
const orderDiff = (roleOrder[aRole] || 99) - (roleOrder[bRole] || 99);
if (orderDiff !== 0) return orderDiff;
const aName = (a.username || a.Username || '').toLowerCase();
const bName = (b.username || b.Username || '').toLowerCase();
return aName.localeCompare(bName);
});
sortedAll.forEach(u => {
const item = document.createElement('div'); const item = document.createElement('div');
item.className = 'user-item'; item.className = 'user-item';
const username = u.username || u.Username || 'User'; const username = u.username || u.Username || 'User';
const role = u.role || u.Role || 'Member'; const role = u.role || u.Role || 'Member';
const roleClass = role.toLowerCase(); const roleClass = role.toLowerCase();
const isOnline = u.isOnline ?? u.IsOnline ?? false; const isOnline = checkIsOnline(u);
item.innerHTML = ` item.innerHTML = `
<div class="user-meta"> <div class="user-meta">
<span class="user-dot ${isOnline ? 'online' : ''}"></span> <span class="user-dot ${isOnline ? 'online' : ''}"></span>
@ -521,6 +641,7 @@
el.userList.appendChild(item); el.userList.appendChild(item);
}); });
} }
}
function renderFiles() { function renderFiles() {
el.filesList.innerHTML = ''; el.filesList.innerHTML = '';
@ -616,9 +737,17 @@
const args = parts.slice(1).join(' ').trim(); const args = parts.slice(1).join(' ').trim();
if (cmd === 'join') { if (cmd === 'join') {
const ch = state.channels.find(c => c.name.toLowerCase() === args.replace('#', '').toLowerCase()); const target = args.replace('#', '').toLowerCase();
if (ch) joinChannel(ch.id); const ch = state.channels.find(c => {
else showToast(`Channel ${args} not found`); const n = (c.name || c.Name || '').toLowerCase();
const id = (c.id || c.Id || '').toLowerCase();
return n === target || id === target;
});
if (ch) {
joinChannel(ch.id || ch.Id);
} else {
showToast(`Channel #${args} not found`);
}
return; return;
} }
@ -641,9 +770,10 @@
return; return;
} }
sendEnvelope('CREATE_CHANNEL', { name, topic: topic || '' }); sendEnvelope('CREATE_CHANNEL', { name, topic: topic || '' });
el.createChannelCard.style.display = 'none'; if (el.createChannelCard) el.createChannelCard.style.display = 'none';
el.newChannelName.value = ''; if (el.newChannelName) el.newChannelName.value = '';
el.newChannelTopic.value = ''; if (el.newChannelTopic) el.newChannelTopic.value = '';
switchTab('chat');
} }
async function uploadFile(file) { async function uploadFile(file) {
@ -745,18 +875,49 @@
}); });
// Channels Create Form // Channels Create Form
if (el.openCreateChannelBtn) {
el.openCreateChannelBtn.addEventListener('click', () => { el.openCreateChannelBtn.addEventListener('click', () => {
el.createChannelCard.style.display = 'block'; if (el.createChannelCard) el.createChannelCard.style.display = 'block';
el.newChannelName.focus(); if (el.newChannelName) el.newChannelName.focus();
}); });
}
if (el.cancelCreateChannelBtn) {
el.cancelCreateChannelBtn.addEventListener('click', () => { el.cancelCreateChannelBtn.addEventListener('click', () => {
el.createChannelCard.style.display = 'none'; if (el.createChannelCard) el.createChannelCard.style.display = 'none';
}); });
}
if (el.submitCreateChannelBtn) {
el.submitCreateChannelBtn.addEventListener('click', () => { el.submitCreateChannelBtn.addEventListener('click', () => {
createChannel(el.newChannelName.value.trim(), el.newChannelTopic.value.trim()); createChannel(el.newChannelName.value.trim(), el.newChannelTopic.value.trim());
}); });
}
if (el.newChannelName) {
el.newChannelName.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
e.preventDefault();
createChannel(el.newChannelName.value.trim(), el.newChannelTopic.value.trim());
}
});
}
if (el.newChannelTopic) {
el.newChannelTopic.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
e.preventDefault();
createChannel(el.newChannelName.value.trim(), el.newChannelTopic.value.trim());
}
});
}
// Toggle In-Chat Online Members Sidebar
if (el.toggleMembersBtn && el.chatMembersSidebar) {
el.toggleMembersBtn.addEventListener('click', () => {
el.chatMembersSidebar.classList.toggle('closed');
});
}
// In-chat Channel Selector Dropdown // In-chat Channel Selector Dropdown
if (el.channelSelectDropdown) { if (el.channelSelectDropdown) {

View file

@ -72,8 +72,15 @@
</select> </select>
<span class="channel-topic" id="activeChannelTopic"></span> <span class="channel-topic" id="activeChannelTopic"></span>
</div> </div>
<div class="chat-header-actions">
<button type="button" class="btn btn-sm btn-outline-members" id="toggleMembersBtn" title="Toggle Online Members">
👥 <span class="members-btn-label">Online</span> (<span id="chatHeaderOnlineCount">0</span>)
</button>
</div>
</div> </div>
<div class="chat-content-container">
<div class="chat-main-area">
<div class="chat-messages" id="chatMessages"> <div class="chat-messages" id="chatMessages">
<div class="welcome-message"> <div class="welcome-message">
<h3 id="welcomeMotd">Welcome to GsDChat!</h3> <h3 id="welcomeMotd">Welcome to GsDChat!</h3>
@ -89,6 +96,18 @@
<input type="text" id="messageInput" placeholder="Message #general... (or /help)" autocomplete="off"> <input type="text" id="messageInput" placeholder="Message #general... (or /help)" autocomplete="off">
<button class="btn btn-primary send-btn" id="sendBtn">Send</button> <button class="btn btn-primary send-btn" id="sendBtn">Send</button>
</div> </div>
</div>
<aside class="chat-members-sidebar" id="chatMembersSidebar">
<div class="members-sidebar-header">
<span>Online Members</span>
<span class="member-count-badge" id="chatOnlineCountBadge">0</span>
</div>
<div class="chat-online-users-list" id="chatOnlineUsersList">
<!-- Populated by JS -->
</div>
</aside>
</div>
</section> </section>
<!-- View 2: Channels View --> <!-- View 2: Channels View -->
@ -123,7 +142,7 @@
<section id="view-users" class="tab-view"> <section id="view-users" class="tab-view">
<div class="view-header"> <div class="view-header">
<h2>Community Members</h2> <h2>Community Members</h2>
<span class="user-count-badge" id="userCountBadge">0 Online</span> <span class="user-count-badge" id="userCountBadge">0 Online / 0 Total</span>
</div> </div>
<div class="user-list" id="userList"> <div class="user-list" id="userList">
<!-- Populated by JS --> <!-- Populated by JS -->

View file

@ -269,4 +269,95 @@ public class EndToEndChatTests : IAsyncLifetime
string downloadedText = await File.ReadAllTextAsync(downloadedFilePath); string downloadedText = await File.ReadAllTextAsync(downloadedFilePath);
Assert.Equal(fileContent, downloadedText); Assert.Equal(fileContent, downloadedText);
} }
[Fact]
public async Task ChannelCreationAndSelection_ShouldSyncState()
{
var stateAlice = new ClientState { ServerUrl = _serverUrl };
using var connAlice = new ChatClientConnection(stateAlice);
var regAlice = await connAlice.RegisterAsync("AliceChannelAdmin", "Password123!");
Assert.True(regAlice.Success);
stateAlice.Token = regAlice.Token!;
stateAlice.CurrentUserId = regAlice.UserId!;
stateAlice.CurrentUsername = regAlice.Username!;
stateAlice.CurrentUserRole = regAlice.Role!;
await connAlice.StartWebSocketAsync();
await Task.Delay(300);
Assert.True(stateAlice.Channels.Count >= 2);
int initialCount = stateAlice.Channels.Count;
// Create new channel
await connAlice.CreateChannelAsync("dev-team", "Developers room");
// Wait for channel list sync
for (int i = 0; i < 20; i++)
{
if (stateAlice.Channels.Count > initialCount) break;
await Task.Delay(100);
}
Assert.Equal(initialCount + 1, stateAlice.Channels.Count);
var newChannel = stateAlice.Channels.Find(c => c.Name == "dev-team");
Assert.NotNull(newChannel);
// Join new channel
await connAlice.JoinChannelAsync(newChannel.Id);
for (int i = 0; i < 20; i++)
{
if (stateAlice.ActiveChannelId == newChannel.Id) break;
await Task.Delay(100);
}
Assert.Equal(newChannel.Id, stateAlice.ActiveChannelId);
}
[Fact]
public async Task BroadcastUserList_ShouldMarkConnectedUsersAsOnline()
{
var stateAlice = new ClientState { ServerUrl = _serverUrl };
using var connAlice = new ChatClientConnection(stateAlice);
var regAlice = await connAlice.RegisterAsync("AliceOnline", "Pass1234!");
Assert.True(regAlice.Success);
stateAlice.Token = regAlice.Token!;
stateAlice.CurrentUserId = regAlice.UserId!;
var stateBob = new ClientState { ServerUrl = _serverUrl };
using var connBob = new ChatClientConnection(stateBob);
var regBob = await connBob.RegisterAsync("BobOnline", "Pass1234!");
Assert.True(regBob.Success);
stateBob.Token = regBob.Token!;
stateBob.CurrentUserId = regBob.UserId!;
await connAlice.StartWebSocketAsync();
await connBob.StartWebSocketAsync();
for (int i = 0; i < 30; i++)
{
if (stateAlice.Users.Count(u => u.IsOnline) >= 2) break;
await Task.Delay(100);
}
Assert.Equal(2, stateAlice.Users.Count(u => u.IsOnline));
// When Bob disconnects, Alice's user list should reflect Bob as offline
connBob.Dispose();
for (int i = 0; i < 30; i++)
{
if (stateAlice.Users.Count(u => u.IsOnline) == 1) break;
await Task.Delay(100);
}
Assert.Equal(1, stateAlice.Users.Count(u => u.IsOnline));
var aliceUser = stateAlice.Users.Find(u => u.Username == "AliceOnline");
Assert.NotNull(aliceUser);
Assert.True(aliceUser.IsOnline);
}
} }