Compare commits

...

6 Commits

Author SHA1 Message Date
Patrik Svensson
8a01b93aca Don't limit tables and grids to markup text
Closes #13
2020-08-24 23:28:40 +02:00
Patrik Svensson
effdecb1d4 Add GitHub Sponsors data (skip-ci) 2020-08-24 12:04:01 +02:00
Patrik Svensson
4cfe55cc27 Emit native line breaks 2020-08-16 13:47:57 +02:00
Patrik Svensson
5b33f80213 Fix line ending problem with text 2020-08-16 12:26:51 +02:00
Patrik Svensson
d7bbaf4a85 Add word wrapping for text
Closes #18
2020-08-14 18:19:24 +02:00
Patrik Svensson
0119364728 Add examples of how to use Spectre.Console 2020-08-12 14:59:17 +02:00
61 changed files with 1486 additions and 734 deletions

1
.github/funding.yml vendored Normal file
View File

@@ -0,0 +1 @@
github: patriksvensson

View File

@@ -13,8 +13,9 @@ for Python.
3. [Usage](#usage)
3.1. [Using the static API](#using-the-static-api)
3.2. [Creating a console](#creating-a-console)
4. [Available styles](#available-styles)
5. [Predefined colors](#predefined-colors)
4. [Running examples](#running-examples)
5. [Available styles](#available-styles)
6. [Predefined colors](#predefined-colors)
## Features
@@ -84,6 +85,42 @@ when manually creating a console, remember that the user's terminal
might not be able to use it, so unless you're creating an IAnsiConsole
for testing, always use `ColorSystemSupport.Detect` and `AnsiSupport.Detect`._
## Running examples
To see Spectre.Console in action, install the
[dotnet-example](https://github.com/patriksvensson/dotnet-example)
global tool.
```
> dotnet tool install -g dotnet-example
```
Now you can list available examples in this repository:
```
> dotnet example
Examples
Colors Demonstrates how to use colors in the console.
Grid Demonstrates how to render grids in a console.
Panel Demonstrates how to render items in panels.
Table Demonstrates how to render tables in a console.
```
And to run an example:
```
> dotnet example table
┌──────────┬──────────┬────────┐
│ Foo │ Bar │ Baz │
├──────────┼──────────┼────────┤
│ Hello │ World! │ │
│ Bounjour │ le │ monde! │
│ Hej │ Världen! │ │
└──────────┴──────────┴────────┘
```
## Available styles
_NOTE: Not all styles are supported in every terminal._

View File

@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
<IsPackable>false</IsPackable>
<Description>Demonstrates how to use [yellow]c[/][red]o[/][green]l[/][blue]o[/][aqua]r[/][lime]s[/] in the console.</Description>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\Spectre.Console\Spectre.Console.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,78 @@
using Spectre.Console;
namespace ColorExample
{
class Program
{
static void Main(string[] args)
{
/////////////////////////////////////////////////////////////////
// 4-BIT
/////////////////////////////////////////////////////////////////
AnsiConsole.ResetColors();
AnsiConsole.WriteLine();
AnsiConsole.MarkupLine("[bold underline]4-bit Colors[/]");
AnsiConsole.WriteLine();
for (var i = 0; i < 16; i++)
{
AnsiConsole.Background = Color.FromInt32(i);
AnsiConsole.Write(string.Format(" {0,-9}", AnsiConsole.Background.ToString()));
AnsiConsole.ResetColors();
if ((i + 1) % 8 == 0)
{
AnsiConsole.WriteLine();
}
}
/////////////////////////////////////////////////////////////////
// 8-BIT
/////////////////////////////////////////////////////////////////
AnsiConsole.ResetColors();
AnsiConsole.WriteLine();
AnsiConsole.MarkupLine("[bold underline]8-bit Colors[/]");
AnsiConsole.WriteLine();
for (var i = 0; i < 16; i++)
{
for (var j = 0; j < 16; j++)
{
var number = i * 16 + j;
AnsiConsole.Background = Color.FromInt32(number);
AnsiConsole.Write(string.Format(" {0,-4}", number));
AnsiConsole.ResetColors();
if ((number + 1) % 16 == 0)
{
AnsiConsole.WriteLine();
}
}
}
/////////////////////////////////////////////////////////////////
// 24-BIT
/////////////////////////////////////////////////////////////////
AnsiConsole.ResetColors();
AnsiConsole.WriteLine();
AnsiConsole.MarkupLine("[bold underline]24-bit Colors[/]");
AnsiConsole.WriteLine();
var index = 0;
for (var i = 0.0005; i < 1; i += 0.0025)
{
index++;
var color = Utilities.HSL2RGB(i, 0.5, 0.5);
AnsiConsole.Background = new Color(color.R, color.G, color.B);
AnsiConsole.Write(" ");
if (index % 50 == 0)
{
AnsiConsole.WriteLine();
}
}
}
}
}

View File

@@ -0,0 +1,77 @@
using System;
using Spectre.Console;
namespace ColorExample
{
public static class Utilities
{
// Borrowed from https://geekymonkey.com/Programming/CSharp/RGB2HSL_HSL2RGB.htm
public static Color HSL2RGB(double h, double sl, double l)
{
double v;
double r, g, b;
r = l; // default to gray
g = l;
b = l;
v = (l <= 0.5) ? (l * (1.0 + sl)) : (l + sl - l * sl);
if (v > 0)
{
double m;
double sv;
int sextant;
double fract, vsf, mid1, mid2;
m = l + l - v;
sv = (v - m) / v;
h *= 6.0;
sextant = (int)h;
fract = h - sextant;
vsf = v * sv * fract;
mid1 = m + vsf;
mid2 = v - vsf;
switch (sextant)
{
case 0:
r = v;
g = mid1;
b = m;
break;
case 1:
r = mid2;
g = v;
b = m;
break;
case 2:
r = m;
g = v;
b = mid1;
break;
case 3:
r = m;
g = mid2;
b = v;
break;
case 4:
r = mid1;
g = m;
b = v;
break;
case 5:
r = v;
g = m;
b = mid2;
break;
}
}
return new Color(
Convert.ToByte(r * 255.0f),
Convert.ToByte(g * 255.0f),
Convert.ToByte(b * 255.0f));
}
}
}

14
examples/Grid/Grid.csproj Normal file
View File

@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
<IsPackable>false</IsPackable>
<Description>Demonstrates how to render grids in a console.</Description>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\Spectre.Console\Spectre.Console.csproj" />
</ItemGroup>
</Project>

25
examples/Grid/Program.cs Normal file
View File

@@ -0,0 +1,25 @@
using Spectre.Console;
namespace GridExample
{
public sealed class Program
{
static void Main(string[] args)
{
AnsiConsole.WriteLine();
AnsiConsole.MarkupLine("Usage: [grey]dotnet [blue]run[/] [[options] [[[[--] <additional arguments>...]][/]");
AnsiConsole.WriteLine();
var grid = new Grid();
grid.AddColumn(new GridColumn { NoWrap = true });
grid.AddColumn(new GridColumn { NoWrap = true, Width = 2 });
grid.AddColumn();
grid.AddRow("Options:", "", "");
grid.AddRow(" [blue]-h[/], [blue]--help[/]", "", "Show command line help.");
grid.AddRow(" [blue]-c[/], [blue]--configuration[/] <CONFIGURATION>", "", "The configuration to run for.");
grid.AddRow(" [blue]-v[/], [blue]--verbosity[/] <LEVEL>", "", "Set the [grey]MSBuild[/] verbosity level.");
AnsiConsole.Render(grid);
}
}
}

View File

@@ -3,12 +3,12 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
<RunAnalyzersDuringBuild>false</RunAnalyzersDuringBuild>
<IsPackable>false</IsPackable>
<Description>Demonstrates how to render items in panels.</Description>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Spectre.Console\Spectre.Console.csproj" />
<ProjectReference Include="..\..\src\Spectre.Console\Spectre.Console.csproj" />
</ItemGroup>
</Project>

49
examples/Panel/Program.cs Normal file
View File

@@ -0,0 +1,49 @@
using Spectre.Console;
namespace PanelExample
{
class Program
{
static void Main(string[] args)
{
var content = Text.Markup(
"[underline]I[/] heard [underline on blue]you[/] like 📦\n\n\n\n" +
"So I put a 📦 in a 📦\n\n" +
"😅");
AnsiConsole.Render(
new Panel(
new Panel(content)
{
Alignment = Justify.Center,
Border = BorderKind.Rounded
}));
// Left adjusted panel with text
AnsiConsole.Render(new Panel(
new Text("Left adjusted\nLeft"))
{
Expand = true,
Alignment = Justify.Left,
});
// Centered ASCII panel with text
AnsiConsole.Render(new Panel(
new Text("Centered\nCenter"))
{
Expand = true,
Alignment = Justify.Center,
Border = BorderKind.Ascii,
});
// Right adjusted, rounded panel with text
AnsiConsole.Render(new Panel(
new Text("Right adjusted\nRight"))
{
Expand = true,
Alignment = Justify.Right,
Border = BorderKind.Rounded,
});
}
}
}

90
examples/Table/Program.cs Normal file
View File

@@ -0,0 +1,90 @@
using Spectre.Console;
namespace TableExample
{
class Program
{
static void Main(string[] args)
{
// A simple table§
RenderSimpleTable();
// A big table
RenderBigTable();
// A complex table
RenderComplexTable();
}
private static void RenderComplexTable()
{
// Create simple table.
var simple = new Table { Border = BorderKind.Rounded };
simple.AddColumn(new TableColumn("[u]Foo[/]").Centered());
simple.AddColumn(new TableColumn("[u]Bar[/]"));
simple.AddColumn(new TableColumn("[u]Baz[/]"));
simple.AddRow("Hello", "[red]World![/]", "");
simple.AddRow("[blue]Bounjour[/]", "[white]le[/]", "[red]monde![/]");
simple.AddRow("[blue]Hej[/]", "[yellow]Världen![/]", "");
// Create other table.
var second = new Table { Border = BorderKind.Square };
second.AddColumn(new TableColumn("[u]Foo[/]"));
second.AddColumn(new TableColumn("[u]Bar[/]"));
second.AddColumn(new TableColumn("[u]Baz[/]"));
second.AddRow("Hello", "[red]World![/]", "");
second.AddRow(simple, new Text("Whaaat"), new Text("Lolz"));
second.AddRow("[blue]Hej[/]", "[yellow]Världen![/]", "");
var table = new Table { Border = BorderKind.Rounded };
table.AddColumn(new TableColumn(new Panel("[u]Foo[/]")));
table.AddColumn(new TableColumn(new Panel("[u]Bar[/]")));
table.AddColumn(new TableColumn(new Panel("[u]Baz[/]")));
// Add some rows
table.AddRow(new Text("Hello").Centered(), new Markup("[red]World![/] 🌍"), Text.Empty);
table.AddRow(second, new Text("Whaaat"), new Text("Lol"));
table.AddRow(new Markup("[blue]Hej[/]").Centered(), new Markup("[yellow]Världen![/]"), Text.Empty);
AnsiConsole.Render(table);
}
private static void RenderSimpleTable()
{
// Create the table.
var table = new Table();
table.AddColumn(new TableColumn("[u]Foo[/]"));
table.AddColumn(new TableColumn("[u]Bar[/]"));
table.AddColumn(new TableColumn("[u]Baz[/]"));
// Add some rows
table.AddRow("Hello", "[red]World![/]", "");
table.AddRow("[blue]Bounjour[/]", "[white]le[/]", "[red]monde![/]");
table.AddRow("[blue]Hej[/]", "[yellow]Världen![/]", "");
AnsiConsole.Render(table);
}
private static void RenderBigTable()
{
// Create the table.
var table = new Table { Border = BorderKind.Rounded };
table.AddColumn("[red underline]Foo[/]");
table.AddColumn(new TableColumn("[blue]Bar[/]") { Alignment = Justify.Right, NoWrap = true });
// Add some rows
table.AddRow("[blue][underline]Hell[/]o[/]", "World 🌍");
table.AddRow("[yellow]Patrik [green]\"Hello World\"[/] Svensson[/]", "Was [underline]here[/]!");
table.AddEmptyRow();
table.AddRow(
"Lorem ipsum dolor sit amet, consectetur adipiscing elit,sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. " +
"Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure " +
"dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat " +
"non proident, sunt in culpa qui officia deserunt mollit anim id est laborum", "◀ Strange language");
table.AddEmptyRow();
table.AddRow("Hej 👋", "[green]Världen[/]");
AnsiConsole.Render(table);
}
}
}

View File

@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
<IsPackable>false</IsPackable>
<Description>Demonstrates how to render tables in a console.</Description>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\Spectre.Console\Spectre.Console.csproj" />
</ItemGroup>
</Project>

View File

@@ -81,3 +81,6 @@ dotnet_diagnostic.RCS1079.severity = warning
# RCS1057: Add empty line between declarations.
dotnet_diagnostic.RCS1057.severity = none
# IDE0004: Remove Unnecessary Cast
dotnet_diagnostic.IDE0004.severity = warning

View File

@@ -1,8 +0,0 @@
root = false
[*.cs]
# Default severity for all analyzer diagnostics
dotnet_analyzer_diagnostic.severity = none
# CS1591: Missing XML comment for publicly visible type or member
dotnet_diagnostic.CS1591.severity = none

View File

@@ -1,169 +0,0 @@
using System;
using Spectre.Console;
namespace Sample
{
public static class Program
{
public static void Main(string[] args)
{
// Use the static API to write some things to the console.
AnsiConsole.Foreground = Color.Chartreuse2;
AnsiConsole.Decoration = Decoration.Underline | Decoration.Bold;
AnsiConsole.WriteLine("Hello World!");
AnsiConsole.Reset();
AnsiConsole.MarkupLine("Capabilities: [yellow underline]{0}[/]", AnsiConsole.Capabilities);
AnsiConsole.MarkupLine("Encoding: [yellow underline]{0}[/]", AnsiConsole.Console.Encoding.EncodingName);
AnsiConsole.MarkupLine("Width=[yellow]{0}[/], Height=[yellow]{1}[/]", AnsiConsole.Width, AnsiConsole.Height);
AnsiConsole.MarkupLine("[white on red]Good[/] [red]bye[/]!");
AnsiConsole.WriteLine();
// We can also use System.ConsoleColor with AnsiConsole
// to set the foreground and background color.
foreach (ConsoleColor value in Enum.GetValues(typeof(ConsoleColor)))
{
var foreground = value;
var background = (ConsoleColor)(15 - (int)value);
AnsiConsole.Foreground = foreground;
AnsiConsole.Background = background;
AnsiConsole.WriteLine("{0} on {1}", foreground, background);
AnsiConsole.ResetColors();
}
// We can get the default console via the static API.
var console = AnsiConsole.Console;
// Or you can build it yourself the old fashion way.
console = AnsiConsole.Create(
new AnsiConsoleSettings()
{
Ansi = AnsiSupport.Yes,
ColorSystem = ColorSystemSupport.Standard,
Out = Console.Out,
});
// In this case, we will find the closest colors
// and downgrade them to the specified color system.
console.WriteLine();
console.Foreground = Color.Chartreuse2;
console.Decoration = Decoration.Underline | Decoration.Bold;
console.WriteLine("Hello World!");
console.ResetColors();
console.ResetDecoration();
console.MarkupLine("Capabilities: [yellow underline]{0}[/]", console.Capabilities);
console.MarkupLine("Encoding: [yellow underline]{0}[/]", AnsiConsole.Console.Encoding.EncodingName);
console.MarkupLine("Width=[yellow]{0}[/], Height=[yellow]{1}[/]", console.Width, console.Height);
console.MarkupLine("[white on red]Good[/] [red]bye[/]!");
console.WriteLine();
// Nest some panels and text
AnsiConsole.Foreground = Color.Maroon;
AnsiConsole.Render(
new Panel(
new Panel(
new Panel(
new Panel(
Text.New(
"[underline]I[/] heard [underline on blue]you[/] like 📦\n\n\n\n" +
"So I put a 📦 in a 📦\nin a 📦 in a 📦\n\n" +
"😅", foreground: Color.White))
{ Alignment = Justify.Center, Border = BorderKind.Rounded })))
{
Border = BorderKind.Ascii
});
// Reset colors
AnsiConsole.ResetColors();
// Left adjusted panel with text
AnsiConsole.Render(new Panel(
Text.New("Left adjusted\nLeft"))
{
Expand = true,
Alignment = Justify.Left,
});
// Centered panel with text
AnsiConsole.Render(new Panel(
Text.New("Centered\nCenter"))
{
Expand = true,
Alignment = Justify.Center,
});
// Right adjusted panel with text
AnsiConsole.Render(new Panel(
Text.New("Right adjusted\nRight"))
{
Expand = true,
Alignment = Justify.Right,
});
// A normal, square table
var table = new Table();
table.AddColumns("[red underline]Foo[/]", "Bar");
table.AddRow("[blue][underline]Hell[/]o[/]", "World 🌍");
table.AddRow("[yellow]Patrik [green]\"Lol[/]\" Svensson[/]", "Was [underline]here[/]!");
table.AddRow("Lorem ipsum dolor sit amet, consectetur adipiscing elit,sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum", "◀ Strange language");
table.AddRow("Hej 👋", "[green]Världen[/]");
AnsiConsole.Render(table);
// A rounded table
table = new Table { Border = BorderKind.Rounded };
table.AddColumns("[red underline]Foo[/]", "Bar");
table.AddRow("[blue][underline]Hell[/]o[/]", "World 🌍");
table.AddRow("[yellow]Patrik [green]\"Lol[/]\" Svensson[/]", "Was [underline]here[/]!");
table.AddRow("Lorem ipsum dolor sit amet, consectetur [blue]adipiscing[/] elit,sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum", "◀ Strange language");
table.AddRow("Hej 👋", "[green]Världen[/]");
AnsiConsole.Render(table);
// A rounded table without headers
table = new Table { Border = BorderKind.Rounded, ShowHeaders = false };
table.AddColumns("[red underline]Foo[/]", "Bar");
table.AddRow("[blue][underline]Hell[/]o[/]", "World 🌍");
table.AddRow("[yellow]Patrik [green]\"Lol[/]\" Svensson[/]", "Was [underline]here[/]!");
table.AddRow("Lorem ipsum dolor sit amet, consectetur [blue]adipiscing[/] elit,sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum", "◀ Strange language");
table.AddRow("Hej 👋", "[green]Världen[/]");
AnsiConsole.Render(table);
// Emulate the usage information for "dotnet run"
AnsiConsole.WriteLine();
AnsiConsole.MarkupLine("Usage: [grey]dotnet [blue]run[/] [[options] [[[[--] <additional arguments>...]][/]");
AnsiConsole.WriteLine();
var grid = new Grid();
grid.AddColumn(new GridColumn { NoWrap = true });
grid.AddColumn(new GridColumn { NoWrap = true, Width = 2 });
grid.AddColumn();
grid.AddRow("Options:", "", "");
grid.AddRow(" [blue]-h[/], [blue]--help[/]", "", "Show command line help.");
grid.AddRow(" [blue]-c[/], [blue]--configuration[/] <CONFIGURATION>", "", "The configuration to run for.\nThe default for most projects is [green]Debug[/].");
grid.AddRow(" [blue]-v[/], [blue]--verbosity[/] <LEVEL>", "", "Set the MSBuild verbosity level. Allowed values are \nq[grey][[uiet][/], m[grey][[inimal][/], n[grey][[ormal][/], d[grey][[etailed][/], and diag[grey][[nostic][/].");
AnsiConsole.Render(grid);
// A simple table
AnsiConsole.WriteLine();
table = new Table { Border = BorderKind.Rounded };
table.AddColumn("Foo");
table.AddColumn("Bar");
table.AddColumn("Baz");
table.AddRow("Qux\nQuuuuuux", "[blue]Corgi[/]", "Waldo");
table.AddRow("Grault", "Garply", "Fred");
AnsiConsole.Render(table);
// Render a table in some panels.
AnsiConsole.Render(new Panel(new Panel(table) { Border = BorderKind.Ascii }) { Padding = new Padding(0, 0) });
// Draw another table
table = new Table { Expand = false };
table.AddColumn(new TableColumn("Date"));
table.AddColumn(new TableColumn("Title"));
table.AddColumn(new TableColumn("Production\nBudget"));
table.AddColumn(new TableColumn("Box Office"));
table.AddRow("Dec 20, 2019", "Star Wars: The Rise of Skywalker", "$275,000,000", "[red]$375,126,118[/]");
table.AddRow("May 25, 2018", "[yellow]Solo[/]: A Star Wars Story", "$275,000,000", "$393,151,347");
table.AddRow("Dec 15, 2017", "Star Wars Ep. VIII: The Last Jedi", "$262,000,000", "[bold green]$1,332,539,889[/]");
AnsiConsole.Render(table);
}
}
}

View File

@@ -2,7 +2,6 @@
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<IsPackable>false</IsPackable>
</PropertyGroup>

View File

@@ -12,7 +12,7 @@ namespace Spectre.Console.Tests.Unit
{
[Theory]
[InlineData("[yellow]Hello[/]", "Hello")]
[InlineData("[yellow]Hello [italic]World[/]![/]", "Hello World!")]
[InlineData("[yellow]Hello [italic]World[/]![/]", "Hello World!")]
public void Should_Output_Expected_Ansi_For_Markup(string markup, string expected)
{
// Given
@@ -26,7 +26,7 @@ namespace Spectre.Console.Tests.Unit
}
[Theory]
[InlineData("[yellow]Hello [[ World[/]", "Hello [ World")]
[InlineData("[yellow]Hello [[ World[/]", "Hello [ World")]
public void Should_Be_Able_To_Escape_Tags(string markup, string expected)
{
// Given

View File

@@ -1,9 +1,9 @@
using System;
using Shouldly;
using Spectre.Console.Composition;
using Spectre.Console.Rendering;
using Xunit;
namespace Spectre.Console.Tests.Unit.Composition
namespace Spectre.Console.Tests.Unit
{
public sealed class BorderTests
{

View File

@@ -1,91 +0,0 @@
using Shouldly;
using Xunit;
namespace Spectre.Console.Tests.Unit
{
public sealed class TextTests
{
[Fact]
public void Should_Render_Unstyled_Text_As_Expected()
{
// Given
var fixture = new PlainConsole(width: 80);
var text = Text.New("Hello World");
// When
fixture.Render(text);
// Then
fixture.Output
.NormalizeLineEndings()
.ShouldBe("Hello World");
}
[Fact]
public void Should_Write_Line_Breaks()
{
// Given
var fixture = new PlainConsole(width: 5);
var text = Text.New("\n\n");
// When
fixture.Render(text);
// Then
fixture.RawOutput.ShouldBe("\n\n");
}
[Fact]
public void Should_Split_Unstyled_Text_To_New_Lines_If_Width_Exceeds_Console_Width()
{
// Given
var fixture = new PlainConsole(width: 5);
var text = Text.New("Hello World");
// When
fixture.Render(text);
// Then
fixture.Output
.NormalizeLineEndings()
.ShouldBe("Hello\n Worl\nd");
}
public sealed class TheStylizeMethod
{
[Fact]
public void Should_Apply_Style_To_Text()
{
// Given
var fixture = new AnsiConsoleFixture(ColorSystem.Standard);
var text = Text.New("Hello World");
text.Stylize(start: 3, end: 8, new Style(decoration: Decoration.Underline));
// When
fixture.Console.Render(text);
// Then
fixture.Output
.NormalizeLineEndings()
.ShouldBe("Hello World");
}
[Fact]
public void Should_Apply_Style_To_Text_Which_Spans_Over_Multiple_Lines()
{
// Given
var fixture = new AnsiConsoleFixture(ColorSystem.Standard, width: 5);
var text = Text.New("Hello World");
text.Stylize(start: 3, end: 8, new Style(decoration: Decoration.Underline));
// When
fixture.Console.Render(text);
// Then
fixture.Output
.NormalizeLineEndings()
.ShouldBe("Hello\n Worl\nd");
}
}
}
}

View File

@@ -2,7 +2,7 @@ using System;
using Shouldly;
using Xunit;
namespace Spectre.Console.Tests.Unit.Composition
namespace Spectre.Console.Tests.Unit
{
public sealed class GridTests
{
@@ -95,6 +95,29 @@ namespace Spectre.Console.Tests.Unit.Composition
console.Lines[1].ShouldBe(" ");
console.Lines[2].ShouldBe("Qux Corgi");
}
[Fact]
public void Should_Add_Empty_Row_At_The_End()
{
// Given
var console = new PlainConsole(width: 80);
var grid = new Grid();
grid.AddColumns(2);
grid.AddRow("Foo", "Bar");
grid.AddEmptyRow();
grid.AddRow("Qux", "Corgi");
grid.AddEmptyRow();
// When
console.Render(grid);
// Then
console.Lines.Count.ShouldBe(4);
console.Lines[0].ShouldBe("Foo Bar ");
console.Lines[1].ShouldBe(" ");
console.Lines[2].ShouldBe("Qux Corgi");
console.Lines[3].ShouldBe(" ");
}
}
[Fact]

View File

@@ -12,7 +12,7 @@ namespace Spectre.Console.Tests.Unit
var console = new PlainConsole(width: 80);
// When
console.Render(new Panel(Text.New("Hello World")));
console.Render(new Panel(new Text("Hello World")));
// Then
console.Lines.Count.ShouldBe(3);
@@ -28,7 +28,7 @@ namespace Spectre.Console.Tests.Unit
var console = new PlainConsole(width: 80);
// When
console.Render(new Panel(Text.New("Hello World"))
console.Render(new Panel(new Text("Hello World"))
{
Padding = new Padding(3, 5),
});
@@ -47,7 +47,7 @@ namespace Spectre.Console.Tests.Unit
var console = new PlainConsole(width: 80);
// When
console.Render(new Panel(Text.New(" \n💩\n ")));
console.Render(new Panel(new Text(" \n💩\n ")));
// Then
console.Lines.Count.ShouldBe(5);
@@ -65,7 +65,7 @@ namespace Spectre.Console.Tests.Unit
var console = new PlainConsole(width: 80);
// When
console.Render(new Panel(Text.New("Hello World\nFoo Bar")));
console.Render(new Panel(new Text("Hello World\nFoo Bar")));
// Then
console.Lines.Count.ShouldBe(4);
@@ -81,7 +81,7 @@ namespace Spectre.Console.Tests.Unit
// Given
var console = new PlainConsole(width: 80);
var text = new Panel(
Text.New("I heard [underline on blue]you[/] like 📦\n\n\n\nSo I put a 📦 in a 📦"));
Text.Markup("I heard [underline on blue]you[/] like 📦\n\n\n\nSo I put a 📦 in a 📦"));
// When
console.Render(text);
@@ -104,7 +104,7 @@ namespace Spectre.Console.Tests.Unit
var console = new PlainConsole(width: 80);
// When
console.Render(new Panel(Text.New("Hello World"))
console.Render(new Panel(new Text("Hello World"))
{
Expand = true,
});
@@ -125,8 +125,7 @@ namespace Spectre.Console.Tests.Unit
// When
console.Render(
new Panel(
Text.New("Hello World").WithAlignment(Justify.Right))
new Panel(new Text("Hello World").RightAligned())
{
Expand = true,
});
@@ -146,8 +145,7 @@ namespace Spectre.Console.Tests.Unit
// When
console.Render(
new Panel(
Text.New("Hello World").WithAlignment(Justify.Center))
new Panel(new Text("Hello World").Centered())
{
Expand = true,
});
@@ -166,7 +164,7 @@ namespace Spectre.Console.Tests.Unit
var console = new PlainConsole(width: 80);
// When
console.Render(new Panel(new Panel(Text.New("Hello World"))));
console.Render(new Panel(new Panel(new Text("Hello World"))));
// Then
console.Lines.Count.ShouldBe(5);

View File

@@ -1,5 +1,5 @@
using Shouldly;
using Spectre.Console.Composition;
using Spectre.Console.Rendering;
using Xunit;
namespace Spectre.Console.Tests.Unit

View File

@@ -2,7 +2,7 @@ using System;
using Shouldly;
using Xunit;
namespace Spectre.Console.Tests.Unit.Composition
namespace Spectre.Console.Tests.Unit
{
public sealed class TableTests
{
@@ -59,7 +59,21 @@ namespace Spectre.Console.Tests.Unit.Composition
public sealed class TheAddRowMethod
{
[Fact]
public void Should_Throw_If_Rows_Are_Null()
public void Should_Throw_If_String_Rows_Are_Null()
{
// Given
var table = new Table();
// When
var result = Record.Exception(() => table.AddRow((string[])null));
// Then
result.ShouldBeOfType<ArgumentNullException>()
.ParamName.ShouldBe("columns");
}
[Fact]
public void Should_Throw_If_Renderable_Rows_Are_Null()
{
// Given
var table = new Table();

View File

@@ -0,0 +1,81 @@
using System.Text;
using Shouldly;
using Spectre.Console.Rendering;
using Xunit;
namespace Spectre.Console.Tests.Unit
{
public sealed class TextTests
{
[Fact]
public void Should_Consider_The_Longest_Word_As_Minimum_Width()
{
var text = new Text("Foo Bar Baz\nQux\nLol mobile");
var result = ((IRenderable)text).Measure(new RenderContext(Encoding.Unicode, false), 80);
result.Min.ShouldBe(6);
}
[Fact]
public void Should_Consider_The_Longest_Line_As_Maximum_Width()
{
var text = new Text("Foo Bar Baz\nQux\nLol mobile");
var result = ((IRenderable)text).Measure(new RenderContext(Encoding.Unicode, false), 80);
result.Max.ShouldBe(11);
}
[Fact]
public void Should_Render_Unstyled_Text_As_Expected()
{
// Given
var fixture = new PlainConsole(width: 80);
var text = new Text("Hello World");
// When
fixture.Render(text);
// Then
fixture.Output
.NormalizeLineEndings()
.ShouldBe("Hello World");
}
[Theory]
[InlineData("Hello\n\nWorld\n\n")]
[InlineData("Hello\r\n\r\nWorld\r\n\r\n")]
public void Should_Write_Line_Breaks(string input)
{
// Given
var fixture = new PlainConsole(width: 5);
var text = new Text(input);
// When
fixture.Render(text);
// Then
fixture.RawOutput.ShouldBe("Hello\n\nWorld\n\n");
}
[Theory]
[InlineData(5, "Hello World", "Hello\nWorld")]
[InlineData(10, "Hello Sweet Nice World", "Hello \nSweet Nice\nWorld")]
public void Should_Split_Unstyled_Text_To_New_Lines_If_Width_Exceeds_Console_Width(
int width, string input, string expected)
{
// Given
var fixture = new PlainConsole(width);
var text = new Text(input);
// When
fixture.Render(text);
// Then
fixture.Output
.NormalizeLineEndings()
.ShouldBe(expected);
}
}
}

View File

@@ -7,8 +7,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Spectre.Console", "Spectre.
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Spectre.Console.Tests", "Spectre.Console.Tests\Spectre.Console.Tests.csproj", "{9F1AC4C1-766E-4421-8A78-B28F5BCDD94F}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Sample", "Sample\Sample.csproj", "{272E6092-BD31-4EB6-A9FF-F4179F91958F}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{20595AD4-8D75-4AF8-B6BC-9C38C160423F}"
ProjectSection(SolutionItems) = preProject
.editorconfig = .editorconfig
@@ -17,6 +15,16 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution
stylecop.json = stylecop.json
EndProjectSection
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Examples", "Examples", "{F0575243-121F-4DEE-9F6B-246E26DC0844}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Table", "..\examples\Table\Table.csproj", "{94ECCBA8-7EBF-4B53-8379-52EB2327417E}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Panel", "..\examples\Panel\Panel.csproj", "{BFF37228-B376-4ADD-9657-4E501F929713}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Grid", "..\examples\Grid\Grid.csproj", "{C7FF6FDB-FB59-4517-8669-521C96AB7323}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Colors", "..\examples\Colors\Colors.csproj", "{1F51C55C-BA4C-4856-9001-0F7924FFB179}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -51,22 +59,64 @@ Global
{9F1AC4C1-766E-4421-8A78-B28F5BCDD94F}.Release|x64.Build.0 = Release|Any CPU
{9F1AC4C1-766E-4421-8A78-B28F5BCDD94F}.Release|x86.ActiveCfg = Release|Any CPU
{9F1AC4C1-766E-4421-8A78-B28F5BCDD94F}.Release|x86.Build.0 = Release|Any CPU
{272E6092-BD31-4EB6-A9FF-F4179F91958F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{272E6092-BD31-4EB6-A9FF-F4179F91958F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{272E6092-BD31-4EB6-A9FF-F4179F91958F}.Debug|x64.ActiveCfg = Debug|Any CPU
{272E6092-BD31-4EB6-A9FF-F4179F91958F}.Debug|x64.Build.0 = Debug|Any CPU
{272E6092-BD31-4EB6-A9FF-F4179F91958F}.Debug|x86.ActiveCfg = Debug|Any CPU
{272E6092-BD31-4EB6-A9FF-F4179F91958F}.Debug|x86.Build.0 = Debug|Any CPU
{272E6092-BD31-4EB6-A9FF-F4179F91958F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{272E6092-BD31-4EB6-A9FF-F4179F91958F}.Release|Any CPU.Build.0 = Release|Any CPU
{272E6092-BD31-4EB6-A9FF-F4179F91958F}.Release|x64.ActiveCfg = Release|Any CPU
{272E6092-BD31-4EB6-A9FF-F4179F91958F}.Release|x64.Build.0 = Release|Any CPU
{272E6092-BD31-4EB6-A9FF-F4179F91958F}.Release|x86.ActiveCfg = Release|Any CPU
{272E6092-BD31-4EB6-A9FF-F4179F91958F}.Release|x86.Build.0 = Release|Any CPU
{94ECCBA8-7EBF-4B53-8379-52EB2327417E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{94ECCBA8-7EBF-4B53-8379-52EB2327417E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{94ECCBA8-7EBF-4B53-8379-52EB2327417E}.Debug|x64.ActiveCfg = Debug|Any CPU
{94ECCBA8-7EBF-4B53-8379-52EB2327417E}.Debug|x64.Build.0 = Debug|Any CPU
{94ECCBA8-7EBF-4B53-8379-52EB2327417E}.Debug|x86.ActiveCfg = Debug|Any CPU
{94ECCBA8-7EBF-4B53-8379-52EB2327417E}.Debug|x86.Build.0 = Debug|Any CPU
{94ECCBA8-7EBF-4B53-8379-52EB2327417E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{94ECCBA8-7EBF-4B53-8379-52EB2327417E}.Release|Any CPU.Build.0 = Release|Any CPU
{94ECCBA8-7EBF-4B53-8379-52EB2327417E}.Release|x64.ActiveCfg = Release|Any CPU
{94ECCBA8-7EBF-4B53-8379-52EB2327417E}.Release|x64.Build.0 = Release|Any CPU
{94ECCBA8-7EBF-4B53-8379-52EB2327417E}.Release|x86.ActiveCfg = Release|Any CPU
{94ECCBA8-7EBF-4B53-8379-52EB2327417E}.Release|x86.Build.0 = Release|Any CPU
{BFF37228-B376-4ADD-9657-4E501F929713}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{BFF37228-B376-4ADD-9657-4E501F929713}.Debug|Any CPU.Build.0 = Debug|Any CPU
{BFF37228-B376-4ADD-9657-4E501F929713}.Debug|x64.ActiveCfg = Debug|Any CPU
{BFF37228-B376-4ADD-9657-4E501F929713}.Debug|x64.Build.0 = Debug|Any CPU
{BFF37228-B376-4ADD-9657-4E501F929713}.Debug|x86.ActiveCfg = Debug|Any CPU
{BFF37228-B376-4ADD-9657-4E501F929713}.Debug|x86.Build.0 = Debug|Any CPU
{BFF37228-B376-4ADD-9657-4E501F929713}.Release|Any CPU.ActiveCfg = Release|Any CPU
{BFF37228-B376-4ADD-9657-4E501F929713}.Release|Any CPU.Build.0 = Release|Any CPU
{BFF37228-B376-4ADD-9657-4E501F929713}.Release|x64.ActiveCfg = Release|Any CPU
{BFF37228-B376-4ADD-9657-4E501F929713}.Release|x64.Build.0 = Release|Any CPU
{BFF37228-B376-4ADD-9657-4E501F929713}.Release|x86.ActiveCfg = Release|Any CPU
{BFF37228-B376-4ADD-9657-4E501F929713}.Release|x86.Build.0 = Release|Any CPU
{C7FF6FDB-FB59-4517-8669-521C96AB7323}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C7FF6FDB-FB59-4517-8669-521C96AB7323}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C7FF6FDB-FB59-4517-8669-521C96AB7323}.Debug|x64.ActiveCfg = Debug|Any CPU
{C7FF6FDB-FB59-4517-8669-521C96AB7323}.Debug|x64.Build.0 = Debug|Any CPU
{C7FF6FDB-FB59-4517-8669-521C96AB7323}.Debug|x86.ActiveCfg = Debug|Any CPU
{C7FF6FDB-FB59-4517-8669-521C96AB7323}.Debug|x86.Build.0 = Debug|Any CPU
{C7FF6FDB-FB59-4517-8669-521C96AB7323}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C7FF6FDB-FB59-4517-8669-521C96AB7323}.Release|Any CPU.Build.0 = Release|Any CPU
{C7FF6FDB-FB59-4517-8669-521C96AB7323}.Release|x64.ActiveCfg = Release|Any CPU
{C7FF6FDB-FB59-4517-8669-521C96AB7323}.Release|x64.Build.0 = Release|Any CPU
{C7FF6FDB-FB59-4517-8669-521C96AB7323}.Release|x86.ActiveCfg = Release|Any CPU
{C7FF6FDB-FB59-4517-8669-521C96AB7323}.Release|x86.Build.0 = Release|Any CPU
{1F51C55C-BA4C-4856-9001-0F7924FFB179}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1F51C55C-BA4C-4856-9001-0F7924FFB179}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1F51C55C-BA4C-4856-9001-0F7924FFB179}.Debug|x64.ActiveCfg = Debug|Any CPU
{1F51C55C-BA4C-4856-9001-0F7924FFB179}.Debug|x64.Build.0 = Debug|Any CPU
{1F51C55C-BA4C-4856-9001-0F7924FFB179}.Debug|x86.ActiveCfg = Debug|Any CPU
{1F51C55C-BA4C-4856-9001-0F7924FFB179}.Debug|x86.Build.0 = Debug|Any CPU
{1F51C55C-BA4C-4856-9001-0F7924FFB179}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1F51C55C-BA4C-4856-9001-0F7924FFB179}.Release|Any CPU.Build.0 = Release|Any CPU
{1F51C55C-BA4C-4856-9001-0F7924FFB179}.Release|x64.ActiveCfg = Release|Any CPU
{1F51C55C-BA4C-4856-9001-0F7924FFB179}.Release|x64.Build.0 = Release|Any CPU
{1F51C55C-BA4C-4856-9001-0F7924FFB179}.Release|x86.ActiveCfg = Release|Any CPU
{1F51C55C-BA4C-4856-9001-0F7924FFB179}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{94ECCBA8-7EBF-4B53-8379-52EB2327417E} = {F0575243-121F-4DEE-9F6B-246E26DC0844}
{BFF37228-B376-4ADD-9657-4E501F929713} = {F0575243-121F-4DEE-9F6B-246E26DC0844}
{C7FF6FDB-FB59-4517-8669-521C96AB7323} = {F0575243-121F-4DEE-9F6B-246E26DC0844}
{1F51C55C-BA4C-4856-9001-0F7924FFB179} = {F0575243-121F-4DEE-9F6B-246E26DC0844}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {5729B071-67A0-48FB-8B1B-275E6822086C}
EndGlobalSection

View File

@@ -1,4 +1,4 @@
using Spectre.Console.Composition;
using Spectre.Console.Rendering;
namespace Spectre.Console
{

View File

@@ -1,18 +0,0 @@
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
namespace Spectre.Console.Composition
{
/// <summary>
/// Represents a line of segments.
/// </summary>
[SuppressMessage("Naming", "CA1710:Identifiers should have correct suffix")]
public sealed class SegmentLine : List<Segment>
{
/// <summary>
/// Gets the length of the line.
/// </summary>
public int Length => this.Sum(line => line.Text.Length);
}
}

View File

@@ -1,297 +0,0 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Spectre.Console.Composition;
using Spectre.Console.Internal;
namespace Spectre.Console
{
/// <summary>
/// Represents text with color and decorations.
/// </summary>
[SuppressMessage("Naming", "CA1724:Type names should not match namespaces")]
[DebuggerDisplay("{_text,nq}")]
public sealed class Text : IRenderable
{
private readonly List<Span> _spans;
private string _text;
/// <summary>
/// Gets or sets the text alignment.
/// </summary>
public Justify Alignment { get; set; } = Justify.Left;
private sealed class Span
{
public int Start { get; }
public int End { get; }
public Style Style { get; }
public Span(int start, int end, Style style)
{
Start = start;
End = end;
Style = style ?? Style.Plain;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="Console.Text"/> class.
/// </summary>
/// <param name="text">The text.</param>
internal Text(string text)
{
_text = text?.NormalizeLineEndings() ?? throw new ArgumentNullException(nameof(text));
_spans = new List<Span>();
}
/// <summary>
/// Initializes a new instance of the <see cref="Text"/> class.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="foreground">The foreground.</param>
/// <param name="background">The background.</param>
/// <param name="decoration">The text decoration.</param>
/// <returns>A <see cref="Text"/> instance.</returns>
public static Text New(
string text,
Color? foreground = null,
Color? background = null,
Decoration? decoration = null)
{
var result = MarkupParser.Parse(text, new Style(foreground, background, decoration));
return result;
}
/// <summary>
/// Sets the text alignment.
/// </summary>
/// <param name="alignment">The text alignment.</param>
/// <returns>The same <see cref="Text"/> instance.</returns>
public Text WithAlignment(Justify alignment)
{
Alignment = alignment;
return this;
}
/// <summary>
/// Appends some text with the specified color and decorations.
/// </summary>
/// <param name="text">The text to append.</param>
/// <param name="style">The text style.</param>
public void Append(string text, Style style)
{
if (text == null)
{
throw new ArgumentNullException(nameof(text));
}
var start = _text.Length;
var end = _text.Length + text.Length;
_text += text;
Stylize(start, end, style);
}
/// <summary>
/// Stylizes a part of the text.
/// </summary>
/// <param name="start">The start position.</param>
/// <param name="end">The end position.</param>
/// <param name="style">The style to apply.</param>
public void Stylize(int start, int end, Style style)
{
if (start >= end)
{
throw new ArgumentOutOfRangeException(nameof(start), "Start position must be less than the end position.");
}
start = Math.Max(start, 0);
end = Math.Min(end, _text.Length);
_spans.Add(new Span(start, end, style));
}
/// <inheritdoc/>
Measurement IRenderable.Measure(RenderContext context, int maxWidth)
{
if (string.IsNullOrEmpty(_text))
{
return new Measurement(1, 1);
}
// TODO: Write some kind of tokenizer for this
var min = Segment.SplitLines(((IRenderable)this).Render(context, maxWidth))
.SelectMany(line => line.Select(segment => segment.Text.Length))
.Max();
var max = _text.SplitLines().Max(x => Cell.GetCellLength(context.Encoding, x));
return new Measurement(min, max);
}
/// <inheritdoc/>
IEnumerable<Segment> IRenderable.Render(RenderContext context, int width)
{
if (string.IsNullOrEmpty(_text))
{
return Array.Empty<Segment>();
}
if (width == 0)
{
return Array.Empty<Segment>();
}
var result = new List<Segment>();
var segments = SplitLineBreaks(CreateSegments());
var justification = context.Justification ?? Alignment;
foreach (var (_, _, last, line) in Segment.SplitLines(segments, width).Enumerate())
{
var length = line.Sum(l => l.StripLineEndings().CellLength(context.Encoding));
if (length < width)
{
// Justify right side
if (justification == Justify.Right)
{
var diff = width - length;
result.Add(new Segment(new string(' ', diff)));
}
else if (justification == Justify.Center)
{
var diff = (width - length) / 2;
result.Add(new Segment(new string(' ', diff)));
}
}
// Render the line.
foreach (var segment in line)
{
result.Add(segment.StripLineEndings());
}
// Justify left side
if (length < width)
{
if (justification == Justify.Center)
{
var diff = (width - length) / 2;
result.Add(new Segment(new string(' ', diff)));
var remainder = (width - length) % 2;
if (remainder != 0)
{
result.Add(new Segment(new string(' ', remainder)));
}
}
}
if (!last || line.Count == 0)
{
result.Add(Segment.LineBreak());
}
}
return result;
}
private static IEnumerable<Segment> SplitLineBreaks(IEnumerable<Segment> segments)
{
// Creates individual segments of line breaks.
var result = new List<Segment>();
var queue = new Stack<Segment>(segments.Reverse());
while (queue.Count > 0)
{
var segment = queue.Pop();
var index = segment.Text.IndexOf("\n", StringComparison.OrdinalIgnoreCase);
if (index == -1)
{
if (!string.IsNullOrEmpty(segment.Text))
{
result.Add(segment);
}
}
else
{
var (first, second) = segment.Split(index);
if (!string.IsNullOrEmpty(first.Text))
{
result.Add(first);
}
result.Add(Segment.LineBreak());
if (second != null)
{
queue.Push(new Segment(second.Text.Substring(1), second.Style));
}
}
}
return result;
}
private IEnumerable<Segment> CreateSegments()
{
// This excellent algorithm to sort spans was ported and adapted from
// https://github.com/willmcgugan/rich/blob/eb2f0d5277c159d8693636ec60c79c5442fd2e43/rich/text.py#L492
// Create the style map.
var styleMap = _spans.SelectIndex((span, index) => (span, index)).ToDictionary(x => x.index + 1, x => x.span.Style);
styleMap[0] = Style.Plain;
// Create a span list.
var spans = new List<(int Offset, bool Leaving, int Style)>();
spans.AddRange(_spans.SelectIndex((span, index) => (span.Start, false, index + 1)));
spans.AddRange(_spans.SelectIndex((span, index) => (span.End, true, index + 1)));
spans = spans.OrderBy(x => x.Offset).ThenBy(x => !x.Leaving).ToList();
// Keep track of applied styles using a stack
var styleStack = new Stack<int>();
// Now build the segments.
var result = new List<Segment>();
foreach (var (offset, leaving, style, nextOffset) in BuildSkipList(spans))
{
if (leaving)
{
// Leaving
styleStack.Pop();
}
else
{
// Entering
styleStack.Push(style);
}
if (nextOffset > offset)
{
// Build the current style from the stack
var styleIndices = styleStack.OrderBy(index => index).ToArray();
var currentStyle = Style.Plain.Combine(styleIndices.Select(index => styleMap[index]));
// Create segment
var text = _text.Substring(offset, Math.Min(_text.Length - offset, nextOffset - offset));
result.Add(new Segment(text, currentStyle));
}
}
return result;
}
private static IEnumerable<(int Offset, bool Leaving, int Style, int NextOffset)> BuildSkipList(
List<(int Offset, bool Leaving, int Style)> spans)
{
return spans.Zip(spans.Skip(1), (first, second) => (first, second)).Select(
x => (x.first.Offset, x.first.Leaving, x.first.Style, NextOffset: x.second.Offset));
}
}
}

View File

@@ -1,6 +1,6 @@
using System;
using Spectre.Console.Composition;
using Spectre.Console.Internal;
using Spectre.Console.Rendering;
namespace Spectre.Console
{
@@ -28,17 +28,24 @@ namespace Spectre.Console
var options = new RenderContext(console.Encoding, console.Capabilities.LegacyConsole);
using (console.PushStyle(Style.Plain))
{
var current = Style.Plain;
foreach (var segment in renderable.Render(options, console.Width))
{
if (!segment.Style.Equals(Style.Plain))
if (string.IsNullOrEmpty(segment.Text))
{
using (var style = console.PushStyle(segment.Style))
{
console.Write(segment.Text);
continue;
}
}
else
if (!segment.Style.Equals(current))
{
console.Foreground = segment.Style.Foreground;
console.Background = segment.Style.Background;
console.Decoration = segment.Style.Decoration;
current = segment.Style;
}
console.Write(segment.Text);
}
}

View File

@@ -1,4 +1,5 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace Spectre.Console.Internal
@@ -33,5 +34,49 @@ namespace Spectre.Console.Internal
var result = text?.NormalizeLineEndings()?.Split(new[] { '\n' }, StringSplitOptions.None);
return result ?? Array.Empty<string>();
}
public static string[] SplitWords(this string word, StringSplitOptions options = StringSplitOptions.None)
{
var result = new List<string>();
static string Read(StringBuffer reader, Func<char, bool> criteria)
{
var buffer = new StringBuilder();
while (!reader.Eof)
{
var current = reader.Peek();
if (!criteria(current))
{
break;
}
buffer.Append(reader.Read());
}
return buffer.ToString();
}
using (var reader = new StringBuffer(word))
{
while (!reader.Eof)
{
var current = reader.Peek();
if (char.IsWhiteSpace(current))
{
var x = Read(reader, c => char.IsWhiteSpace(c));
if (options != StringSplitOptions.RemoveEmptyEntries)
{
result.Add(x);
}
}
else
{
result.Add(Read(reader, c => !char.IsWhiteSpace(c)));
}
}
}
return result.ToArray();
}
}
}

View File

@@ -70,6 +70,11 @@ namespace Spectre.Console.Internal
public static int GetCellLength(Encoding encoding, char rune)
{
if (rune == '\r' || rune == '\n')
{
return 0;
}
// Is it represented by a single byte?
// In that case we don't have to calculate the
// actual cell width.

View File

@@ -10,7 +10,7 @@ namespace Spectre.Console.Internal
{
style ??= Style.Plain;
var result = new Text(string.Empty);
var result = new Text();
using var tokenizer = new MarkupTokenizer(text);
var stack = new Stack<Style>();

View File

@@ -0,0 +1,61 @@
namespace Spectre.Console
{
/// <summary>
/// Contains extension methods for <see cref="IAlignable"/>.
/// </summary>
public static class AlignableExtensions
{
/// <summary>
/// Sets the alignment for an <see cref="IAlignable"/> object.
/// </summary>
/// <typeparam name="T">The alignable type.</typeparam>
/// <param name="alignable">The alignable object.</param>
/// <param name="alignment">The alignment.</param>
/// <returns>The same alignable object.</returns>
public static T WithAlignment<T>(this T alignable, Justify alignment)
where T : IAlignable
{
alignable.Alignment = alignment;
return alignable;
}
/// <summary>
/// Sets the <see cref="IAlignable"/> object to be left aligned.
/// </summary>
/// <typeparam name="T">The alignable type.</typeparam>
/// <param name="alignable">The alignable object.</param>
/// <returns>The same alignable object.</returns>
public static T LeftAligned<T>(this T alignable)
where T : IAlignable
{
alignable.Alignment = Justify.Left;
return alignable;
}
/// <summary>
/// Sets the <see cref="IAlignable"/> object to be centered.
/// </summary>
/// <typeparam name="T">The alignable type.</typeparam>
/// <param name="alignable">The alignable object.</param>
/// <returns>The same alignable object.</returns>
public static T Centered<T>(this T alignable)
where T : IAlignable
{
alignable.Alignment = Justify.Center;
return alignable;
}
/// <summary>
/// Sets the <see cref="IAlignable"/> object to be right aligned.
/// </summary>
/// <typeparam name="T">The alignable type.</typeparam>
/// <param name="alignable">The alignable object.</param>
/// <returns>The same alignable object.</returns>
public static T RightAligned<T>(this T alignable)
where T : IAlignable
{
alignable.Alignment = Justify.Right;
return alignable;
}
}
}

View File

@@ -3,7 +3,7 @@ using System.Collections.Generic;
using System.Globalization;
using System.Linq;
namespace Spectre.Console.Composition
namespace Spectre.Console.Rendering
{
/// <summary>
/// Represents a border used by tables.

View File

@@ -1,4 +1,4 @@
namespace Spectre.Console.Composition
namespace Spectre.Console.Rendering
{
/// <summary>
/// Represents the different border parts.

View File

@@ -1,6 +1,6 @@
using System;
namespace Spectre.Console.Composition
namespace Spectre.Console.Rendering
{
/// <summary>
/// Represents an old school ASCII border.

View File

@@ -1,4 +1,4 @@
namespace Spectre.Console.Composition
namespace Spectre.Console.Rendering
{
/// <summary>
/// Represents an invisible border.

View File

@@ -1,6 +1,6 @@
using System;
namespace Spectre.Console.Composition
namespace Spectre.Console.Rendering
{
/// <summary>
/// Represents a rounded border.

View File

@@ -1,6 +1,6 @@
using System;
namespace Spectre.Console.Composition
namespace Spectre.Console.Rendering
{
/// <summary>
/// Represents a square border.

View File

@@ -1,15 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Spectre.Console.Composition;
using Spectre.Console.Internal;
using Spectre.Console.Rendering;
namespace Spectre.Console
{
/// <summary>
/// Represents a grid.
/// A renderable grid.
/// </summary>
public sealed class Grid : IRenderable
public sealed class Grid : Renderable
{
private readonly Table _table;
@@ -28,13 +28,13 @@ namespace Spectre.Console
}
/// <inheritdoc/>
public Measurement Measure(RenderContext context, int maxWidth)
protected override Measurement Measure(RenderContext context, int maxWidth)
{
return ((IRenderable)_table).Measure(context, maxWidth);
}
/// <inheritdoc/>
public IEnumerable<Segment> Render(RenderContext context, int width)
protected override IEnumerable<Segment> Render(RenderContext context, int width)
{
return ((IRenderable)_table).Render(context, width);
}
@@ -109,8 +109,8 @@ namespace Spectre.Console
/// </summary>
public void AddEmptyRow()
{
var columns = new string[_table.ColumnCount];
Enumerable.Range(0, _table.ColumnCount).ForEach(index => columns[index] = string.Empty);
var columns = new IRenderable[_table.ColumnCount];
Enumerable.Range(0, _table.ColumnCount).ForEach(index => columns[index] = Text.Empty);
AddRow(columns);
}
@@ -118,7 +118,7 @@ namespace Spectre.Console
/// Adds a new row to the grid.
/// </summary>
/// <param name="columns">The columns to add.</param>
public void AddRow(params string[] columns)
public void AddRow(params IRenderable[] columns)
{
if (columns is null)
{

View File

@@ -3,7 +3,7 @@ namespace Spectre.Console
/// <summary>
/// Represents a grid column.
/// </summary>
public sealed class GridColumn
public sealed class GridColumn : IAlignable
{
/// <summary>
/// Gets or sets the width of the column.

View File

@@ -0,0 +1,31 @@
using System;
using System.Linq;
namespace Spectre.Console
{
/// <summary>
/// Contains extension methods for <see cref="Grid"/>.
/// </summary>
public static class GridExtensions
{
/// <summary>
/// Adds a new row to the grid.
/// </summary>
/// <param name="grid">The grid to add the row to.</param>
/// <param name="columns">The columns to add.</param>
public static void AddRow(this Grid grid, params string[] columns)
{
if (grid is null)
{
throw new ArgumentNullException(nameof(grid));
}
if (columns is null)
{
throw new ArgumentNullException(nameof(columns));
}
grid.AddRow(columns.Select(column => new Markup(column)).ToArray());
}
}
}

View File

@@ -0,0 +1,13 @@
namespace Spectre.Console
{
/// <summary>
/// Represents something that is alignable.
/// </summary>
public interface IAlignable
{
/// <summary>
/// Gets or sets the alignment.
/// </summary>
Justify? Alignment { get; set; }
}
}

View File

@@ -1,6 +1,6 @@
using System.Collections.Generic;
namespace Spectre.Console.Composition
namespace Spectre.Console.Rendering
{
/// <summary>
/// Represents something that can be rendered to the console.

View File

@@ -0,0 +1,43 @@
using System.Collections.Generic;
using Spectre.Console.Internal;
using Spectre.Console.Rendering;
namespace Spectre.Console
{
/// <summary>
/// A renderable piece of markup text.
/// </summary>
public sealed class Markup : Renderable, IAlignable
{
private readonly Text _text;
/// <inheritdoc/>
public Justify? Alignment
{
get => _text.Alignment;
set => _text.Alignment = value;
}
/// <summary>
/// Initializes a new instance of the <see cref="Markup"/> class.
/// </summary>
/// <param name="text">The markup text.</param>
/// <param name="style">The style of the text.</param>
public Markup(string text, Style? style = null)
{
_text = MarkupParser.Parse(text, style);
}
/// <inheritdoc/>
protected override Measurement Measure(RenderContext context, int maxWidth)
{
return ((IRenderable)_text).Measure(context, maxWidth);
}
/// <inheritdoc/>
protected override IEnumerable<Segment> Render(RenderContext context, int maxWidth)
{
return ((IRenderable)_text).Render(context, maxWidth);
}
}
}

View File

@@ -1,6 +1,6 @@
using System;
namespace Spectre.Console.Composition
namespace Spectre.Console.Rendering
{
/// <summary>
/// Represents a measurement.

View File

@@ -1,13 +1,14 @@
using System.Collections.Generic;
using System.Linq;
using Spectre.Console.Composition;
using Spectre.Console.Rendering;
using SpectreBorder = Spectre.Console.Rendering.Border;
namespace Spectre.Console
{
/// <summary>
/// Represents a panel which contains another renderable item.
/// A renderable panel.
/// </summary>
public sealed class Panel : IRenderable
public sealed class Panel : Renderable
{
private const int EdgeWidth = 2;
@@ -42,6 +43,15 @@ namespace Spectre.Console
/// </summary>
public Padding Padding { get; set; } = new Padding(1, 1);
/// <summary>
/// Initializes a new instance of the <see cref="Panel"/> class.
/// </summary>
/// <param name="text">The panel content.</param>
public Panel(string text)
: this(new Markup(text))
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Panel"/> class.
/// </summary>
@@ -52,23 +62,25 @@ namespace Spectre.Console
}
/// <inheritdoc/>
Measurement IRenderable.Measure(RenderContext context, int maxWidth)
protected override Measurement Measure(RenderContext context, int maxWidth)
{
var childWidth = _child.Measure(context, maxWidth);
return new Measurement(childWidth.Min + 2 + Padding.GetHorizontalPadding(), childWidth.Max + 2 + Padding.GetHorizontalPadding());
return new Measurement(
childWidth.Min + 2 + Padding.GetHorizontalPadding(),
childWidth.Max + 2 + Padding.GetHorizontalPadding());
}
/// <inheritdoc/>
IEnumerable<Segment> IRenderable.Render(RenderContext context, int width)
protected override IEnumerable<Segment> Render(RenderContext context, int maxWidth)
{
var border = Composition.Border.GetBorder(Border, (context.LegacyConsole || !context.Unicode) && SafeBorder);
var border = SpectreBorder.GetBorder(Border, (context.LegacyConsole || !context.Unicode) && SafeBorder);
var paddingWidth = Padding.GetHorizontalPadding();
var childWidth = width - EdgeWidth - paddingWidth;
var childWidth = maxWidth - EdgeWidth - paddingWidth;
if (!Expand)
{
var measurement = _child.Measure(context, width - EdgeWidth - paddingWidth);
var measurement = _child.Measure(context, maxWidth - EdgeWidth - paddingWidth);
childWidth = measurement.Max;
}
@@ -80,7 +92,7 @@ namespace Spectre.Console
new Segment(border.GetPart(BorderPart.HeaderTopLeft)),
new Segment(border.GetPart(BorderPart.HeaderTop, panelWidth)),
new Segment(border.GetPart(BorderPart.HeaderTopRight)),
new Segment("\n"),
Segment.LineBreak,
};
// Render the child.
@@ -118,14 +130,14 @@ namespace Spectre.Console
}
result.Add(new Segment(border.GetPart(BorderPart.CellRight)));
result.Add(new Segment("\n"));
result.Add(Segment.LineBreak);
}
// Panel bottom
result.Add(new Segment(border.GetPart(BorderPart.FooterBottomLeft)));
result.Add(new Segment(border.GetPart(BorderPart.FooterBottom, panelWidth)));
result.Add(new Segment(border.GetPart(BorderPart.FooterBottomRight)));
result.Add(new Segment("\n"));
result.Add(Segment.LineBreak);
return result;
}

View File

@@ -1,6 +1,6 @@
using System.Text;
namespace Spectre.Console.Composition
namespace Spectre.Console.Rendering
{
/// <summary>
/// Represents a render context.

View File

@@ -0,0 +1,41 @@
using System.Collections.Generic;
namespace Spectre.Console.Rendering
{
/// <summary>
/// Base class for a renderable object implementing <see cref="IRenderable"/>.
/// </summary>
public abstract class Renderable : IRenderable
{
/// <inheritdoc/>
Measurement IRenderable.Measure(RenderContext context, int maxWidth)
{
return Measure(context, maxWidth);
}
/// <inheritdoc/>
IEnumerable<Segment> IRenderable.Render(RenderContext context, int maxWidth)
{
return Render(context, maxWidth);
}
/// <summary>
/// Measures the renderable object.
/// </summary>
/// <param name="context">The render context.</param>
/// <param name="maxWidth">The maximum allowed width.</param>
/// <returns>The minimum and maximum width of the object.</returns>
protected virtual Measurement Measure(RenderContext context, int maxWidth)
{
return new Measurement(maxWidth, maxWidth);
}
/// <summary>
/// Renders the object.
/// </summary>
/// <param name="context">The render context.</param>
/// <param name="maxWidth">The maximum allowed width.</param>
/// <returns>A collection of segments.</returns>
protected abstract IEnumerable<Segment> Render(RenderContext context, int maxWidth);
}
}

View File

@@ -5,7 +5,7 @@ using System.Linq;
using System.Text;
using Spectre.Console.Internal;
namespace Spectre.Console.Composition
namespace Spectre.Console.Rendering
{
/// <summary>
/// Represents a renderable segment.
@@ -24,11 +24,28 @@ namespace Spectre.Console.Composition
/// </summary>
public bool IsLineBreak { get; }
/// <summary>
/// Gets a value indicating whether or not this is a whitespace
/// that should be preserved but not taken into account when
/// layouting text.
/// </summary>
public bool IsWhiteSpace { get; }
/// <summary>
/// Gets the segment style.
/// </summary>
public Style Style { get; }
/// <summary>
/// Gets a segment representing a line break.
/// </summary>
public static Segment LineBreak { get; } = new Segment(Environment.NewLine, Style.Plain, true);
/// <summary>
/// Gets an empty segment.
/// </summary>
public static Segment Empty { get; } = new Segment(string.Empty, Style.Plain);
/// <summary>
/// Initializes a new instance of the <see cref="Segment"/> class.
/// </summary>
@@ -58,15 +75,7 @@ namespace Spectre.Console.Composition
Text = text.NormalizeLineEndings();
Style = style;
IsLineBreak = lineBreak;
}
/// <summary>
/// Creates a segment that represents an implicit line break.
/// </summary>
/// <returns>A segment that represents an implicit line break.</returns>
public static Segment LineBreak()
{
return new Segment("\n", Style.Plain, true);
IsWhiteSpace = string.IsNullOrWhiteSpace(text);
}
/// <summary>
@@ -86,7 +95,7 @@ namespace Spectre.Console.Composition
/// <returns>A new segment without any trailing line endings.</returns>
public Segment StripLineEndings()
{
return new Segment(Text.TrimEnd('\n'), Style);
return new Segment(Text.TrimEnd('\n').TrimEnd('\r'), Style);
}
/// <summary>
@@ -143,9 +152,9 @@ namespace Spectre.Console.Composition
{
var segment = stack.Pop();
if (line.Length + segment.Text.Length > maxWidth)
if (line.Width + segment.Text.Length > maxWidth)
{
var diff = -(maxWidth - (line.Length + segment.Text.Length));
var diff = -(maxWidth - (line.Width + segment.Text.Length));
var offset = segment.Text.Length - diff;
var (first, second) = segment.Split(offset);
@@ -166,7 +175,7 @@ namespace Spectre.Console.Composition
{
if (segment.Text == "\n")
{
if (line.Length > 0 || segment.IsLineBreak)
if (line.Width > 0 || segment.IsLineBreak)
{
lines.Add(line);
line = new SegmentLine();
@@ -189,7 +198,7 @@ namespace Spectre.Console.Composition
if (parts.Length > 1)
{
if (line.Length > 0)
if (line.Width > 0)
{
lines.Add(line);
line = new SegmentLine();

View File

@@ -0,0 +1,38 @@
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
namespace Spectre.Console.Rendering
{
/// <summary>
/// Represents a collection of segments.
/// </summary>
[SuppressMessage("Naming", "CA1710:Identifiers should have correct suffix")]
public sealed class SegmentLine : List<Segment>
{
/// <summary>
/// Gets the width of the line.
/// </summary>
public int Width => this.Sum(line => line.Text.Length);
/// <summary>
/// Gets the cell width of the segment line.
/// </summary>
/// <param name="encoding">The encoding to use.</param>
/// <returns>The cell width of the segment line.</returns>
public int CellWidth(Encoding encoding)
{
return this.Sum(line => line.CellLength(encoding));
}
/// <summary>
/// Preprends a segment to the line.
/// </summary>
/// <param name="segment">The segment to prepend.</param>
public void Prepend(Segment segment)
{
Insert(0, segment);
}
}
}

View File

@@ -0,0 +1,25 @@
using System.Collections;
using System.Collections.Generic;
namespace Spectre.Console.Rendering
{
internal sealed class SegmentLineEnumerator : IEnumerable<Segment>
{
private readonly List<SegmentLine> _lines;
public SegmentLineEnumerator(List<SegmentLine> lines)
{
_lines = lines;
}
public IEnumerator<Segment> GetEnumerator()
{
return new SegmentLineIterator(_lines);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}

View File

@@ -0,0 +1,99 @@
using System.Collections;
using System.Collections.Generic;
namespace Spectre.Console.Rendering
{
internal sealed class SegmentLineIterator : IEnumerator<Segment>
{
private readonly List<SegmentLine> _lines;
private int _currentLine;
private int _currentIndex;
private bool _lineBreakEmitted;
public Segment Current { get; private set; }
object? IEnumerator.Current => Current;
public SegmentLineIterator(List<SegmentLine> lines)
{
_currentLine = 0;
_currentIndex = -1;
_lines = lines;
Current = Segment.Empty;
}
public void Dispose()
{
}
public bool MoveNext()
{
if (_currentLine > _lines.Count - 1)
{
return false;
}
_currentIndex += 1;
// Did we go past the end of the line?
if (_currentIndex > _lines[_currentLine].Count - 1)
{
// We haven't just emitted a line break?
if (!_lineBreakEmitted)
{
// Got any more lines?
if (_currentIndex + 1 > _lines[_currentLine].Count - 1)
{
// Only emit a line break if the next one isn't a line break.
if ((_currentLine + 1 <= _lines.Count - 1)
&& _lines[_currentLine + 1].Count > 0
&& !_lines[_currentLine + 1][0].IsLineBreak)
{
_lineBreakEmitted = true;
Current = Segment.LineBreak;
return true;
}
}
}
// Increase the line and reset the index.
_currentLine += 1;
_currentIndex = 0;
_lineBreakEmitted = false;
// No more lines?
if (_currentLine > _lines.Count - 1)
{
return false;
}
// Nothing on the line?
while (_currentIndex > _lines[_currentLine].Count - 1)
{
_currentLine += 1;
_currentIndex = 0;
if (_currentLine > _lines.Count - 1)
{
return false;
}
}
}
// Reset the flag
_lineBreakEmitted = false;
Current = _lines[_currentLine][_currentIndex];
return true;
}
public void Reset()
{
_currentLine = 0;
_currentIndex = -1;
Current = Segment.Empty;
}
}
}

View File

@@ -1,8 +1,8 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Spectre.Console.Composition;
using Spectre.Console.Internal;
using Spectre.Console.Rendering;
namespace Spectre.Console
{
@@ -100,13 +100,13 @@ namespace Spectre.Console
var maxWidths = new List<int>();
// Include columns in measurement
var measure = ((IRenderable)column.Text).Measure(options, maxWidth);
var measure = column.Text.Measure(options, maxWidth);
minWidths.Add(measure.Min);
maxWidths.Add(measure.Max);
foreach (var row in rows)
{
measure = ((IRenderable)row).Measure(options, maxWidth);
measure = row.Measure(options, maxWidth);
minWidths.Add(measure.Min);
maxWidths.Add(measure.Max);
}

View File

@@ -1,18 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Spectre.Console.Composition;
using Spectre.Console.Internal;
using Spectre.Console.Rendering;
using SpectreBorder = Spectre.Console.Rendering.Border;
namespace Spectre.Console
{
/// <summary>
/// Represents a table.
/// A renderable table.
/// </summary>
public sealed partial class Table : IRenderable
public sealed partial class Table : Renderable
{
private readonly List<TableColumn> _columns;
private readonly List<List<Text>> _rows;
private readonly List<List<IRenderable>> _rows;
/// <summary>
/// Gets the number of columns in the table.
@@ -67,21 +68,7 @@ namespace Spectre.Console
public Table()
{
_columns = new List<TableColumn>();
_rows = new List<List<Text>>();
}
/// <summary>
/// Adds a column to the table.
/// </summary>
/// <param name="column">The column to add.</param>
public void AddColumn(string column)
{
if (column is null)
{
throw new ArgumentNullException(nameof(column));
}
AddColumn(new TableColumn(column));
_rows = new List<List<IRenderable>>();
}
/// <summary>
@@ -103,23 +90,6 @@ namespace Spectre.Console
_columns.Add(column);
}
/// <summary>
/// Adds multiple columns to the table.
/// </summary>
/// <param name="columns">The columns to add.</param>
public void AddColumns(params string[] columns)
{
if (columns is null)
{
throw new ArgumentNullException(nameof(columns));
}
foreach (var column in columns)
{
AddColumn(column);
}
}
/// <summary>
/// Adds multiple columns to the table.
/// </summary>
@@ -142,8 +112,8 @@ namespace Spectre.Console
/// </summary>
public void AddEmptyRow()
{
var columns = new string[ColumnCount];
Enumerable.Range(0, ColumnCount).ForEach(index => columns[index] = string.Empty);
var columns = new IRenderable[ColumnCount];
Enumerable.Range(0, ColumnCount).ForEach(index => columns[index] = Text.Empty);
AddRow(columns);
}
@@ -151,7 +121,7 @@ namespace Spectre.Console
/// Adds a row to the table.
/// </summary>
/// <param name="columns">The row columns to add.</param>
public void AddRow(params string[] columns)
public void AddRow(params IRenderable[] columns)
{
if (columns is null)
{
@@ -168,11 +138,11 @@ namespace Spectre.Console
throw new InvalidOperationException("The number of row columns are greater than the number of table columns.");
}
_rows.Add(columns.Select(column => Text.New(column)).ToList());
_rows.Add(columns.ToList());
}
/// <inheritdoc/>
Measurement IRenderable.Measure(RenderContext context, int maxWidth)
protected override Measurement Measure(RenderContext context, int maxWidth)
{
if (context is null)
{
@@ -194,20 +164,20 @@ namespace Spectre.Console
}
/// <inheritdoc/>
IEnumerable<Segment> IRenderable.Render(RenderContext context, int width)
protected override IEnumerable<Segment> Render(RenderContext context, int maxWidth)
{
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
var border = Composition.Border.GetBorder(Border, (context.LegacyConsole || !context.Unicode) && SafeBorder);
var border = SpectreBorder.GetBorder(Border, (context.LegacyConsole || !context.Unicode) && SafeBorder);
var tableWidth = maxWidth;
var showBorder = Border != BorderKind.None;
var hideBorder = Border == BorderKind.None;
var hasRows = _rows.Count > 0;
var maxWidth = width;
if (Width != null)
{
maxWidth = Math.Min(Width.Value, maxWidth);
@@ -219,13 +189,13 @@ namespace Spectre.Console
var columnWidths = CalculateColumnWidths(context, maxWidth);
// Update the table width.
width = columnWidths.Sum() + GetExtraWidth(includePadding: true);
tableWidth = columnWidths.Sum() + GetExtraWidth(includePadding: true);
var rows = new List<List<Text>>();
var rows = new List<List<IRenderable>>();
if (ShowHeaders)
{
// Add columns to top of rows
rows.Add(new List<Text>(_columns.Select(c => c.Text)));
rows.Add(new List<IRenderable>(_columns.Select(c => c.Text)));
}
// Add rows.
@@ -244,7 +214,7 @@ namespace Spectre.Console
var justification = _columns[columnIndex].Alignment;
var childContext = context.WithJustification(justification);
var lines = Segment.SplitLines(((IRenderable)cell).Render(childContext, rowWidth));
var lines = Segment.SplitLines(cell.Render(childContext, rowWidth));
cellHeight = Math.Max(cellHeight, lines.Count);
cells.Add(lines);
}
@@ -268,7 +238,7 @@ namespace Spectre.Console
}
result.Add(new Segment(border.GetPart(BorderPart.HeaderTopRight)));
result.Add(Segment.LineBreak());
result.Add(Segment.LineBreak);
}
// Iterate through each cell row
@@ -327,7 +297,7 @@ namespace Spectre.Console
}
}
result.Add(Segment.LineBreak());
result.Add(Segment.LineBreak);
}
// Show header separator?
@@ -349,7 +319,7 @@ namespace Spectre.Console
}
result.Add(new Segment(border.GetPart(BorderPart.HeaderBottomRight)));
result.Add(Segment.LineBreak());
result.Add(Segment.LineBreak);
}
// Show bottom of footer?
@@ -371,7 +341,7 @@ namespace Spectre.Console
}
result.Add(new Segment(border.GetPart(BorderPart.FooterBottomRight)));
result.Add(Segment.LineBreak());
result.Add(Segment.LineBreak);
}
}

View File

@@ -1,16 +1,17 @@
using System;
using Spectre.Console.Rendering;
namespace Spectre.Console
{
/// <summary>
/// Represents a table column.
/// </summary>
public sealed class TableColumn
public sealed class TableColumn : IAlignable
{
/// <summary>
/// Gets the text associated with the column.
/// </summary>
public Text Text { get; }
public IRenderable Text { get; }
/// <summary>
/// Gets or sets the width of the column.
@@ -39,8 +40,17 @@ namespace Spectre.Console
/// </summary>
/// <param name="text">The table column text.</param>
public TableColumn(string text)
: this(new Markup(text))
{
Text = Text.New(text ?? throw new ArgumentNullException(nameof(text)));
}
/// <summary>
/// Initializes a new instance of the <see cref="TableColumn"/> class.
/// </summary>
/// <param name="renderable">The <see cref="IRenderable"/> instance to use as the table column.</param>
public TableColumn(IRenderable renderable)
{
Text = renderable ?? throw new ArgumentNullException(nameof(renderable));
Width = null;
Padding = new Padding(1, 1);
NoWrap = false;

View File

@@ -0,0 +1,78 @@
using System;
using System.Linq;
namespace Spectre.Console
{
/// <summary>
/// Contains extension methods for <see cref="Table"/>.
/// </summary>
public static class TableExtensions
{
/// <summary>
/// Adds a column to the table.
/// </summary>
/// <param name="table">The table to add the column to.</param>
/// <param name="column">The column to add.</param>
/// <returns>The added <see cref="TableColumn"/> instance.</returns>
public static TableColumn AddColumn(this Table table, string column)
{
if (table is null)
{
throw new ArgumentNullException(nameof(table));
}
if (column is null)
{
throw new ArgumentNullException(nameof(column));
}
var tableColumn = new TableColumn(column);
table.AddColumn(tableColumn);
return tableColumn;
}
/// <summary>
/// Adds multiple columns to the table.
/// </summary>
/// <param name="table">The table to add the columns to.</param>
/// <param name="columns">The columns to add.</param>
public static void AddColumns(this Table table, params string[] columns)
{
if (table is null)
{
throw new ArgumentNullException(nameof(table));
}
if (columns is null)
{
throw new ArgumentNullException(nameof(columns));
}
foreach (var column in columns)
{
AddColumn(table, column);
}
}
/// <summary>
/// Adds a row to the table.
/// </summary>
/// <param name="table">The table to add the row to.</param>
/// <param name="columns">The row columns to add.</param>
public static void AddRow(this Table table, params string[] columns)
{
if (table is null)
{
throw new ArgumentNullException(nameof(table));
}
if (columns is null)
{
throw new ArgumentNullException(nameof(columns));
}
table.AddRow(columns.Select(column => new Markup(column)).ToArray());
}
}
}

View File

@@ -0,0 +1,272 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Spectre.Console.Internal;
using Spectre.Console.Rendering;
namespace Spectre.Console
{
/// <summary>
/// A renderable piece of text.
/// </summary>
[DebuggerDisplay("{_text,nq}")]
[SuppressMessage("Naming", "CA1724:Type names should not match namespaces")]
public sealed class Text : Renderable, IAlignable
{
private readonly List<SegmentLine> _lines;
/// <summary>
/// Gets an empty <see cref="Text"/> instance.
/// </summary>
public static Text Empty { get; } = new Text(string.Empty);
/// <summary>
/// Gets or sets the text alignment.
/// </summary>
public Justify? Alignment { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="Text"/> class.
/// </summary>
public Text()
{
_lines = new List<SegmentLine>();
}
/// <summary>
/// Initializes a new instance of the <see cref="Text"/> class.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="style">The style of the text.</param>
public Text(string text, Style? style = null)
: this()
{
if (text is null)
{
throw new ArgumentNullException(nameof(text));
}
Append(text, style);
}
/// <summary>
/// Creates a <see cref="Text"/> instance representing
/// the specified markup text.
/// </summary>
/// <param name="text">The markup text.</param>
/// <param name="style">The text style.</param>
/// <returns>a <see cref="Text"/> instance representing the specified markup text.</returns>
public static Text Markup(string text, Style? style = null)
{
var result = MarkupParser.Parse(text, style ?? Style.Plain);
return result;
}
/// <inheritdoc/>
protected override Measurement Measure(RenderContext context, int maxWidth)
{
if (_lines.Count == 0)
{
return new Measurement(0, 0);
}
var min = _lines.Max(line => line.Max(segment => segment.CellLength(context.Encoding)));
var max = _lines.Max(x => x.CellWidth(context.Encoding));
return new Measurement(min, max);
}
/// <inheritdoc/>
protected override IEnumerable<Segment> Render(RenderContext context, int maxWidth)
{
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
if (_lines.Count == 0)
{
return Array.Empty<Segment>();
}
var lines = SplitLines(context, maxWidth);
// Justify lines
var justification = context.Justification ?? Alignment ?? Justify.Left;
foreach (var (_, _, last, line) in lines.Enumerate())
{
var length = line.Sum(l => l.StripLineEndings().CellLength(context.Encoding));
if (length < maxWidth)
{
// Justify right side
if (justification == Justify.Right)
{
var diff = maxWidth - length;
line.Prepend(new Segment(new string(' ', diff)));
}
else if (justification == Justify.Center)
{
// Left side.
var diff = (maxWidth - length) / 2;
line.Prepend(new Segment(new string(' ', diff)));
// Right side
line.Add(new Segment(new string(' ', diff)));
var remainder = (maxWidth - length) % 2;
if (remainder != 0)
{
line.Add(new Segment(new string(' ', remainder)));
}
}
}
}
return new SegmentLineEnumerator(lines);
}
/// <summary>
/// Appends a piece of text.
/// </summary>
/// <param name="text">The text to append.</param>
/// <param name="style">The style of the appended text.</param>
public void Append(string text, Style? style = null)
{
if (text is null)
{
throw new ArgumentNullException(nameof(text));
}
foreach (var (_, first, last, part) in text.SplitLines().Enumerate())
{
var current = part;
if (first)
{
var line = _lines.LastOrDefault();
if (line == null)
{
_lines.Add(new SegmentLine());
line = _lines.Last();
}
if (string.IsNullOrEmpty(current))
{
line.Add(Segment.Empty);
}
else
{
foreach (var span in current.SplitWords())
{
line.Add(new Segment(span, style ?? Style.Plain));
}
}
}
else
{
var line = new SegmentLine();
if (string.IsNullOrEmpty(current))
{
line.Add(Segment.Empty);
}
else
{
foreach (var span in current.SplitWords())
{
line.Add(new Segment(span, style ?? Style.Plain));
}
}
_lines.Add(line);
}
}
}
private List<SegmentLine> Clone()
{
var result = new List<SegmentLine>();
foreach (var line in _lines)
{
var newLine = new SegmentLine();
foreach (var segment in line)
{
newLine.Add(segment);
}
result.Add(newLine);
}
return result;
}
private List<SegmentLine> SplitLines(RenderContext context, int maxWidth)
{
if (_lines.Max(x => x.CellWidth(context.Encoding)) <= maxWidth)
{
return Clone();
}
var lines = new List<SegmentLine>();
var line = new SegmentLine();
var newLine = true;
using (var iterator = new SegmentLineIterator(_lines))
{
while (iterator.MoveNext())
{
var current = iterator.Current;
if (current == null)
{
throw new InvalidOperationException("Iterator returned empty segment.");
}
if (newLine && current.IsWhiteSpace && !current.IsLineBreak)
{
newLine = false;
continue;
}
newLine = false;
if (current.IsLineBreak)
{
line.Add(current);
lines.Add(line);
line = new SegmentLine();
newLine = true;
continue;
}
var length = current.CellLength(context.Encoding);
if (line.CellWidth(context.Encoding) + length > maxWidth)
{
line.Add(Segment.Empty);
lines.Add(line);
line = new SegmentLine();
newLine = true;
}
if (newLine && current.IsWhiteSpace)
{
continue;
}
newLine = false;
line.Add(current);
}
}
// Flush remaining.
if (line.Count > 0)
{
lines.Add(line);
}
return lines;
}
}
}

View File

@@ -57,6 +57,15 @@ namespace Spectre.Console
return StyleParser.Parse(text);
}
/// <summary>
/// Creates a copy of the current <see cref="Style"/>.
/// </summary>
/// <returns>A copy of the current <see cref="Style"/>.</returns>
public Style Clone()
{
return new Style(Foreground, Background, Decoration);
}
/// <summary>
/// Converts the string representation of a style to its <see cref="Style"/> equivalent.
/// A return value indicates whether the operation succeeded.