Skip to content

Commit 3514695

Browse files
authored
convert three digit hex to six (#976)
* convert three digit hex to six * add unit test in colors.spec.js * change threeDigitHexToSix to use regex
1 parent 4cbb7a2 commit 3514695

File tree

2 files changed

+17
-1
lines changed

2 files changed

+17
-1
lines changed

src/style/__tests__/colors.spec.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,14 @@ describe('style/Colors', () => {
1919
expect(uut.rgba(101, 200, 136, 0.25)).toBe('rgba(101, 200, 136, 0.25)');
2020
});
2121

22+
it('should add alpha to 3 digits hex color value', () => {
23+
expect(uut.rgba('#333', 0.7)).toBe('rgba(51, 51, 51, 0.7)');
24+
expect(uut.rgba('#333', 0.1)).toBe('rgba(51, 51, 51, 0.1)');
25+
expect(uut.rgba('#DEF', 0.25)).toBe('rgba(221, 238, 255, 0.25)');
26+
expect(uut.rgba('#F24', 1)).toBe('rgba(255, 34, 68, 1)');
27+
});
28+
29+
2230
it('should handle wrong number of params', () => {
2331
expect(() => uut.rgba(101, 136, 0.7)).toThrow(new Error('rgba can work with either 2 or 4 arguments'));
2432
});

src/style/colors.ts

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -204,7 +204,15 @@ function validateHex(value: string) {
204204
if (!/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/.test(value)) {
205205
throw new Error(`${value} is invalid hex color`);
206206
}
207-
return value.replace('#', '');
207+
value = value.replace('#', '');
208+
if (value.length === 3) {
209+
value = threeDigitHexToSix(value);
210+
}
211+
return value;
212+
}
213+
214+
function threeDigitHexToSix(value: string) {
215+
return value.replace(/./g, '$&$&');
208216
}
209217

210218
const TypedColors = Colors as ExtendTypeWith<typeof Colors, typeof colorsPalette>

0 commit comments

Comments
 (0)