Introduce MarkupInterpolated and MarkupLineInterpolated extensions (#761)

* Introduce MarkupInterpolated and MarkupLineInterpolated extensions

These new methods enable easily writing markup with a nice and intuitive syntax without having to worry about escaping the markup.

```csharp
string input = args[0];
string output = Process(input);
AnsiConsole.MarkupLineInterpolated($"[blue]{input}[/] -> [green]{output}[/]");

```

The `Interpolated` suffix was inspired by the Entity Framework Core [FromSqlInterpolated][1] method.

[1]: https://docs.microsoft.com/en-us/ef/core/querying/raw-sql#passing-parameters

* Fixing whitespace to match file scoped namespaces

* Adding FromInterpolated helper to Markup widget

Allows automatic handling of interpolated strings to be used on the Markup widget. This would be helpful for people working with Tables and the Tree control who would not be using the MarkupInterpolated methods.

* Documentation for markup interpolated methods.

Co-authored-by: Cédric Luthi <cedric.luthi@gmail.com>
This commit is contained in:
Phil Scott
2022-03-22 17:34:25 -04:00
committed by GitHub
parent 1f2629e2e1
commit 1d8154f9b0
6 changed files with 234 additions and 0 deletions

View File

@ -54,6 +54,29 @@ public sealed class Markup : Renderable, IAlignable, IOverflowable
return ((IRenderable)_paragraph).Render(context, maxWidth);
}
/// <summary>
/// Returns a new instance of a Markup widget from an interpolated string.
/// </summary>
/// <param name="value">The interpolated string value to write.</param>
/// <param name="style">The style of the text.</param>
/// <returns>A new markup instance.</returns>
public static Markup FromInterpolated(FormattableString value, Style? style = null)
{
return FromInterpolated(CultureInfo.CurrentCulture, value, style);
}
/// <summary>
/// Returns a new instance of a Markup widget from an interpolated string.
/// </summary>
/// <param name="provider">The format provider to use.</param>
/// <param name="value">The interpolated string value to write.</param>
/// <param name="style">The style of the text.</param>
/// <returns>A new markup instance.</returns>
public static Markup FromInterpolated(IFormatProvider provider, FormattableString value, Style? style = null)
{
return new Markup(EscapeInterpolated(provider, value), style);
}
/// <summary>
/// Escapes text so that it wont be interpreted as markup.
/// </summary>
@ -83,4 +106,10 @@ public sealed class Markup : Renderable, IAlignable, IOverflowable
return text.RemoveMarkup();
}
internal static string EscapeInterpolated(IFormatProvider provider, FormattableString value)
{
object?[] args = value.GetArguments().Select(arg => arg is string s ? s.EscapeMarkup() : arg).ToArray();
return string.Format(provider, value.Format, args);
}
}