| 1 | // Function to generate a complementary color |
| 2 | export function getComplementaryColor(hexColor: string | undefined): string { |
| 3 | // Default to a nice blue if no color is provided |
| 4 | if (!hexColor) return `#3498db` |
| 5 | |
| 6 | // Remove the hash if it exists |
| 7 | const color = hexColor.replace(/^#/, ``) |
| 8 | |
| 9 | // Convert hex to RGB |
| 10 | const r = parseInt(color.substring(0, 2), 16) |
| 11 | const g = parseInt(color.substring(2, 2), 16) |
| 12 | const b = parseInt(color.substring(4, 2), 16) |
| 13 | |
| 14 | // Calculate complementary color (inverting the RGB values) |
| 15 | const compR = 255 - r |
| 16 | const compG = 255 - g |
| 17 | const compB = 255 - b |
| 18 | |
| 19 | // Calculate brightness of the background |
| 20 | const brightness = r * 0.299 + g * 0.587 + b * 0.114 |
| 21 | |
| 22 | // If the complementary color doesn't have enough contrast, adjust it |
| 23 | const compBrightness = compR * 0.299 + compG * 0.587 + compB * 0.114 |
| 24 | const brightnessDiff = Math.abs(brightness - compBrightness) |
| 25 | |
| 26 | if (brightnessDiff < 128) { |
| 27 | // Not enough contrast, use a more vibrant alternative |
| 28 | if (brightness > 128) { |
| 29 | // Dark color for light background |
| 30 | return `#8e44ad` // Purple |
| 31 | } else { |
| 32 | // Light color for dark background |
| 33 | return `#f1c40f` // Yellow |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | // Convert back to hex |
| 38 | return `#${((1 << 24) + (compR << 16) + (compG << 8) + compB).toString(16).slice(1)}` |
| 39 | } |