Fix custom theme support for short hex & rgba hex strings (#29726)

* Fix custom theme support for hex colours other than 6-char

Signed-off-by: Michael Telatynski <7t3chguy@gmail.com>

* Iterate

Signed-off-by: Michael Telatynski <7t3chguy@gmail.com>

* Iterate

Signed-off-by: Michael Telatynski <7t3chguy@gmail.com>

* Iterate

Signed-off-by: Michael Telatynski <7t3chguy@gmail.com>

---------

Signed-off-by: Michael Telatynski <7t3chguy@gmail.com>
This commit is contained in:
Michael Telatynski
2025-04-14 09:31:21 +01:00
committed by GitHub
parent 779543fa0f
commit 1430fd5af6
2 changed files with 86 additions and 5 deletions

View File

@@ -129,7 +129,7 @@ function clearCustomTheme(): void {
// remove all css variables, we assume these are there because of the custom theme
const inlineStyleProps = Object.values(document.body.style);
for (const prop of inlineStyleProps) {
if (prop.startsWith("--")) {
if (typeof prop === "string" && prop.startsWith("--")) {
document.body.style.removeProperty(prop);
}
}
@@ -206,16 +206,49 @@ function generateCustomCompoundCSS(theme: CompoundTheme): string {
return `@layer compound.custom { :root, [class*="cpd-theme-"] { ${properties.join(" ")} } }`;
}
/**
* Normalizes the hex colour to 8 characters (including alpha)
* @param hexColor the hex colour to normalize
*/
function normalizeHexColour(hexColor: string): string {
switch (hexColor.length) {
case 4:
case 5:
// Short RGB or RGBA hex
return `#${hexColor
.slice(1)
.split("")
.map((c) => c + c)
.join("")}`;
case 7:
// Long RGB hex
return `${hexColor}ff`;
default:
return hexColor;
}
}
function setHexAlpha(normalizedHexColor: string, alpha: number): string {
return normalizeHexColour(normalizedHexColor).slice(0, 7) + Math.round(alpha).toString(16).padStart(2, "0");
}
function parseAlpha(normalizedHexColor: string): number {
return parseInt(normalizedHexColor.slice(7), 16);
}
function setCustomThemeVars(customTheme: CustomTheme): void {
const { style } = document.body;
function setCSSColorVariable(name: string, hexColor: string, doPct = true): void {
style.setProperty(`--${name}`, hexColor);
const normalizedHexColor = normalizeHexColour(hexColor);
const baseAlpha = parseAlpha(normalizedHexColor);
if (doPct) {
// uses #rrggbbaa to define the color with alpha values at 0%, 15% and 50%
style.setProperty(`--${name}-0pct`, hexColor + "00");
style.setProperty(`--${name}-15pct`, hexColor + "26");
style.setProperty(`--${name}-50pct`, hexColor + "7F");
// uses #rrggbbaa to define the color with alpha values at 0%, 15% and 50% (relative to base alpha channel)
style.setProperty(`--${name}-0pct`, setHexAlpha(normalizedHexColor, 0));
style.setProperty(`--${name}-15pct`, setHexAlpha(normalizedHexColor, baseAlpha * 0.15));
style.setProperty(`--${name}-50pct`, setHexAlpha(normalizedHexColor, baseAlpha * 0.5));
}
}