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

Handle short form hex colors in conversion functions #24642

Merged
merged 2 commits into from
Mar 16, 2025
Merged
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
9 changes: 9 additions & 0 deletions src/common/color/convert-color.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,15 @@ export const hs2rgb = (hs: [number, number]): [number, number, number] =>

export function theme2hex(themeColor: string): string {
if (themeColor.startsWith("#")) {
if (themeColor.length === 4 || themeColor.length === 5) {
const c = themeColor;
// Convert short-form hex (#abc) to 6 digit (#aabbcc). Ignore alpha channel.
return `#${c[1]}${c[1]}${c[2]}${c[2]}${c[3]}${c[3]}`;
}
if (themeColor.length === 9) {
// Ignore alpha channel.
return themeColor.substring(0, 7);
}
return themeColor;
}

Expand Down
5 changes: 4 additions & 1 deletion test/common/color/convert-color.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,13 @@ describe("Color Conversion Tests", () => {
expect(hs2rgb(hs)).toEqual([255, 0, 0]);
});

it("should convert theme color to hex", () => {
it("should convert theme color to hex (ignoring alpha)", () => {
expect(theme2hex("red")).toBe("#ff0000");
expect(theme2hex("#ff0000")).toBe("#ff0000");
expect(theme2hex("unicorn")).toBe("unicorn");
expect(theme2hex("#abc")).toBe("#aabbcc");
expect(theme2hex("#abcd")).toBe("#aabbcc");
expect(theme2hex("#aabbccdd")).toBe("#aabbcc");
});

it("should convert rgb theme color to hex", () => {
Expand Down
Loading