Debian Codegraph @

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

raw
1 import { Fragment, useEffect, useRef, useState, useContext } from 'react';
2 import { css } from '@patternfly/react-styles';
3 import styles from '@patternfly/react-styles/css/components/Alert/alert';
4 import alertGroupStyles from '@patternfly/react-styles/css/components/Alert/alert-group';
5 import { AlertIcon } from './AlertIcon';
6 import { capitalize, useOUIAProps, OUIAProps } from '../../helpers';
7 import { AlertContext } from './AlertContext';
8 import { AlertGroupContext } from './AlertGroupContext';
9 import maxLines from '@patternfly/react-tokens/dist/esm/c_alert__title_max_lines';
10 import { Tooltip, TooltipPosition } from '../Tooltip';
11 import { AlertToggleExpandButton } from './AlertToggleExpandButton';
12
13 export enum AlertVariant {
14 success = 'success',
15 danger = 'danger',
16 warning = 'warning',
17 info = 'info',
18 custom = 'custom'
19 }
20
21 /** The main alert component. */
22
23 export interface AlertProps extends Omit<React.HTMLProps<HTMLDivElement>, 'action' | 'title'>, OUIAProps {
24 /** Close button; use the alert action close button component. */
25 actionClose?: React.ReactNode;
26 /** Action links; use a single alert action link component or multiple wrapped in an array
27 * or React fragment.
28 */
29 actionLinks?: React.ReactNode;
30 /** Content rendered inside the alert. */
31 children?: React.ReactNode;
32 /** Additional classes to add to the alert. */
33 className?: string;
34 /** Set a custom icon to the alert. If not set the icon is set according to the variant. */
35 customIcon?: React.ReactNode;
36 /** Uniquely identifies the alert. */
37 id?: string;
38 /** Flag indicating that the alert is expandable. */
39 isExpandable?: boolean;
40 /** Flag to indicate if the alert is inline. */
41 isInline?: boolean;
42 /** Flag to indicate if the alert is in a live region. */
43 isLiveRegion?: boolean;
44 /** Flag to indicate if the alert is plain. */
45 isPlain?: boolean;
46 /** Function to be executed on alert timeout. Relevant when the timeout prop is set. */
47 onTimeout?: () => void;
48 /** If set to true, the timeout is 8000 milliseconds. If a number is provided, alert will
49 * be dismissed after that amount of time in milliseconds.
50 */
51 timeout?: number | boolean;
52 /** If the user hovers over the alert and `timeout` expires, this is how long to wait
53 * before finally dismissing the alert.
54 */
55 timeoutAnimation?: number;
56 /** Title of the alert. */
57 title: React.ReactNode;
58 /** Sets the element to use as the alert title. Default is h4. */
59 component?: keyof React.JSX.IntrinsicElements;
60 /** Adds accessible text to the alert toggle. */
61 toggleAriaLabel?: string;
62 /** Position of the tooltip which is displayed if text is truncated. */
63 tooltipPosition?:
64 | TooltipPosition
65 | 'auto'
66 | 'top'
67 | 'bottom'
68 | 'left'
69 | 'right'
70 | 'top-start'
71 | 'top-end'
72 | 'bottom-start'
73 | 'bottom-end'
74 | 'left-start'
75 | 'left-end'
76 | 'right-start'
77 | 'right-end';
78 /** Truncate title to number of lines. */
79 truncateTitle?: number;
80 /** Adds alert variant styles. */
81 variant?: 'success' | 'danger' | 'warning' | 'info' | 'custom';
82 /** Variant label text for screen readers. */
83 variantLabel?: string;
84 /** Value to overwrite the randomly generated data-ouia-component-id.*/
85 ouiaId?: number | string;
86 /** Set the value of data-ouia-safe. Only set to true when the component is in a static state, i.e. no animations are occurring. At all other times, this value must be false. */
87 ouiaSafe?: boolean;
88 }
89
90 export const Alert: React.FunctionComponent<AlertProps> = ({
91 variant = AlertVariant.custom,
92 isInline = false,
93 isPlain = false,
94 isLiveRegion = false,
95 variantLabel = `${capitalize(variant)} alert:`,
96 actionClose,
97 actionLinks,
98 title,
99 component = 'h4',
100 children = '',
101 className = '',
102 ouiaId,
103 ouiaSafe = true,
104 timeout = false,
105 timeoutAnimation = 3000,
106 onTimeout = () => {},
107 truncateTitle = 0,
108 tooltipPosition,
109 customIcon,
110 isExpandable = false,
111 toggleAriaLabel = `${capitalize(variant)} alert details`,
112 onMouseEnter = () => {},
113 onMouseLeave = () => {},
114 id,
115 ...props
116 }: AlertProps) => {
117 const ouiaProps = useOUIAProps(Alert.displayName, ouiaId, ouiaSafe, variant);
118 const getHeadingContent = (
119 <Fragment>
120 <span className="pf-v6-screen-reader">{variantLabel}</span>
121 {title}
122 </Fragment>
123 );
124
125 const titleRef = useRef(null);
126 const TitleComponent = component as any;
127
128 const divRef = useRef<HTMLDivElement>(undefined);
129 const [isTooltipVisible, setIsTooltipVisible] = useState(false);
130 useEffect(() => {
131 if (!titleRef.current || !truncateTitle) {
132 return;
133 }
134 titleRef.current.style.setProperty(maxLines.name, truncateTitle.toString());
135 const showTooltip = titleRef.current && titleRef.current.offsetHeight < titleRef.current.scrollHeight;
136 if (isTooltipVisible !== showTooltip) {
137 setIsTooltipVisible(showTooltip);
138 }
139 }, [titleRef, truncateTitle, isTooltipVisible]);
140
141 const [timedOut, setTimedOut] = useState(false);
142 const [timedOutAnimation, setTimedOutAnimation] = useState(true);
143 const [isMouseOver, setIsMouseOver] = useState<boolean | undefined>();
144 const [containsFocus, setContainsFocus] = useState<boolean | undefined>();
145 const shouldDismiss = timedOut && timedOutAnimation && !isMouseOver && !containsFocus;
146 const [isDismissed, setIsDismissed] = useState(false);
147 const { hasAnimations, updateTransitionEnd } = useContext(AlertGroupContext);
148 const { offstageRight } = alertGroupStyles.modifiers;
149
150 const getParentAlertGroupItem = () => divRef.current?.closest(`.${alertGroupStyles.alertGroupItem}`);
151 useEffect(() => {
152 const shouldSetDismissed = shouldDismiss && !isDismissed;
153 if (!shouldSetDismissed) {
154 return;
155 }
156
157 const alertGroupItem = getParentAlertGroupItem();
158 alertGroupItem?.classList.add(offstageRight);
159
160 if (hasAnimations) {
161 updateTransitionEnd(() => {
162 setIsDismissed(true);
163 });
164 } else {
165 setIsDismissed(true);
166 }
167 }, [shouldDismiss, isDismissed]);
168
169 useEffect(() => {
170 const calculatedTimeout = timeout === true ? 8000 : Number(timeout);
171 if (calculatedTimeout > 0) {
172 const timer = setTimeout(() => setTimedOut(true), calculatedTimeout);
173 return () => clearTimeout(timer);
174 }
175 }, [timeout]);
176 useEffect(() => {
177 const onDocumentFocus = () => {
178 if (divRef.current) {
179 if (divRef.current.contains(document.activeElement)) {
180 setContainsFocus(true);
181 setTimedOutAnimation(false);
182 } else if (containsFocus) {
183 setContainsFocus(false);
184 }
185 }
186 };
187
188 document.addEventListener('focus', onDocumentFocus, true);
189
190 return () => document.removeEventListener('focus', onDocumentFocus, true);
191 }, [containsFocus]);
192 useEffect(() => {
193 if (containsFocus === false || isMouseOver === false) {
194 const timer = setTimeout(() => setTimedOutAnimation(true), timeoutAnimation);
195 return () => clearTimeout(timer);
196 }
197 }, [containsFocus, isMouseOver, timeoutAnimation]);
198 useEffect(() => {
199 isDismissed && onTimeout();
200 }, [isDismissed, onTimeout]);
201 useEffect(() => {
202 const alertGroupItem = getParentAlertGroupItem();
203 setTimeout(() => alertGroupItem?.classList.remove(alertGroupStyles.modifiers.offstageTop), 0);
204 }, []);
205
206 const [isExpanded, setIsExpanded] = useState(false);
207 const onToggleExpand = () => {
208 setIsExpanded(!isExpanded);
209 };
210
211 const myOnMouseEnter = (ev: React.MouseEvent<HTMLDivElement>) => {
212 setIsMouseOver(true);
213 setTimedOutAnimation(false);
214 onMouseEnter(ev);
215 };
216
217 const myOnMouseLeave = (ev: React.MouseEvent<HTMLDivElement>) => {
218 setIsMouseOver(false);
219 onMouseLeave(ev);
220 };
221
222 if (shouldDismiss && isDismissed) {
223 return null;
224 }
225 const Title = (
226 <TitleComponent
227 {...(isTooltipVisible && { tabIndex: 0 })}
228 ref={titleRef}
229 className={css(styles.alertTitle, truncateTitle && styles.modifiers.truncate)}
230 >
231 {getHeadingContent}
232 </TitleComponent>
233 );
234
235 return (
236 <div
237 ref={divRef}
238 className={css(
239 styles.alert,
240 isInline && styles.modifiers.inline,
241 isPlain && styles.modifiers.plain,
242 isExpandable && styles.modifiers.expandable,
243 isExpanded && styles.modifiers.expanded,
244 styles.modifiers[variant],
245 className
246 )}
247 {...ouiaProps}
248 {...(isLiveRegion && {
249 'aria-live': 'polite',
250 'aria-atomic': 'false'
251 })}
252 onMouseEnter={myOnMouseEnter}
253 onMouseLeave={myOnMouseLeave}
254 id={id}
255 {...props}
256 >
257 {isExpandable && (
258 <AlertContext.Provider value={{ title, variantLabel }}>
259 <div className={css(styles.alertToggle)}>
260 <AlertToggleExpandButton
261 isExpanded={isExpanded}
262 onToggleExpand={onToggleExpand}
263 aria-label={toggleAriaLabel}
264 />
265 </div>
266 </AlertContext.Provider>
267 )}
268 <AlertIcon variant={variant} customIcon={customIcon} />
269 {isTooltipVisible ? (
270 <Tooltip content={getHeadingContent} position={tooltipPosition}>
271 {Title}
272 </Tooltip>
273 ) : (
274 Title
275 )}
276 {actionClose && (
277 <AlertContext.Provider value={{ title, variantLabel }}>
278 <div className={css(styles.alertAction)}>{actionClose}</div>
279 </AlertContext.Provider>
280 )}
281 {children && (!isExpandable || (isExpandable && isExpanded)) && (
282 <div className={css(styles.alertDescription)}>{children}</div>
283 )}
284 {actionLinks && <div className={css(styles.alertActionGroup)}>{actionLinks}</div>}
285 </div>
286 );
287 };
288 Alert.displayName = 'Alert';