|
1 | 1 | import type { IColor, IRangeColor, IRgb, IRgba } from "../Core/Interfaces/Colors.js"; |
2 | 2 | import type { IColorManager } from "../Core/Interfaces/IColorManager.js"; |
3 | 3 |
|
| 4 | +/** |
| 5 | + * Indexes for accessing color components from regex capture groups. |
| 6 | + * Uses 1-based indexing as index 0 contains the full match. |
| 7 | + */ |
4 | 8 | enum RgbIndexes { |
5 | 9 | r = 1, |
6 | 10 | g = 2, |
7 | 11 | b = 3, |
8 | 12 | a = 4, |
9 | 13 | } |
10 | 14 |
|
| 15 | +const shorthandHexRegex = /^#?([a-f\d])([a-f\d])([a-f\d])([a-f\d])?$/i, |
| 16 | + hexRegex = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})?$/i, |
| 17 | + hexRadix = 16, |
| 18 | + defaultAlpha = 1, |
| 19 | + alphaFactor = 0xff; |
| 20 | + |
11 | 21 | /** |
| 22 | + * Manages hexadecimal color string parsing and conversion to RGB/RGBA format. |
| 23 | + * Implements the IColorManager interface for handling hex color values. |
12 | 24 | */ |
13 | 25 | export class HexColorManager implements IColorManager { |
14 | 26 | readonly key; |
@@ -40,25 +52,20 @@ export class HexColorManager implements IColorManager { |
40 | 52 | return; |
41 | 53 | } |
42 | 54 |
|
43 | | - const shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])([a-f\d])?$/i, |
44 | | - hexFixed = hexColor.replace(shorthandRegex, (_, r: string, g: string, b: string, a: string) => { |
| 55 | + const hexFixed = hexColor.replace(shorthandHexRegex, (_, r: string, g: string, b: string, a: string) => { |
45 | 56 | return r + r + g + g + b + b + (a !== undefined ? a + a : ""); |
46 | 57 | }), |
47 | | - regex = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})?$/i, |
48 | | - result = regex.exec(hexFixed), |
49 | | - radix = 16, |
50 | | - defaultAlpha = 1, |
51 | | - alphaFactor = 0xff; |
| 58 | + result = hexRegex.exec(hexFixed); |
52 | 59 |
|
53 | 60 | return result |
54 | 61 | ? { |
55 | 62 | a: |
56 | 63 | result[RgbIndexes.a] !== undefined |
57 | | - ? parseInt(result[RgbIndexes.a], radix) / alphaFactor |
| 64 | + ? parseInt(result[RgbIndexes.a], hexRadix) / alphaFactor |
58 | 65 | : defaultAlpha, |
59 | | - b: parseInt(result[RgbIndexes.b], radix), |
60 | | - g: parseInt(result[RgbIndexes.g], radix), |
61 | | - r: parseInt(result[RgbIndexes.r], radix), |
| 66 | + b: parseInt(result[RgbIndexes.b], hexRadix), |
| 67 | + g: parseInt(result[RgbIndexes.g], hexRadix), |
| 68 | + r: parseInt(result[RgbIndexes.r], hexRadix), |
62 | 69 | } |
63 | 70 | : undefined; |
64 | 71 | } |
|
0 commit comments