Debian Codegraph @

node/@patternfly/react-core/src/components/Label/Label.tsx

raw
1 import { createRef, Fragment, useEffect, useRef, useState } from 'react';
2 import styles from '@patternfly/react-styles/css/components/Label/label';
3 import labelGrpStyles from '@patternfly/react-styles/css/components/Label/label-group';
4 import { Button } from '../Button';
5 import { Tooltip, TooltipPosition } from '../Tooltip';
6 import { css } from '@patternfly/react-styles';
7 import { useIsomorphicLayoutEffect } from '../../helpers';
8 import cssTextMaxWidth from '@patternfly/react-tokens/dist/esm/c_label__text_MaxWidth';
9 import RhMicronsCloseIcon from '@patternfly/react-icons/dist/esm/icons/rh-microns-close-icon';
10 import RhUiCheckCircleFillIcon from '@patternfly/react-icons/dist/esm/icons/rh-ui-check-circle-fill-icon';
11 import RhUiNotificationFillIcon from '@patternfly/react-icons/dist/esm/icons/rh-ui-notification-fill-icon';
12 import RhUiErrorFillIcon from '@patternfly/react-icons/dist/esm/icons/rh-ui-error-fill-icon';
13 import RhUiWarningFillIcon from '@patternfly/react-icons/dist/esm/icons/rh-ui-warning-fill-icon';
14 import RhUiInformationFillIcon from '@patternfly/react-icons/dist/esm/icons/rh-ui-information-fill-icon';
15
16 /** Semantic status for labels (default icon and status styling). */
17 export enum LabelStatus {
18 success = 'success',
19 warning = 'warning',
20 danger = 'danger',
21 info = 'info',
22 custom = 'custom'
23 }
24
25 /** Label palette color when not using the `status` prop. */
26 export enum LabelColor {
27 blue = 'blue',
28 teal = 'teal',
29 green = 'green',
30 orange = 'orange',
31 purple = 'purple',
32 red = 'red',
33 orangered = 'orangered',
34 grey = 'grey',
35 yellow = 'yellow'
36 }
37
38 export interface LabelProps extends React.HTMLProps<HTMLSpanElement> {
39 /** Content rendered inside the label. */
40 children?: React.ReactNode;
41 /** Additional classes added to the label. */
42 className?: string;
43 /** Color of the label. */
44 color?: 'blue' | 'teal' | 'green' | 'orange' | 'purple' | 'red' | 'orangered' | 'grey' | 'yellow' | LabelColor;
45 /** Variant of the label. */
46 variant?: 'outline' | 'filled' | 'overflow' | 'add';
47 /** Status of the label with a respective icon and color. Overrides the color set by the color property. */
48 status?: 'success' | 'warning' | 'danger' | 'info' | 'custom';
49 /** Flag indicating the label is compact. */
50 isCompact?: boolean;
51 /** Flag indicating the label is disabled. Works only on clickable labels, so either href or onClick props must be passed in. */
52 isDisabled?: boolean;
53 /** Flag indicating the label is editable. */
54 isEditable?: boolean;
55 /** Flag indicating the label is clickable. This flag will automatically be set if a href is passed, or if an onClick handler is passed and the label is not an overflow or add variant. This should be manually set when using the render prop. */
56 isClickable?: boolean;
57 /** Additional props passed to the editable label text div. Optionally passing onInput and onBlur callbacks will allow finer custom text input control. */
58 editableProps?: any;
59 /** Callback when an editable label completes an edit. */
60 onEditComplete?: (event: MouseEvent | KeyboardEvent, newText: string) => void;
61 /** Callback when an editable label cancels an edit. */
62 onEditCancel?: (event: KeyboardEvent, previousText: string) => void;
63 /** The max width of the label before it is truncated. Can be any valid CSS unit, such as '100%', '100px', or '16ch'. */
64 textMaxWidth?: string;
65 /** Position of the tooltip which is displayed if text is truncated */
66 tooltipPosition?:
67 | TooltipPosition
68 | 'auto'
69 | 'top'
70 | 'bottom'
71 | 'left'
72 | 'right'
73 | 'top-start'
74 | 'top-end'
75 | 'bottom-start'
76 | 'bottom-end'
77 | 'left-start'
78 | 'left-end'
79 | 'right-start'
80 | 'right-end';
81 /** Icon added to the left of the label text. Overrides the icon set by the status property. */
82 icon?: React.ReactNode;
83 /** Close click callback for removable labels. If present, label will have a close button. */
84 onClose?: (event: React.MouseEvent) => void;
85 /** Node for custom close button. */
86 closeBtn?: React.ReactNode;
87 /** Aria label for close button */
88 closeBtnAriaLabel?: string;
89 /** Additional properties for the default close button. */
90 closeBtnProps?: any;
91 /** Href for a label that is a link. If present, the label will change to an anchor element. This should not be passed in if the onClick prop is also passed in. */
92 href?: string;
93 /** Callback for when the label is clicked. This should not be passed in if the href or isEditable props are also passed in. */
94 onClick?: (event: React.MouseEvent) => void;
95 /** Forwards the label content and className to rendered function. Use this prop for react router support.*/
96 render?: ({
97 className,
98 content,
99 componentRef
100 }: {
101 className: string;
102 content: React.ReactNode;
103 componentRef: any;
104 }) => React.ReactNode;
105 }
106
107 const colorStyles: Record<LabelColor, string> = {
108 [LabelColor.blue]: styles.modifiers.blue,
109 [LabelColor.teal]: styles.modifiers.teal,
110 [LabelColor.green]: styles.modifiers.green,
111 [LabelColor.orange]: styles.modifiers.orange,
112 [LabelColor.purple]: styles.modifiers.purple,
113 [LabelColor.red]: styles.modifiers.red,
114 [LabelColor.orangered]: styles.modifiers.orangered,
115 [LabelColor.yellow]: styles.modifiers.yellow,
116 [LabelColor.grey]: ''
117 };
118
119 const statusIcons: Record<LabelStatus, React.ReactNode> = {
120 [LabelStatus.success]: <RhUiCheckCircleFillIcon />,
121 [LabelStatus.warning]: <RhUiWarningFillIcon />,
122 [LabelStatus.danger]: <RhUiErrorFillIcon />,
123 [LabelStatus.info]: <RhUiInformationFillIcon />,
124 [LabelStatus.custom]: <RhUiNotificationFillIcon />
125 };
126
127 export const Label: React.FunctionComponent<LabelProps> = ({
128 children,
129 className = '',
130 color = LabelColor.grey,
131 variant = 'filled',
132 status,
133 isCompact = false,
134 isDisabled = false,
135 isEditable = false,
136 isClickable: isClickableProp = false,
137 editableProps,
138 textMaxWidth,
139 tooltipPosition,
140 icon,
141 onClose,
142 onClick: onLabelClick,
143 onEditCancel,
144 onEditComplete,
145 closeBtn,
146 closeBtnAriaLabel,
147 closeBtnProps,
148 href,
149 render,
150 ...props
151 }: LabelProps) => {
152 const [isEditableActive, setIsEditableActive] = useState<boolean>(false);
153 const [currValue, setCurrValue] = useState(children);
154 const editableButtonRef = useRef<HTMLButtonElement>(undefined);
155 const editableInputRef = useRef<HTMLInputElement>(undefined);
156
157 const isOverflowLabel = variant === 'overflow';
158 const isAddLabel = variant === 'add';
159 const isClickable = isClickableProp || (onLabelClick && !isOverflowLabel && !isAddLabel) || href;
160
161 let _icon;
162 if (status) {
163 _icon = statusIcons[status];
164 }
165 if (icon) {
166 _icon = icon;
167 }
168
169 useEffect(() => {
170 const onDocMouseDown = (event: MouseEvent) => {
171 if (
172 isEditableActive &&
173 editableInputRef &&
174 editableInputRef.current &&
175 !editableInputRef.current.contains(event.target as Node)
176 ) {
177 if (editableInputRef.current.value) {
178 onEditComplete && onEditComplete(event, editableInputRef.current.value);
179 }
180 setIsEditableActive(false);
181 }
182 };
183
184 const onKeyDown = (event: KeyboardEvent) => {
185 const key = event.key;
186 if (
187 (!isEditableActive &&
188 (!editableButtonRef ||
189 !editableButtonRef.current ||
190 !editableButtonRef.current.contains(event.target as Node))) ||
191 (isEditableActive &&
192 (!editableInputRef || !editableInputRef.current || !editableInputRef.current.contains(event.target as Node)))
193 ) {
194 return;
195 }
196 if (isEditableActive && (key === 'Enter' || key === 'Tab')) {
197 event.preventDefault();
198 event.stopImmediatePropagation();
199 if (editableInputRef.current.value) {
200 onEditComplete && onEditComplete(event, editableInputRef.current.value);
201 }
202 setIsEditableActive(false);
203 editableButtonRef?.current?.focus();
204 }
205 if (isEditableActive && key === 'Escape') {
206 event.preventDefault();
207 event.stopImmediatePropagation();
208 // Reset div text to initial children prop - pre-edit
209 if (editableInputRef.current.value) {
210 editableInputRef.current.value = children as string;
211 onEditCancel && onEditCancel(event, children as string);
212 }
213 setIsEditableActive(false);
214 editableButtonRef?.current?.focus();
215 }
216 if (!isEditableActive && key === 'Enter') {
217 event.preventDefault();
218 event.stopImmediatePropagation();
219 setIsEditableActive(true);
220
221 // Set cursor position to end of text
222 const el = event.target as HTMLElement;
223 const range = document.createRange();
224 const sel = window.getSelection();
225 range.selectNodeContents(el);
226 range.collapse(false);
227 sel.removeAllRanges();
228 sel.addRange(range);
229 }
230 };
231
232 document.addEventListener('mousedown', onDocMouseDown);
233 document.addEventListener('keydown', onKeyDown);
234 return () => {
235 document.removeEventListener('mousedown', onDocMouseDown);
236 document.removeEventListener('keydown', onKeyDown);
237 };
238 }, [isEditableActive, editableInputRef, editableButtonRef, onEditComplete, onEditCancel, children]);
239
240 useEffect(() => {
241 if (onLabelClick && href) {
242 // eslint-disable-next-line no-console
243 console.warn(
244 'Link labels cannot have onClick passed, this results in invalid HTML. Please remove either the href or onClick prop.'
245 );
246 } else if (onLabelClick && isEditable) {
247 // eslint-disable-next-line no-console
248 console.warn(
249 'Editable labels cannot have onClick passed, clicking starts the label edit process. Please remove either the isEditable or onClick prop.'
250 );
251 }
252 }, [onLabelClick, href, isEditable]);
253
254 const isClickableDisabled = (href || onLabelClick) && isDisabled;
255
256 const defaultCloseButton = (
257 <Button
258 type="button"
259 variant="plain"
260 hasNoPadding
261 onClick={onClose}
262 aria-label={closeBtnAriaLabel || `Close ${children}`}
263 {...(isClickableDisabled && { isDisabled: true })}
264 {...closeBtnProps}
265 icon={<RhMicronsCloseIcon />}
266 />
267 );
268
269 const closeButton = <span className={css(styles.labelActions)}>{closeBtn || defaultCloseButton}</span>;
270 const textRef = createRef<any>();
271 // ref to apply tooltip when rendered is used
272 const componentRef = useRef(undefined);
273 const [isTooltipVisible, setIsTooltipVisible] = useState(false);
274 useIsomorphicLayoutEffect(() => {
275 const currTextRef = isEditable ? editableButtonRef : textRef;
276 if (!isEditableActive) {
277 setIsTooltipVisible(currTextRef.current && currTextRef.current.offsetWidth < currTextRef.current.scrollWidth);
278 }
279 }, [isEditableActive]);
280 const content = (
281 <Fragment>
282 {_icon && <span className={css(styles.labelIcon)}>{_icon}</span>}
283 <span
284 ref={textRef}
285 className={css(styles.labelText)}
286 {...(textMaxWidth && {
287 style: {
288 [cssTextMaxWidth.name]: textMaxWidth
289 } as React.CSSProperties
290 })}
291 >
292 {children}
293 </span>
294 </Fragment>
295 );
296
297 useEffect(() => {
298 if (isEditableActive && editableInputRef) {
299 editableInputRef.current && editableInputRef.current.focus();
300 }
301 }, [editableInputRef, isEditableActive]);
302
303 const updateVal = () => {
304 setCurrValue(editableInputRef.current.value);
305 };
306
307 let LabelComponentChildElement = 'span';
308 if (href) {
309 LabelComponentChildElement = 'a';
310 } else if (isEditable || (onLabelClick && !isOverflowLabel && !isAddLabel)) {
311 LabelComponentChildElement = 'button';
312 }
313
314 const clickableLabelProps = {
315 type: 'button',
316 onClick: onLabelClick
317 };
318
319 const isButton = LabelComponentChildElement === 'button';
320
321 const labelComponentChildProps = {
322 className: css(styles.labelContent, isClickable && styles.modifiers.clickable),
323 ...(isTooltipVisible && { tabIndex: 0 }),
324 ...(href && { href }),
325 // Need to prevent onClick since aria-disabled won't prevent AT from triggering the link
326 ...(href && isDisabled && { onClick: (event: MouseEvent) => event.preventDefault() }),
327 ...(isButton && clickableLabelProps),
328 ...(isEditable && {
329 ref: editableButtonRef,
330 onClick: (e: React.MouseEvent) => {
331 setIsEditableActive(true);
332 e.stopPropagation();
333 },
334 ...editableProps
335 }),
336 ...(isClickableDisabled && isButton && { disabled: true }),
337 ...(isClickableDisabled && href && { tabIndex: -1, 'aria-disabled': true })
338 };
339
340 let labelComponentChild = (
341 <LabelComponentChildElement {...labelComponentChildProps}>{content}</LabelComponentChildElement>
342 );
343
344 if (render) {
345 labelComponentChild = (
346 <Fragment>
347 {isTooltipVisible && <Tooltip triggerRef={componentRef} content={children} position={tooltipPosition} />}
348 {render({
349 className: styles.labelContent,
350 content,
351 componentRef
352 })}
353 </Fragment>
354 );
355 } else if (isTooltipVisible) {
356 labelComponentChild = (
357 <Tooltip content={children} position={tooltipPosition}>
358 {labelComponentChild}
359 </Tooltip>
360 );
361 }
362
363 const LabelComponent = (isOverflowLabel || isAddLabel ? 'button' : 'span') as any;
364
365 return (
366 <LabelComponent
367 {...props}
368 className={css(
369 styles.label,
370 isClickableDisabled && styles.modifiers.disabled,
371 colorStyles[color],
372 variant === 'filled' && styles.modifiers.filled,
373 variant === 'outline' && styles.modifiers.outline,
374 status && styles.modifiers[status],
375 isOverflowLabel && styles.modifiers.overflow,
376 isCompact && styles.modifiers.compact,
377 isEditable && labelGrpStyles.modifiers.editable,
378 isEditableActive && styles.modifiers.editableActive,
379 isClickable && styles.modifiers.clickable,
380 isAddLabel && styles.modifiers.add,
381 className
382 )}
383 onClick={isOverflowLabel || isAddLabel ? onLabelClick : undefined}
384 {...(LabelComponent === 'button' && { type: 'button' })}
385 >
386 {!isEditableActive && labelComponentChild}
387 {!isEditableActive && onClose && closeButton}
388 {isEditableActive && (
389 <input
390 className={css(styles.labelContent)}
391 type="text"
392 id="editable-input"
393 ref={editableInputRef}
394 value={currValue}
395 onChange={updateVal}
396 {...editableProps}
397 />
398 )}
399 </LabelComponent>
400 );
401 };
402 Label.displayName = 'Label';