This commit is contained in:
tyuXX 2026-10-10 16:40:35 +00:00
commit f25ba8adcd
64 changed files with 5959 additions and 0 deletions

View file

@ -0,0 +1,240 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GsDChat.Client.Network;
using GsDChat.Client.Rendering;
using GsDChat.Client.State;
namespace GsDChat.Client.Screens;
public class ChatScreen : IScreen
{
private readonly ClientState _state;
private readonly ChatClientConnection _connection;
public string ScreenId => "F1_Chat";
public string Title => "Chat";
public string ShortcutKey => "F1";
public ChatScreen(ClientState state, ChatClientConnection connection)
{
_state = state;
_connection = connection;
}
public void Render(int width, int height, StringBuilder sb)
{
var ch = _state.ActiveChannel;
string chName = ch != null ? $"#{ch.Name}" : "(no channel)";
string topic = ch != null && !string.IsNullOrEmpty(ch.Topic) ? $" - {ch.Topic}" : "";
// Header line
string header = $" {Ansi.Bold}{Ansi.Cyan}{chName}{Ansi.Reset}{Ansi.Gray}{topic}{Ansi.Reset}";
sb.AppendLine(PadOrTruncate(header, width));
sb.AppendLine(new string('─', Math.Max(0, width)));
// Messages area: height minus (Header: 2, Footer/Input: 3, Tab bar & status: 3) = height - 8
int msgAreaHeight = Math.Max(3, height - 8);
List<Core.Models.ChatMessage> messages = new();
if (!string.IsNullOrEmpty(_state.ActiveChannelId) &&
_state.ChannelMessages.TryGetValue(_state.ActiveChannelId, out var msgs))
{
messages = msgs;
}
// Viewport calculation with scroll offset
int totalMessages = messages.Count;
int maxScroll = Math.Max(0, totalMessages - msgAreaHeight);
int scroll = Math.Clamp(_state.ChatScrollOffset, 0, maxScroll);
int startIndex = Math.Max(0, totalMessages - msgAreaHeight - scroll);
int countToTake = Math.Min(msgAreaHeight, totalMessages - startIndex);
var visible = messages.Skip(startIndex).Take(countToTake).ToList();
// Print blank lines if fewer messages than viewport height
int emptyLines = msgAreaHeight - visible.Count;
for (int i = 0; i < emptyLines; i++)
{
sb.AppendLine();
}
foreach (var msg in visible)
{
string time = msg.CreatedAt.ToLocalTime().ToString("HH:mm:ss");
string roleColor = msg.SenderRole switch
{
"Owner" => Ansi.BrightYellow,
"Admin" => Ansi.BrightMagenta,
_ => Ansi.BrightCyan
};
string line;
if (!string.IsNullOrEmpty(msg.AttachmentId))
{
line = $" {Ansi.Gray}[{time}]{Ansi.Reset} <{roleColor}@{msg.SenderUsername}{Ansi.Reset}> {Ansi.BrightYellow}📎 [{msg.AttachmentName} - {FileStorageServiceFormat(msg.AttachmentSizeBytes ?? 0)}]{Ansi.Reset}";
}
else
{
line = $" {Ansi.Gray}[{time}]{Ansi.Reset} <{roleColor}@{msg.SenderUsername}{Ansi.Reset}> {msg.Content}";
}
sb.AppendLine(PadOrTruncate(line, width));
}
// Divider
sb.AppendLine(new string('─', Math.Max(0, width)));
// Input Line
string prompt = $" {Ansi.Cyan}[{chName}] > {Ansi.Reset}";
string inputDisplay = _state.InputBuffer + "█";
sb.AppendLine(prompt + inputDisplay);
}
public async Task HandleKeyAsync(ConsoleKeyInfo key)
{
if (key.Key == ConsoleKey.Enter)
{
string text = _state.InputBuffer.Trim();
_state.InputBuffer = string.Empty;
if (string.IsNullOrEmpty(text)) return;
if (text.StartsWith("/"))
{
await HandleSlashCommandAsync(text);
}
else
{
if (!string.IsNullOrEmpty(_state.ActiveChannelId))
{
await _connection.SendChatMessageAsync(_state.ActiveChannelId, text);
}
else
{
_state.SetStatus("Please join a channel first (Press F2).");
}
}
_state.ChatScrollOffset = 0;
_state.NeedsRedraw = true;
}
else if (key.Key == ConsoleKey.Backspace)
{
if (_state.InputBuffer.Length > 0)
{
_state.InputBuffer = _state.InputBuffer[..^1];
_state.NeedsRedraw = true;
}
}
else if (key.Key == ConsoleKey.PageUp)
{
_state.ChatScrollOffset += 5;
_state.NeedsRedraw = true;
}
else if (key.Key == ConsoleKey.PageDown)
{
_state.ChatScrollOffset = Math.Max(0, _state.ChatScrollOffset - 5);
_state.NeedsRedraw = true;
}
else if (key.Key == ConsoleKey.Escape)
{
_state.InputBuffer = string.Empty;
_state.NeedsRedraw = true;
}
else if (!char.IsControl(key.KeyChar))
{
_state.InputBuffer += key.KeyChar;
_state.NeedsRedraw = true;
}
}
private async Task HandleSlashCommandAsync(string input)
{
string[] parts = input.Split(' ', 2);
string cmd = parts[0].TrimStart('/').ToLowerInvariant();
string args = parts.Length > 1 ? parts[1].Trim() : string.Empty;
switch (cmd)
{
case "join":
if (string.IsNullOrEmpty(args))
{
_state.SetStatus("Usage: /join <channel_name>");
return;
}
var target = _state.Channels.FirstOrDefault(c => c.Name.Equals(args.TrimStart('#'), StringComparison.OrdinalIgnoreCase));
if (target != null)
{
await _connection.JoinChannelAsync(target.Id);
_state.SetStatus($"Joined #{target.Name}");
}
else
{
_state.SetStatus($"Channel #{args} not found.");
}
break;
case "create":
if (string.IsNullOrEmpty(args))
{
_state.SetStatus("Usage: /create <channel_name> [topic]");
return;
}
var createParts = args.Split(' ', 2);
string newName = createParts[0];
string newTopic = createParts.Length > 1 ? createParts[1] : string.Empty;
await _connection.CreateChannelAsync(newName, newTopic);
break;
case "upload":
if (string.IsNullOrEmpty(args))
{
_state.SetStatus("Usage: /upload <local_file_path>");
return;
}
if (string.IsNullOrEmpty(_state.ActiveChannelId))
{
_state.SetStatus("Select an active channel first.");
return;
}
_state.SetStatus($"Uploading {args}...");
await _connection.UploadFileAsync(args, _state.ActiveChannelId);
break;
case "download":
if (string.IsNullOrEmpty(args))
{
_state.SetStatus("Usage: /download <file_id>");
return;
}
_state.SetStatus($"Downloading file {args}...");
await _connection.DownloadFileAsync(args, "downloads");
break;
default:
await _connection.ExecuteCommandAsync(cmd, args, _state.ActiveChannelId);
break;
}
}
private static string FileStorageServiceFormat(long bytes)
{
string[] suffixes = { "B", "KB", "MB", "GB" };
int order = 0;
double size = bytes;
while (size >= 1024 && order < suffixes.Length - 1)
{
order++;
size /= 1024;
}
return $"{size:0.##} {suffixes[order]}";
}
private static string PadOrTruncate(string str, int width)
{
if (width <= 0) return string.Empty;
return str;
}
}