Skip to content

[EuiAvatar] Calculate high-contrast text against background #7824

@daniel-rhoades

Description

@daniel-rhoades

Summary

Within the Avatar component, for the purposes of rendering initials, the text colour is selected based either the selected or generated background colour:

const assignedColor =
color || visColors[Math.floor(name.length % visColors.length)];
const textColor = isColorDark(...hexToRgb(assignedColor))
? '#FFFFFF'
: '#000000';

Currently, the logic simplistically chooses white (for dark backgrounds) or black (for light backgrounds), this won't necessarily provide a sufficient contrast against some background colours. Neither is there support for explicitly setting the text colour.

A similar issue applies to the Badge component:

export const getTextColor = ({ euiTheme }: UseEuiTheme, bgColor: string) => {
const textColor = isColorDark(...chroma(bgColor).rgb())
? euiTheme.colors.ghost
: euiTheme.colors.ink;
return textColor;
};

Albeit inconsistent with Avatar, the Badge component does at least raise a contrast warning:

// Set dark or light text color based upon best contrast
const textColor = getTextColor(euiTheme, color);
// Check the contrast ratio. If it's low contrast, emit a console awrning
const contrastRatio = getColorContrast(textColor, color);
if (contrastRatio < wcagContrastMin) {
console.warn(
`Warning: ${color} badge has a low contrast of ${contrastRatio.toFixed(
2
)}. Should be above ${wcagContrastMin}.`
);
}

Acceptance Criteria

  1. Calculate an appropriate high-contrasting colour (WCAG AA compliant) based on the background colour
  2. (Optionally) expose an additional property to allow the colour to be overridden

Fortunately, an existing utility function already exists within the EUI component library for calculating an appropriate contrasting colour: makeHighContrastColor.

Metadata

Metadata

Assignees

No one assigned

    Labels

    accessibilityhelp wantedThe EUI team is unlikely prioritize. (Don't delete - used for automation)stale-issue(Don't delete - used for automation)

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions