Skip to content

Commit

Permalink
Remove: Tinycolor usage from component color utils (#35553)
Browse files Browse the repository at this point in the history
  • Loading branch information
jorgefilipecosta authored Oct 12, 2021
1 parent 286856e commit 17bdf97
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 10 deletions.
13 changes: 6 additions & 7 deletions packages/components/src/ui/utils/colors.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,14 @@
* External dependencies
*/
import memoize from 'memize';
import tinycolor from 'tinycolor2';
import { colord, extend } from 'colord';
import namesPlugin from 'colord/plugins/names';

/** @type {HTMLDivElement} */
let colorComputationNode;

extend( [ namesPlugin ] );

/**
* @return {HTMLDivElement | undefined} The HTML element for color computation.
*/
Expand All @@ -32,7 +35,7 @@ function getColorComputationNode() {
*/
function isColor( value ) {
if ( typeof value !== 'string' ) return false;
const test = tinycolor( value );
const test = colord( value );

return test.isValid();
}
Expand Down Expand Up @@ -77,12 +80,8 @@ const getComputedBackgroundColor = memoize( _getComputedBackgroundColor );
*/
export function getOptimalTextColor( backgroundColor ) {
const background = getComputedBackgroundColor( backgroundColor );
const isReadableWithBlackText = tinycolor.isReadable(
background,
'#000000'
);

return isReadableWithBlackText ? '#000000' : '#ffffff';
return colord( background ).isLight() ? '#000000' : '#ffffff';
}

/**
Expand Down
8 changes: 5 additions & 3 deletions packages/components/src/utils/colors.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
/**
* External dependencies
*/
import tinycolor from 'tinycolor2';
import { colord, extend } from 'colord';
import namesPlugin from 'colord/plugins/names';

extend( [ namesPlugin ] );

/**
* Generating a CSS compliant rgba() color value.
Expand All @@ -15,6 +18,5 @@ import tinycolor from 'tinycolor2';
* // rgba(0, 0, 0, 0.5)
*/
export function rgba( hexValue = '', alpha = 1 ) {
const { r, g, b } = tinycolor( hexValue ).toRgb();
return `rgba(${ r }, ${ g }, ${ b }, ${ alpha })`;
return colord( hexValue ).alpha( alpha ).toRgbString();
}
11 changes: 11 additions & 0 deletions packages/components/src/utils/test/colors.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
/**
* Internal dependencies
*/
import { rgba } from '../colors';

describe( 'rbga', () => {
it( 'should output the expected string', () => {
expect( rgba( '#000000', 0.5 ) ).toBe( 'rgba(0, 0, 0, 0.5)' );
expect( rgba( '#f00', 0.2 ) ).toBe( 'rgba(255, 0, 0, 0.2)' );
} );
} );

0 comments on commit 17bdf97

Please sign in to comment.