* Parses a hex color string to RGB values. * Supports #RGB, #RRGGBB formats (with or without #).
(hex: string)
| 22 | * Supports #RGB, #RRGGBB formats (with or without #). |
| 23 | */ |
| 24 | function parseHexColor(hex: string): [number, number, number] | null { |
| 25 | // Remove # if present and trim whitespace |
| 26 | const cleanHex = hex.replace(/^#/, '').trim(); |
| 27 | |
| 28 | if (!/^[0-9A-Fa-f]+$/.test(cleanHex)) { |
| 29 | return null; |
| 30 | } |
| 31 | |
| 32 | let r: number, g: number, b: number; |
| 33 | |
| 34 | if (cleanHex.length === 3) { |
| 35 | // #RGB format |
| 36 | r = parseInt(cleanHex[0] + cleanHex[0], 16); |
| 37 | g = parseInt(cleanHex[1] + cleanHex[1], 16); |
| 38 | b = parseInt(cleanHex[2] + cleanHex[2], 16); |
| 39 | } else if (cleanHex.length === 6) { |
| 40 | // #RRGGBB format |
| 41 | r = parseInt(cleanHex.slice(0, 2), 16); |
| 42 | g = parseInt(cleanHex.slice(2, 4), 16); |
| 43 | b = parseInt(cleanHex.slice(4, 6), 16); |
| 44 | } else { |
| 45 | return null; |
| 46 | } |
| 47 | |
| 48 | return [r, g, b]; |
| 49 | } |
| 50 | |
| 51 | /** |
| 52 | * Checks if a search string looks like a hex color code. |
no test coverage detected