diff --git a/packages/charts/src/common/color_calcs.ts b/packages/charts/src/common/color_calcs.ts index e37a952715..32207766e2 100644 --- a/packages/charts/src/common/color_calcs.ts +++ b/packages/charts/src/common/color_calcs.ts @@ -146,6 +146,8 @@ export function colorIsDark(color: Color): boolean { return luminance < 0.2; } +const invert = (r: number, g: number, b: number) => [r, g, b].map((x) => 255 - x).join(','); + /** * inverse color for text * @internal @@ -159,27 +161,24 @@ export function getTextColorIfTextInvertible( ): Color { const inverseForContrast = specifiedTextColorIsDark === backgroundIsDark; const { r: tr, g: tg, b: tb, opacity: to } = stringToRGB(textColor); - if (!textContrast) { - return inverseForContrast - ? to === undefined - ? `rgb(${255 - tr}, ${255 - tg}, ${255 - tb})` - : `rgba(${255 - tr}, ${255 - tg}, ${255 - tb}, ${to})` - : textColor; - } - if (textContrast === true) { - return inverseForContrast - ? to === undefined - ? makeHighContrastColor(`rgb(${255 - tr}, ${255 - tg}, ${255 - tb})`, backgroundColor) - : makeHighContrastColor(`rgba(${255 - tr}, ${255 - tg}, ${255 - tb}, ${to})`, backgroundColor) - : makeHighContrastColor(textColor, backgroundColor); - } else if (typeof textContrast === 'number') { + const inverted = invert(tr, tg, tb); + + if (!textContrast) + return inverseForContrast ? (to === undefined ? `rgb(${inverted})` : `rgba(${inverted}, ${to})`) : textColor; + + if (textContrast && typeof textContrast !== 'number') return contrast(); + + if (typeof textContrast === 'number') return contrast(textContrast); + + return 'black'; // this should never happen; added it as previously function return type included undefined; todo + + function contrast(ratio?: any) { return inverseForContrast ? to === undefined - ? makeHighContrastColor(`rgb(${255 - tr}, ${255 - tg}, ${255 - tb})`, backgroundColor, textContrast) - : makeHighContrastColor(`rgba(${255 - tr}, ${255 - tg}, ${255 - tb}, ${to})`, backgroundColor, textContrast) - : makeHighContrastColor(textColor, backgroundColor, textContrast); + ? makeHighContrastColor(`rgb(${inverted})`, backgroundColor, ratio || undefined) + : makeHighContrastColor(`rgba(${inverted}, ${to})`, backgroundColor, ratio || undefined) + : makeHighContrastColor(textColor, backgroundColor, ratio || undefined); } - return 'black'; // this should never happen; added it as previously function return type included undefined; todo } /**