Skip to content
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: 6 additions & 2 deletions src/__tests__/input-color.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import React from 'react';
import renderer from 'react-test-renderer';
import InputColor from '../';
import { parseColor, hex2alpha } from '../utils';
import { parseColor, hex2alpha, rgbaToHex } from '../utils';

test('render', () => {
expect(() =>
Expand Down Expand Up @@ -29,7 +29,7 @@ test('parseColor', () => {
s: 76,
v: 86,
a: 20,
hex: '#3498db',
hex: '#3498db32',
rgba: 'rgba(52,152,219,0.2)',
});
});
Expand All @@ -40,3 +40,7 @@ test('hex2alpha', () => {
expect(hex2alpha('38')).toEqual(22);
expect(hex2alpha('00')).toEqual(0);
});

test('rgbaToHex', () => {
expect(rgbaToHex('rgba(255, 255, 255,0.5))')).toEqual(`#ffffff80`);
});
4 changes: 3 additions & 1 deletion src/color-picker.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
rgba,
hsv2rgb,
} from '@swiftcarrot/color-fns';
import { rgbaToHex } from './utils';

const KEY_ENTER = 13;

Expand All @@ -35,7 +36,8 @@ const ColorPicker = ({ color, onChange }) => {
}

function changeAlpha(a) {
changeColor({ ...color, a });
const hex = rgbaToHex(`rgba(${r}, ${g}, ${b}, ${a / 100})`);
changeColor({ ...color, a, hex });
}

function changeHex(hex) {
Expand Down
30 changes: 29 additions & 1 deletion src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ export function hex2alpha(aa) {

export function parseColor(hexColor) {
hexColor = hexColor.toLowerCase();
const hex = hexColor.substr(0, 7);
const hex = hexColor;
const rgb = hex2rgb(hex);
const { r, g, b } = rgb;
const hsv = rgb2hsv(r, g, b);
Expand All @@ -15,6 +15,34 @@ export function parseColor(hexColor) {
return { ...hsv, r, g, b, a, hex, rgba: rgba(r, g, b, a) };
}

export function trim(str) {
return str.replace(/^\s+|\s+$/gm, '');
}

export function rgbaToHex(rgba) {
let inParts = rgba.substring(rgba.indexOf('(')).split(','),
r = parseInt(trim(inParts[0].substring(1)), 10),
g = parseInt(trim(inParts[1]), 10),
b = parseInt(trim(inParts[2]), 10),
a = parseFloat(
trim(inParts[3].substring(0, inParts[3].length - 1)),
).toFixed(2);
let outParts = [
r.toString(16),
g.toString(16),
b.toString(16),
Math.round(a * 255)
.toString(16)
.substring(0, 2),
];
outParts.forEach(function (part, i) {
if (part.length === 1) {
outParts[i] = '0' + part;
}
});
return '#' + outParts.join('');
}

export {
rgb2hsv,
hsv2hex,
Expand Down