| 1 |
/** |
| 2 |
* Color utility functions for CSS generation and color manipulation |
| 3 |
*/ |
| 4 |
|
| 5 |
/** |
| 6 |
* Apply alpha (opacity) to a color string. |
| 7 |
* Supports hex (#RGB, #RRGGBB), rgb(), rgba(), hsl(), hsla(), and named colors. |
| 8 |
* For hex colors, appends the alpha hex component. For other formats, uses CSS color-mix or fallback. |
| 9 |
* |
| 10 |
* @param color - Color string in any CSS format |
| 11 |
* @param alphaHex - 2-digit hex representation of alpha (e.g., "26" for ~15% opacity) |
| 12 |
* @returns Color string with alpha applied |
| 13 |
*/ |
| 14 |
export function applyAlpha(color: string, alphaHex: string): string { |
| 15 |
if (!color || !alphaHex) return color |
| 16 |
|
| 17 |
if (!/^[0-9A-Fa-f]{2}$/.test(alphaHex)) { |
| 18 |
return color |
| 19 |
} |
| 20 |
|
| 21 |
// If it's a hex color (#RGB or #RRGGBB), append the alpha hex directly |
| 22 |
if (color.startsWith('#')) { |
| 23 |
if (color.length === 4) { |
| 24 |
// Expand 3-digit hex shorthand #RGB to #RRGGBB |
| 25 |
const expanded = `#${color[1]}${color[1]}${color[2]}${color[2]}${color[3]}${color[3]}` |
| 26 |
return `${expanded}${alphaHex}` |
| 27 |
} |
| 28 |
if (color.length === 7) { |
| 29 |
// Full 6-digit hex, append alpha hex |
| 30 |
return `${color}${alphaHex}` |
| 31 |
} |
| 32 |
// Already has alpha (5 or 8 chars), return as-is |
| 33 |
return color |
| 34 |
} |
| 35 |
|
| 36 |
// For rgb, rgba, hsl, hsla, or named colors, use CSS color-mix (modern approach) |
| 37 |
// This is more robust than trying to parse and convert formats |
| 38 |
// Fallback: use rgba with the color-mix syntax understood by most modern browsers |
| 39 |
const alphaDecimal = parseInt(alphaHex, 16) / 255 |
| 40 |
return `color-mix(in srgb, ${color} ${(alphaDecimal * 100).toFixed(1)}%, transparent)` |
| 41 |
} |
| 42 |
|