-
Notifications
You must be signed in to change notification settings - Fork 841
/
badge.tsx
379 lines (340 loc) Β· 10.3 KB
/
badge.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import React, {
AriaAttributes,
FunctionComponent,
HTMLAttributes,
MouseEventHandler,
ReactNode,
Ref,
} from 'react';
import classNames from 'classnames';
import chroma from 'chroma-js';
import { CommonProps, ExclusiveUnion, keysOf, PropsOf } from '../common';
import {
euiPaletteColorBlindBehindText,
getSecureRelForTarget,
isColorDark,
} from '../../services';
import { EuiInnerText } from '../inner_text';
import { EuiIcon, IconColor, IconType } from '../icon';
import { chromaValid, parseColor } from '../color_picker/utils';
type IconSide = 'left' | 'right';
type WithButtonProps = {
/**
* Will apply an onclick to the badge itself
*/
onClick: MouseEventHandler<HTMLButtonElement>;
/**
* Aria label applied to the onClick button
*/
onClickAriaLabel: AriaAttributes['aria-label'];
} & Omit<HTMLAttributes<HTMLButtonElement>, 'onClick' | 'color'>;
type WithAnchorProps = {
href: string;
target?: string;
rel?: string;
} & Omit<HTMLAttributes<HTMLAnchorElement>, 'href' | 'color' | 'onClick'>;
type WithSpanProps = Omit<HTMLAttributes<HTMLSpanElement>, 'onClick' | 'color'>;
interface WithIconOnClick {
/**
* Will apply an onclick to icon within the badge
*/
iconOnClick: MouseEventHandler<HTMLButtonElement>;
/**
* Aria label applied to the iconOnClick button
*/
iconOnClickAriaLabel: AriaAttributes['aria-label'];
}
export type EuiBadgeProps = {
/**
* Accepts any string from our icon library
*/
iconType?: IconType;
/**
* The side of the badge the icon should sit
*/
iconSide?: IconSide;
/**
* Accepts either our palette colors (primary, secondary ..etc) or a hex value `#FFFFFF`, `#000`.
*/
color?: IconColor;
/**
* Will override any color passed through the `color` prop.
*/
isDisabled?: boolean;
/**
* Props passed to the close button.
*/
closeButtonProps?: Partial<PropsOf<EuiIcon>>;
} & CommonProps &
ExclusiveUnion<WithIconOnClick, {}> &
ExclusiveUnion<
ExclusiveUnion<WithButtonProps, WithAnchorProps>,
WithSpanProps
>;
// TODO - replace with variables once https://github.com/elastic/eui/issues/2731 is closed
const colorInk = '#000';
const colorGhost = '#fff';
// The color blind palette has some stricter accessibility needs with regards to
// charts and contrast. We use the euiPaletteColorBlindBehindText variant here since our
// accessibility concerns pertain to foreground (text) and background contrast
const visColors = euiPaletteColorBlindBehindText();
const colorToHexMap: { [color in IconColor]: string } = {
// TODO - replace with variable once https://github.com/elastic/eui/issues/2731 is closed
default: '#d3dae6',
primary: visColors[1],
secondary: visColors[0],
accent: visColors[2],
warning: visColors[5],
danger: visColors[9],
};
export const COLORS = keysOf(colorToHexMap);
const iconSideToClassNameMap: { [side in IconSide]: string } = {
left: 'euiBadge--iconLeft',
right: 'euiBadge--iconRight',
};
export const ICON_SIDES = keysOf(iconSideToClassNameMap);
export const EuiBadge: FunctionComponent<EuiBadgeProps> = ({
children,
color = 'default',
iconType,
iconSide = 'left',
className,
isDisabled,
onClick,
iconOnClick,
onClickAriaLabel,
iconOnClickAriaLabel,
closeButtonProps,
href,
rel,
target,
style,
...rest
}) => {
checkValidColor(color);
let optionalCustomStyles: object | undefined = style;
let textColor = null;
// TODO - replace with variable once https://github.com/elastic/eui/issues/2731 is closed
const wcagContrastBase = 4.5; // WCAG AA contrast level
let wcagContrast = null;
let colorHex = null;
// Check if a valid color name was provided
if (COLORS.indexOf(color) > -1) {
// Get the hex equivalent for the provided color name
colorHex = colorToHexMap[color];
// Set dark or light text color based upon best contrast
textColor = setTextColor(colorHex);
optionalCustomStyles = {
backgroundColor: colorHex,
color: textColor,
...optionalCustomStyles,
};
} else if (color !== 'hollow') {
// This is a custom color that is neither from the base palette nor hollow
// Let's do our best to ensure that it provides sufficient contrast
// Set dark or light text color based upon best contrast
textColor = setTextColor(color);
// Check the contrast
wcagContrast = getColorContrast(textColor, color);
if (wcagContrast < wcagContrastBase) {
// It's low contrast, so lets show a warning in the console
console.warn(
'Warning: ',
color,
' badge has low contrast of ',
wcagContrast.toFixed(2),
'. Should be above ',
wcagContrastBase,
'.'
);
}
optionalCustomStyles = {
backgroundColor: color,
color: textColor,
...optionalCustomStyles,
};
}
const classes = classNames(
'euiBadge',
{
'euiBadge-isClickable': (onClick || href) && !iconOnClick,
'euiBadge-isDisabled': isDisabled,
'euiBadge--hollow': color === 'hollow',
},
iconSideToClassNameMap[iconSide],
className
);
const closeClassNames = classNames(
'euiBadge__icon',
closeButtonProps && closeButtonProps.className
);
const Element = href && !isDisabled ? 'a' : 'button';
const relObj: {
href?: string;
target?: string;
rel?: string;
onClick?:
| ((event: React.MouseEvent<HTMLButtonElement, MouseEvent>) => void)
| ((event: React.MouseEvent<HTMLAnchorElement, MouseEvent>) => void);
} = {};
if (href && !isDisabled) {
relObj.href = href;
relObj.target = target;
relObj.rel = getSecureRelForTarget({ href, target, rel });
} else if (onClick) {
relObj.onClick = onClick;
}
let optionalIcon: ReactNode = null;
if (iconType) {
if (iconOnClick) {
if (!iconOnClickAriaLabel) {
console.warn(
'When passing the iconOnClick props to EuiBadge, you must also provide iconOnClickAriaLabel'
);
}
optionalIcon = (
<button
className="euiBadge__iconButton"
aria-label={iconOnClickAriaLabel}
disabled={isDisabled}
title={iconOnClickAriaLabel}
onClick={iconOnClick}>
<EuiIcon
type={iconType}
size="s"
{...closeButtonProps}
className={closeClassNames}
/>
</button>
);
} else {
optionalIcon = (
<EuiIcon
type={iconType}
size={children ? 's' : 'm'}
className="euiBadge__icon"
/>
);
}
}
if (onClick && !onClickAriaLabel) {
console.warn(
'When passing onClick to EuiBadge, you must also provide onClickAriaLabel'
);
}
const content = (
<span className="euiBadge__content">
{children && <span className="euiBadge__text">{children}</span>}
{optionalIcon}
</span>
);
if (iconOnClick) {
return onClick || href ? (
<span className={classes} style={optionalCustomStyles}>
<span className="euiBadge__content">
<EuiInnerText>
{(ref, innerText) => (
<Element
className="euiBadge__childButton"
disabled={isDisabled}
aria-label={onClickAriaLabel}
ref={ref}
title={innerText}
{...(relObj as HTMLAttributes<HTMLElement>)}
{...(rest as HTMLAttributes<HTMLElement>)}>
{children}
</Element>
)}
</EuiInnerText>
{optionalIcon}
</span>
</span>
) : (
<EuiInnerText>
{(ref, innerText) => (
<span
className={classes}
style={optionalCustomStyles}
ref={ref}
title={innerText}
{...rest}>
{content}
</span>
)}
</EuiInnerText>
);
} else if (onClick || href) {
return (
<EuiInnerText>
{(ref, innerText) => (
<Element
disabled={isDisabled}
aria-label={onClickAriaLabel}
className={classes}
style={optionalCustomStyles}
ref={ref as Ref<HTMLButtonElement & HTMLAnchorElement>}
title={innerText}
{...(relObj as HTMLAttributes<HTMLElement>)}
{...(rest as HTMLAttributes<HTMLElement>)}>
{content}
</Element>
)}
</EuiInnerText>
);
} else {
return (
<EuiInnerText>
{(ref, innerText) => (
<span
className={classes}
style={optionalCustomStyles}
ref={ref}
title={innerText}
{...rest}>
{content}
</span>
)}
</EuiInnerText>
);
}
};
function getColorContrast(textColor: string, color: string) {
const contrastValue = chroma.contrast(textColor, color);
return contrastValue;
}
function setTextColor(bgColor: string) {
const textColor = isColorDark(...chroma(bgColor).rgb())
? colorGhost
: colorInk;
return textColor;
}
function checkValidColor(color: null | IconColor | string) {
const colorExists = !!color;
const isNamedColor = (color && COLORS.includes(color)) || color === 'hollow';
const isValidColorString = color && chromaValid(parseColor(color) || '');
if (!colorExists && !isNamedColor && !isValidColorString) {
console.warn(
'EuiBadge expects a valid color. This can either be a three or six ' +
`character hex value, rgb(a) value, hsv value, hollow, or one of the following: ${COLORS}. ` +
`Instead got ${color}.`
);
}
}