From 0256da511dbba043dc4d4562e1f22ea5fdc93b29 Mon Sep 17 00:00:00 2001 From: Adam Kapos Date: Tue, 18 Feb 2025 14:04:46 +0700 Subject: [PATCH] Fix theme2hex with custom theme colors (#24282) --- src/common/color/convert-color.ts | 19 +++++++++++++------ test/common/color/convert-color.test.ts | 12 ++++++++++++ 2 files changed, 25 insertions(+), 6 deletions(-) diff --git a/src/common/color/convert-color.ts b/src/common/color/convert-color.ts index 5afac322e8..2253b0fe24 100644 --- a/src/common/color/convert-color.ts +++ b/src/common/color/convert-color.ts @@ -136,11 +136,18 @@ export function theme2hex(themeColor: string): string { } const rgbFromColorName = colors[themeColor]; - if (!rgbFromColorName) { - // We have a named color, and there's nothing in the table, - // so nothing further we can do with it. - // Compare/border/background color will all be the same. - return themeColor; + if (rgbFromColorName) { + return rgb2hex(rgbFromColorName); } - return rgb2hex(rgbFromColorName); + + const rgbMatch = themeColor.match(/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/); + if (rgbMatch) { + const [, r, g, b] = rgbMatch.map(Number); + return rgb2hex([r, g, b]); + } + + // We have a named color, and there's nothing in the table, + // so nothing further we can do with it. + // Compare/border/background color will all be the same. + return themeColor; } diff --git a/test/common/color/convert-color.test.ts b/test/common/color/convert-color.test.ts index c04e995b2c..f3cc873109 100644 --- a/test/common/color/convert-color.test.ts +++ b/test/common/color/convert-color.test.ts @@ -51,4 +51,16 @@ describe("Color Conversion Tests", () => { expect(theme2hex("#ff0000")).toBe("#ff0000"); expect(theme2hex("unicorn")).toBe("unicorn"); }); + + it("should convert rgb theme color to hex", () => { + expect(theme2hex("rgb( 255, 0, 0)")).toBe("#ff0000"); + expect(theme2hex("rgb(0,255, 0)")).toBe("#00ff00"); + expect(theme2hex("rgb(0, 0,255 )")).toBe("#0000ff"); + }); + + it("should convert rgba theme color to hex by ignoring alpha", () => { + expect(theme2hex("rgba( 255, 0, 0, 0.5)")).toBe("#ff0000"); + expect(theme2hex("rgba(0,255, 0, 0.3)")).toBe("#00ff00"); + expect(theme2hex("rgba(0, 0,255 , 0.7)")).toBe("#0000ff"); + }); });