feat: add terminal text measurer

- measure terminal display width for text and escape sequences

- truncate rendered lines to terminal columns

- add width and truncation examples
This commit is contained in:
chuan
2026-06-03 22:14:35 +08:00
parent d385348c62
commit 7103f8acc0
3 changed files with 183 additions and 5 deletions
+12 -3
View File
@@ -5,14 +5,16 @@ using TinyTUI.Rendering;
using TinyTUI.Runtime;
using TinyTUI.Stdio;
using TinyTUI.Stdout;
using TinyTUI.Text;
using var terminalInput = new ConsoleTerminalInput();
var terminalOutput = new ConsoleTerminalOutput();
var parser = new DefaultInputParser();
var renderer = new FullScreenRenderer(terminalOutput);
var textMeasurer = new TerminalTextMeasurer();
var renderer = new FullScreenRenderer(terminalOutput, textMeasurer);
using var runtime = new TuiRuntime(terminalInput, parser, renderer);
var component = new EchoComponent(runtime);
var component = new EchoComponent(runtime, textMeasurer);
runtime.Add(component);
runtime.SetFocus(component);
@@ -34,7 +36,7 @@ finally
/// <summary>
/// 用于手动验证 Runtime 的示例组件
/// </summary>
file sealed class EchoComponent(ITuiRuntime runtime) : IInputComponent
file sealed class EchoComponent(ITuiRuntime runtime, ITextMeasurer textMeasurer) : IInputComponent
{
private readonly ManualResetEventSlim _done = new();
private readonly List<string> _events = [];
@@ -54,6 +56,13 @@ file sealed class EchoComponent(ITuiRuntime runtime) : IInputComponent
"- 调整窗口大小 验证 Resize 事件会进入焦点组件并触发重渲染",
"- 按 Esc 退出",
string.Empty,
"宽度示例:",
$"字符串 \"abc\" 的终端宽度 = {textMeasurer.GetWidth("abc")}",
$"字符串 \"\" 的终端宽度 = {textMeasurer.GetWidth("")}",
$"字符串 \"😀\" 的终端宽度 = {textMeasurer.GetWidth("😀")}",
$"截断前 \"abc中文😀xyz\" 的终端宽度 = {textMeasurer.GetWidth("abc中文😀xyz")}",
$"截断到 8 列后的结果 = \"{textMeasurer.Truncate("abc中文😀xyz", 8)}\"",
string.Empty,
"最近事件:",
};