Label.tsx

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