Skip to content

Commit

Permalink
ColorPalette: make more resilient against duplicate colors
Browse files Browse the repository at this point in the history
  • Loading branch information
ciampo committed Aug 9, 2022
1 parent 60adc79 commit 4fe18ea
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 6 deletions.
16 changes: 11 additions & 5 deletions packages/components/src/color-palette/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
/**
* External dependencies
*/
import { map } from 'lodash';
import { colord, extend } from 'colord';
import namesPlugin from 'colord/plugins/names';
import a11yPlugin from 'colord/plugins/a11y';
Expand Down Expand Up @@ -35,15 +34,22 @@ function SinglePalette( {
actions,
} ) {
const colorOptions = useMemo( () => {
return map( colors, ( { color, name } ) => {
// In case the palette contains multiple entries with the same color value,
// only consider the first instance as the "selected" one.
const firstMatchedColorIndex = colors.findIndex(
( { color } ) => color === value
);

return colors.map( ( { color, name }, index ) => {
const colordColor = colord( color );
const isSelected = firstMatchedColorIndex === index;

return (
<CircularOptionPicker.Option
key={ color }
isSelected={ value === color }
key={ `${ color }-${ index }` }
isSelected={ isSelected }
selectedIconProps={
value === color
isSelected
? {
fill:
colordColor.contrast() >
Expand Down
13 changes: 12 additions & 1 deletion packages/components/src/color-palette/stories/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ MultipleOrigins.args = {
],
},
{
name: 'Primary colors',
name: 'Secondary colors',
colors: [
{ name: 'Orange', color: '#f60' },
{ name: 'Green', color: '#0f0' },
Expand Down Expand Up @@ -112,3 +112,14 @@ CSSVariables.args = {
{ name: 'Blue', color: 'var(--blue)' },
],
};

export const DuplicatedColors = Template.bind( {} );
DuplicatedColors.args = {
colors: [
{ name: 'Primary', color: '#f00' },
{ name: 'Secondary', color: '#ff0' },
{ name: 'Accent', color: '#00f' },
{ name: 'Primary', color: '#f00' },
{ name: 'Accent2', color: '#00f' },
],
};

0 comments on commit 4fe18ea

Please sign in to comment.