Добавленно TUI

This commit is contained in:
2026-03-05 23:00:24 +04:00
parent 3d57b2a574
commit 479014a03b
4 changed files with 233 additions and 13 deletions

45
TUI/InputHelper.cs Normal file
View File

@@ -0,0 +1,45 @@
using System;
namespace su.divan2000.UtilsTUI
{
public static class InputHelper
{
public static double AskDouble(string prompt)
{
double val;
while (true)
{
Console.Write(prompt);
if (double.TryParse(Console.ReadLine(), out val))
return val;
Console.WriteLine("Некорректный ввод. Введите число в формате 1.0, 2.5 и т.д.");
}
}
public static int AskInt(string prompt)
{
int val;
while (true)
{
Console.Write(prompt);
if (int.TryParse(Console.ReadLine(), out val))
return val;
Console.WriteLine("Некорректный ввод. Введите целое число.");
}
}
public static bool AskYesNo(string prompt)
{
while (true)
{
Console.Write(prompt);
string? s = Console.ReadLine()?.Trim().ToLower();
if (s == "да") return true;
if (s == "нет") return false;
Console.WriteLine("Введите 'да' или 'нет'.");
}
}
}
}

109
TUI/Menu.cs Normal file
View File

@@ -0,0 +1,109 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace su.divan2000.UtilsTUI
{
/// <summary>
/// TUI menu;
/// </summary>
internal class Menu
{
private List<Option> options;
private int selected;
private string title;
/// <summary>
/// Constructor of menu;
/// </summary>
/// <param name="title">Title of menu</param>
public Menu(string title)
{
this.title = title;
this.options = new List<Option> { };
}
/// <summary>
/// Add option to menu;
/// </summary>
/// <param name="name">Name of option</param>
/// <param name="action">Action, runs if option selected</param>
public void AddOption(string name, Action action)
{
this.options.Add(new Option(name, action));
}
/// <summary>
/// Set title of menu;
/// </summary>
/// <param name="title">New title of menu</param>
public void SetTitle(string title)
{
this.title = title;
}
/// <summary>
/// Run menu;
/// Console will be clean!;
/// </summary>
public void RunMenu()
{
selected = 0;
this.PrintMenu();
ConsoleKeyInfo keyinfo;
do
{
keyinfo = Console.ReadKey();
if (keyinfo.Key == ConsoleKey.DownArrow)
{
if (selected + 1 < options.Count)
{
selected++;
this.PrintMenu();
}
}
if (keyinfo.Key == ConsoleKey.UpArrow)
{
if (selected > 0)
{
selected--;
this.PrintMenu();
}
}
if (keyinfo.Key == ConsoleKey.Enter)
{
Console.Clear();
options[selected].Action.Invoke();
}
} while (keyinfo.Key != ConsoleKey.Enter);
}
private void PrintMenu()
{
Console.Clear();
Console.WriteLine(title);
int optionIndex = 0;
foreach (Option option in options)
{
string pointer = optionIndex == selected ? " ->" : " ";
Console.WriteLine($"{pointer}{option.Name}");
optionIndex++;
}
}
private struct Option
{
public string Name { get; }
public Action Action { get; }
public Option(string name, Action action)
{
Name = name;
Action = action;
}
}
}
}