Skip to content
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

[core] Add support #rrggbbaa pattern in hexToRgb function #20931

Merged
merged 2 commits into from
May 8, 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
10 changes: 8 additions & 2 deletions packages/material-ui/src/styles/colorManipulator.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,14 +27,20 @@ function clamp(value, min = 0, max = 1) {
export function hexToRgb(color) {
color = color.substr(1);

const re = new RegExp(`.{1,${color.length / 3}}`, 'g');
const re = new RegExp(`.{1,${color.length >= 6 ? 2 : 1}}`, 'g');
let colors = color.match(re);

if (colors && colors[0].length === 1) {
colors = colors.map((n) => n + n);
}

return colors ? `rgb(${colors.map((n) => parseInt(n, 16)).join(', ')})` : '';
return colors
? `rgb${colors.length === 4 ? 'a' : ''}(${colors
.map((n, index) => {
return index < 3 ? parseInt(n, 16) : Math.round((parseInt(n, 16) / 255) * 1000) / 1000;
})
.join(', ')})`
: '';
}

function intToHex(int) {
Expand Down
12 changes: 12 additions & 0 deletions packages/material-ui/src/styles/colorManipulator.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,10 @@ describe('utils/colorManipulator', () => {
it('converts a long hex color to an rgb color` ', () => {
expect(hexToRgb('#a94fd3')).to.equal('rgb(169, 79, 211)');
});

it('converts a long alpha hex color to an argb color` ', () => {
expect(hexToRgb('#111111f8')).to.equal('rgba(17, 17, 17, 0.973)');
});
});

describe('rgbToHex', () => {
Expand Down Expand Up @@ -125,6 +129,14 @@ describe('utils/colorManipulator', () => {
const output2 = decomposeColor(output1);
expect(output1).to.deep.equal(output2);
});

it('converts rgba hex', () => {
const decomposed = decomposeColor('#111111f8');
expect(decomposed).to.deep.equal({
type: 'rgba',
values: [17, 17, 17, 0.973],
});
});
});

describe('getContrastRatio', () => {
Expand Down