Skip to content

Commit

Permalink
Implement 3 digit hex parsing (#1708)
Browse files Browse the repository at this point in the history
  • Loading branch information
TheMarteh authored Dec 4, 2024
1 parent 29ab313 commit 58bf89a
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
7 changes: 7 additions & 0 deletions src/Spectre.Console/Color.cs
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,13 @@ public static Color FromHex(string hex)
hex = hex.Substring(1);
}

// 3 digit hex codes are expanded to 6 digits
// by doubling each digit, conform to CSS color codes
if (hex.Length == 3)
{
hex = string.Concat(hex.Select(c => new string(c, 2)));
}

var r = byte.Parse(hex.Substring(0, 2), NumberStyles.HexNumber);
var g = byte.Parse(hex.Substring(2, 2), NumberStyles.HexNumber);
var b = byte.Parse(hex.Substring(4, 2), NumberStyles.HexNumber);
Expand Down
17 changes: 17 additions & 0 deletions src/Tests/Spectre.Console.Tests/Unit/ColorTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,23 @@ public void Should_Not_Parse_Non_Color_Try_From_Hex(string noncolor)
color.ShouldBe(Color.Default);
}

[Theory]
[InlineData("ffffff")]
[InlineData("#ffffff")]
[InlineData("fff")]
[InlineData("#fff")]
public void Should_Parse_3_Digit_Hex_Colors_From_Hex(string color)
{
// Given
var expected = new Color(255, 255, 255);

// When
var result = Color.FromHex(color);

// Then
result.ShouldBe(expected);
}

[Fact]
public void Should_Consider_Color_And_Non_Color_Equal()
{
Expand Down

0 comments on commit 58bf89a

Please sign in to comment.