| 1 | export function parseHexColor(hexColor: string): { |
| 2 | r: number; |
| 3 | g: number; |
| 4 | b: number; |
| 5 | } { |
| 6 | if (hexColor.startsWith("#")) { |
| 7 | hexColor = hexColor.slice(1); |
| 8 | } |
| 9 | |
| 10 | if (hexColor.length > 6) { |
| 11 | hexColor = hexColor.slice(0, 6); |
| 12 | } |
| 13 | |
| 14 | const r = parseInt(hexColor.substring(0, 2), 16); |
| 15 | const g = parseInt(hexColor.substring(2, 4), 16); |
| 16 | const b = parseInt(hexColor.substring(4, 6), 16); |
| 17 | |
| 18 | return { r, g, b }; |
| 19 | } |
| 20 | |
| 21 | export function parseColorForHex(colorVar: string): string { |
| 22 | const value = getComputedStyle(document.documentElement).getPropertyValue( |
| 23 | colorVar, |
| 24 | ); |
| 25 | if (value.startsWith("#")) { |
| 26 | return value.slice(0, 7); |
| 27 | } |
| 28 | |
| 29 | // Parse rgb/rgba |
| 30 | const rgbValues = value |
| 31 | .slice(value.startsWith("rgba") ? 5 : 4, -1) |
| 32 | .split(",") |
| 33 | .map((x) => x.trim()) |
| 34 | .filter((_, i) => i < 3) // Only take the first 3 values (RGB, ignore alpha) |
| 35 | .map((x) => parseInt(x, 10)); |
| 36 | |
| 37 | let hex = |
| 38 | "#" + |
| 39 | rgbValues |
| 40 | .map((x) => x.toString(16)) |
| 41 | .map((x) => (x.length === 1 ? "0" + x : x)) |
| 42 | .join(""); |
| 43 | |
| 44 | return hex; |
| 45 | } |