Label.tsx

 1import React from 'react';
 2
 3import { common } from '@material-ui/core/colors';
 4import { makeStyles } from '@material-ui/core/styles';
 5import {
 6  getContrastRatio,
 7  darken,
 8} from '@material-ui/core/styles/colorManipulator';
 9
10import { LabelFragment } from '../graphql/fragments.generated';
11import { Color } from 'src/gqlTypes';
12
13// Minimum contrast between the background and the text color
14const contrastThreshold = 2.5;
15
16// Guess the text color based on the background color
17const getTextColor = (background: string) =>
18  getContrastRatio(background, common.white) >= contrastThreshold
19    ? common.white // White on dark backgrounds
20    : common.black; // And black on light ones
21
22const _rgb = (color: Color) =>
23  'rgb(' + color.R + ',' + color.G + ',' + color.B + ')';
24
25// Create a style object from the label RGB colors
26const createStyle = (color: Color) => ({
27  backgroundColor: _rgb(color),
28  color: getTextColor(_rgb(color)),
29  borderBottomColor: darken(_rgb(color), 0.2),
30});
31
32const useStyles = makeStyles((theme) => ({
33  label: {
34    ...theme.typography.body1,
35    padding: '1px 6px 0.5px',
36    fontSize: '0.9em',
37    fontWeight: 500,
38    margin: '0.05em 1px calc(-1.5px + 0.05em)',
39    borderRadius: '3px',
40    display: 'inline-block',
41    borderBottom: 'solid 1.5px',
42    verticalAlign: 'bottom',
43  },
44}));
45
46type Props = { label: LabelFragment };
47function Label({ label }: Props) {
48  const classes = useStyles();
49  return (
50    <span className={classes.label} style={createStyle(label.color)}>
51      {label.name}
52    </span>
53  );
54}
55
56export default Label;