| 1 | /** |
| 2 | * Converts various color input formats to an {r:0,g:0,b:0} object. |
| 3 | * |
| 4 | * @param {string} color The string representation of a color |
| 5 | * @example |
| 6 | * colorToRgb('#000'); |
| 7 | * @example |
| 8 | * colorToRgb('#000000'); |
| 9 | * @example |
| 10 | * colorToRgb('rgb(0,0,0)'); |
| 11 | * @example |
| 12 | * colorToRgb('rgba(0,0,0)'); |
| 13 | * |
| 14 | * @return {{r: number, g: number, b: number, [a]: number}|null} |
| 15 | */ |
| 16 | export const colorToRgb = (color: string) => { |
| 17 | let hex3 = color.match(/^#([0-9a-f]{3})$/i); |
| 18 | if (hex3 && hex3[1]) { |
| 19 | const hex3Value = hex3[1]; |
| 20 | return { |
| 21 | r: parseInt(hex3Value.charAt(0), 16) * 0x11, |
| 22 | g: parseInt(hex3Value.charAt(1), 16) * 0x11, |
| 23 | b: parseInt(hex3Value.charAt(2), 16) * 0x11, |
| 24 | }; |
| 25 | } |
| 26 | |
| 27 | let hex6 = color.match(/^#([0-9a-f]{6})$/i); |
| 28 | if (hex6 && hex6[1]) { |
| 29 | const hex6Value = hex6[1]; |
| 30 | return { |
| 31 | r: parseInt(hex6Value.slice(0, 2), 16), |
| 32 | g: parseInt(hex6Value.slice(2, 4), 16), |
| 33 | b: parseInt(hex6Value.slice(4, 6), 16), |
| 34 | }; |
| 35 | } |
| 36 | |
| 37 | let rgb = color.match(/^rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/i); |
| 38 | if (rgb) { |
| 39 | return { |
| 40 | r: parseInt(rgb[1], 10), |
| 41 | g: parseInt(rgb[2], 10), |
| 42 | b: parseInt(rgb[3], 10), |
| 43 | }; |
| 44 | } |
| 45 | |
| 46 | let rgba = color.match( |
| 47 | /^rgba\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*([\d]+|[\d]*.[\d]+)\s*\)$/i |
| 48 | ); |
| 49 | if (rgba) { |
| 50 | return { |
| 51 | r: parseInt(rgba[1], 10), |
| 52 | g: parseInt(rgba[2], 10), |
| 53 | b: parseInt(rgba[3], 10), |
| 54 | a: parseFloat(rgba[4]), |
| 55 | }; |
| 56 | } |
| 57 | |
| 58 | return null; |
| 59 | }; |
| 60 | |
| 61 | /** |
| 62 | * Calculates brightness on a scale of 0-255. |
| 63 | * |
| 64 | * @param {string} color See colorToRgb for supported formats. |
| 65 | * @see {@link colorToRgb} |
| 66 | */ |
| 67 | export const colorBrightness = (color: string | { r: number; g: number; b: number } | null) => { |
| 68 | if (typeof color === 'string') color = colorToRgb(color); |
| 69 | |
| 70 | if (color) { |
| 71 | return (color.r * 299 + color.g * 587 + color.b * 114) / 1000; |
| 72 | } |
| 73 | |
| 74 | return null; |
| 75 | }; |
| 76 |