Skip to content

Commit 98bf1dc

Browse files
committed
Use function to get the composite background color
1 parent 2eec7a6 commit 98bf1dc

File tree

2 files changed

+23
-11
lines changed

2 files changed

+23
-11
lines changed

packages/components/src/color-palette/index.tsx

+9-10
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ import type { WordPressComponentProps } from '../ui/context';
4343
import type { DropdownProps } from '../dropdown/types';
4444
import {
4545
extractColorNameFromCurrentValue,
46+
getCompositeBackgroundColor,
4647
isMultiplePaletteArray,
4748
normalizeColorValue,
4849
showTransparentBackground,
@@ -227,14 +228,10 @@ function UnforwardedColorPalette(
227228
);
228229

229230
const colordColor = colord( normalizedColorValue ?? '' );
230-
const mixedColor =
231-
colordColor.alpha() < 1
232-
? colord( '#fff' ).mix(
233-
colordColor.alpha( 1 ),
234-
colordColor.alpha()
235-
)
236-
: colordColor;
237-
231+
const compositeColor = getCompositeBackgroundColor(
232+
colord( '#fff' ),
233+
colordColor
234+
);
238235
const valueWithoutLeadingHash = value?.startsWith( '#' )
239236
? value.substring( 1 )
240237
: value ?? '';
@@ -285,8 +282,10 @@ function UnforwardedColorPalette(
285282
: {
286283
background: value,
287284
color:
288-
mixedColor.contrast() >
289-
mixedColor.contrast( '#000' )
285+
compositeColor.contrast() >
286+
compositeColor.contrast(
287+
'#000'
288+
)
290289
? '#fff'
291290
: '#000',
292291
}

packages/components/src/color-palette/utils.ts

+14-1
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,11 @@
22
* External dependencies
33
*/
44
import type { RefObject } from 'react';
5+
import type { Colord } from 'colord';
56
import { colord, extend } from 'colord';
67
import namesPlugin from 'colord/plugins/names';
78
import a11yPlugin from 'colord/plugins/a11y';
9+
import mixPlugin from 'colord/plugins/mix';
810

911
/**
1012
* WordPress dependencies
@@ -16,7 +18,7 @@ import { __ } from '@wordpress/i18n';
1618
*/
1719
import type { ColorObject, ColorPaletteProps, PaletteObject } from './types';
1820

19-
extend( [ namesPlugin, a11yPlugin ] );
21+
extend( [ namesPlugin, a11yPlugin, mixPlugin ] );
2022

2123
export const extractColorNameFromCurrentValue = (
2224
currentValue?: ColorPaletteProps[ 'value' ],
@@ -96,3 +98,14 @@ export const normalizeColorValue = (
9698
? colord( computedBackgroundColor ).toHex()
9799
: value;
98100
};
101+
102+
// Composite with background color behind when the front background color is transparent
103+
// to get the actual background color.
104+
export const getCompositeBackgroundColor = (
105+
behindColor: Colord,
106+
frontColor: Colord
107+
) => {
108+
return frontColor.alpha() < 1
109+
? behindColor.mix( frontColor.alpha( 1 ), frontColor.alpha() )
110+
: frontColor;
111+
};

0 commit comments

Comments
 (0)