Label.tsx

 1import { Chip } from '@mui/material';
 2import { common } from '@mui/material/colors';
 3import { darken, getContrastRatio } from '@mui/material/styles';
 4
 5import { Color } from '../gqlTypes';
 6import { LabelFragment } from '../graphql/fragments.generated';
 7
 8const _rgb = (color: Color) =>
 9  'rgb(' + color.R + ',' + color.G + ',' + color.B + ')';
10
11// Minimum contrast between the background and the text color
12const contrastThreshold = 2.5;
13// Guess the text color based on the background color
14const getTextColor = (background: string) =>
15  getContrastRatio(background, common.white) >= contrastThreshold
16    ? common.white // White on dark backgrounds
17    : common.black; // And black on light ones
18
19// Create a style object from the label RGB colors
20const createStyle = (color: Color, maxWidth?: string) => ({
21  backgroundColor: _rgb(color),
22  color: getTextColor(_rgb(color)),
23  borderBottomColor: darken(_rgb(color), 0.2),
24  maxWidth: maxWidth,
25});
26
27type Props = {
28  label: LabelFragment;
29  inline?: boolean;
30  maxWidth?: string;
31  className?: string;
32};
33function Label({ label, inline, maxWidth, className }: Props) {
34  return (
35    <Chip
36      size={'small'}
37      label={label.name}
38      component={inline ? 'span' : 'div'}
39      className={className}
40      style={createStyle(label.color, maxWidth)}
41    />
42  );
43}
44export default Label;