Label.tsx

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