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