Label.js

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