Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add method to TrimEnd FormattedMessage #5308

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions Robust.Shared/Utility/FormattedMessage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,40 @@ public void Clear()
_nodes.Clear();
}

/// <summary>
/// Removes excess whitespace at the end of markup.
/// </summary>
public void TrimEnd()
{
for (var i = _nodes.Count - 1; i >= 0; i--)
{
var node = _nodes[i];
var markup = node.Value;

if (markup.StringValue == null)
break;

var value = markup.StringValue.Trim();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Isn't this going to trim at the end of both sides of the last node?


// If we stripped all text then remove the node and continue.
if (string.IsNullOrEmpty(value))
{
_nodes.RemoveAt(i);
continue;
}

// Only trimmed some of it so update node and stop.
if (value != node.Value.StringValue)
{
_nodes.RemoveAt(i);
markup = markup with { StringValue = value };
_nodes.Add(new MarkupNode(value, markup, node.Attributes));
}

break;
}
}

/// <summary>
/// Returns an enumerator that enumerates every rune for each text node contained in this formatted text instance.
/// </summary>
Expand Down
24 changes: 24 additions & 0 deletions Robust.UnitTesting/Shared/Utility/FormattedMessage_Test.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,30 @@ namespace Robust.UnitTesting.Shared.Utility
[TestOf(typeof(FormattedMessage))]
public sealed class FormattedMessage_Test
{
private static (FormattedMessage Message, bool Trimmed)[] _trimMessages = new[]
{
(FormattedMessage.FromUnformatted("weh"), false),
(FormattedMessage.FromUnformatted("weh "), true),
(FormattedMessage.Empty, false),
(FormattedMessage.FromUnformatted("weh\n"), true),
};

[Test, TestCaseSource(nameof(_trimMessages))]
public static void TestTrimEnd((FormattedMessage message, bool shouldTrim) test)
{
var copy = FormattedMessage.FromUnformatted(test.message.ToString());
copy.TrimEnd();

if (test.shouldTrim)
{
Assert.That(copy.ToString(), Is.Not.EqualTo(test.message.ToString()));
}
else
{
Assert.That(copy.ToString(), Is.EqualTo(test.message.ToString()));
}
}

[Test]
public static void TestParseMarkup()
{
Expand Down
Loading