Skip to content

convert three digit hex to six #976

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Oct 23, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions src/style/__tests__/colors.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,14 @@ describe('style/Colors', () => {
expect(uut.rgba(101, 200, 136, 0.25)).toBe('rgba(101, 200, 136, 0.25)');
});

it('should add alpha to 3 digits hex color value', () => {
expect(uut.rgba('#333', 0.7)).toBe('rgba(51, 51, 51, 0.7)');
expect(uut.rgba('#333', 0.1)).toBe('rgba(51, 51, 51, 0.1)');
expect(uut.rgba('#DEF', 0.25)).toBe('rgba(221, 238, 255, 0.25)');
expect(uut.rgba('#F24', 1)).toBe('rgba(255, 34, 68, 1)');
});


it('should handle wrong number of params', () => {
expect(() => uut.rgba(101, 136, 0.7)).toThrow(new Error('rgba can work with either 2 or 4 arguments'));
});
Expand Down
10 changes: 9 additions & 1 deletion src/style/colors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,15 @@ function validateHex(value: string) {
if (!/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/.test(value)) {
throw new Error(`${value} is invalid hex color`);
}
return value.replace('#', '');
value = value.replace('#', '');
if (value.length === 3) {
value = threeDigitHexToSix(value);
}
return value;
}

function threeDigitHexToSix(value: string) {
return value.replace(/./g, '$&$&');
}

const TypedColors = Colors as ExtendTypeWith<typeof Colors, typeof colorsPalette>
Expand Down