Skip to content

Commit 58bf89a

Browse files
authored
Implement 3 digit hex parsing (#1708)
1 parent 29ab313 commit 58bf89a

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
lines changed

src/Spectre.Console/Color.cs

+7
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,13 @@ public static Color FromHex(string hex)
230230
hex = hex.Substring(1);
231231
}
232232

233+
// 3 digit hex codes are expanded to 6 digits
234+
// by doubling each digit, conform to CSS color codes
235+
if (hex.Length == 3)
236+
{
237+
hex = string.Concat(hex.Select(c => new string(c, 2)));
238+
}
239+
233240
var r = byte.Parse(hex.Substring(0, 2), NumberStyles.HexNumber);
234241
var g = byte.Parse(hex.Substring(2, 2), NumberStyles.HexNumber);
235242
var b = byte.Parse(hex.Substring(4, 2), NumberStyles.HexNumber);

src/Tests/Spectre.Console.Tests/Unit/ColorTests.cs

+17
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,23 @@ public void Should_Not_Parse_Non_Color_Try_From_Hex(string noncolor)
6868
color.ShouldBe(Color.Default);
6969
}
7070

71+
[Theory]
72+
[InlineData("ffffff")]
73+
[InlineData("#ffffff")]
74+
[InlineData("fff")]
75+
[InlineData("#fff")]
76+
public void Should_Parse_3_Digit_Hex_Colors_From_Hex(string color)
77+
{
78+
// Given
79+
var expected = new Color(255, 255, 255);
80+
81+
// When
82+
var result = Color.FromHex(color);
83+
84+
// Then
85+
result.ShouldBe(expected);
86+
}
87+
7188
[Fact]
7289
public void Should_Consider_Color_And_Non_Color_Equal()
7390
{

0 commit comments

Comments
 (0)