From 58bf89a56a7f747665acff45484abf9182fd3977 Mon Sep 17 00:00:00 2001 From: Martijn Straathof <55099674+TheMarteh@users.noreply.github.com> Date: Wed, 4 Dec 2024 16:31:21 +0100 Subject: [PATCH] Implement 3 digit hex parsing (#1708) --- src/Spectre.Console/Color.cs | 7 +++++++ .../Spectre.Console.Tests/Unit/ColorTests.cs | 17 +++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/src/Spectre.Console/Color.cs b/src/Spectre.Console/Color.cs index d3fc25396..9c87d62f4 100644 --- a/src/Spectre.Console/Color.cs +++ b/src/Spectre.Console/Color.cs @@ -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); diff --git a/src/Tests/Spectre.Console.Tests/Unit/ColorTests.cs b/src/Tests/Spectre.Console.Tests/Unit/ColorTests.cs index e2ea9dde1..cae3cb54a 100644 --- a/src/Tests/Spectre.Console.Tests/Unit/ColorTests.cs +++ b/src/Tests/Spectre.Console.Tests/Unit/ColorTests.cs @@ -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() {