Debian Codegraph @

node/@patternfly/react-core/src/demos/examples/AlertGroup/AlertGroupToastWithNotificationDrawer.tsx

raw
1 import { useEffect, useState } from 'react';
2 import {
3 Button,
4 EmptyState,
5 EmptyStateBody,
6 NotificationBadge,
7 NotificationBadgeVariant,
8 NotificationDrawer,
9 NotificationDrawerBody,
10 NotificationDrawerHeader,
11 NotificationDrawerList,
12 NotificationDrawerListItem,
13 NotificationDrawerListItemBody,
14 NotificationDrawerListItemHeader,
15 PageSection,
16 Content,
17 EmptyStateVariant,
18 NumberInput,
19 Alert,
20 AlertProps,
21 AlertGroup,
22 AlertActionCloseButton,
23 ToolbarItem,
24 Dropdown,
25 DropdownList,
26 DropdownItem,
27 MenuToggle,
28 MenuToggleElement
29 } from '@patternfly/react-core';
30 import SearchIcon from '@patternfly/react-icons/dist/js/icons/search-icon';
31 import RhUiEllipsisVerticalFillIcon from '@patternfly/react-icons/dist/esm/icons/rh-ui-ellipsis-vertical-fill-icon';
32 import { DashboardHeader } from '@patternfly/react-core/dist/js/demos/DashboardHeader';
33 import { DashboardWrapper } from '@patternfly/react-core/dist/js/demos/DashboardWrapper';
34
35 interface NotificationProps {
36 title: string;
37 srTitle: string;
38 variant: 'custom' | 'success' | 'danger' | 'warning' | 'info';
39 key: React.Key;
40 timestamp: string;
41 description: string;
42 isNotificationRead: boolean;
43 }
44
45 export const AlertGroupToastWithNotificationDrawer: React.FunctionComponent = () => {
46 const maxDisplayedAlerts = 3;
47 const minAlerts = 0;
48 const maxAlerts = 100;
49 const alertTimeout = 8000;
50
51 const [isDrawerExpanded, setDrawerExpanded] = useState(false);
52 const [openDropdownKey, setOpenDropdownKey] = useState<React.Key | null>(null);
53 const [overflowMessage, setOverflowMessage] = useState<string>('');
54 const [maxDisplayed, setMaxDisplayed] = useState(maxDisplayedAlerts);
55 const [alerts, setAlerts] = useState<React.ReactElement<AlertProps>[]>([]);
56 const [notifications, setNotifications] = useState<NotificationProps[]>([]);
57
58 useEffect(() => {
59 setOverflowMessage(buildOverflowMessage());
60 }, [maxDisplayed, notifications, alerts]);
61
62 const addNewNotification = (variant: NotificationProps['variant']) => {
63 const variantFormatted = variant.charAt(0).toUpperCase() + variant.slice(1);
64 const title = variantFormatted + ' alert notification';
65 const srTitle = variantFormatted + ' alert';
66 const description = variantFormatted + ' alert notification description';
67 const key = getUniqueId();
68 const timestamp = getTimeCreated();
69
70 setNotifications((prevNotifications) => [
71 { title, srTitle, variant, key, timestamp, description, isNotificationRead: false },
72 ...prevNotifications
73 ]);
74
75 if (!isDrawerExpanded) {
76 setAlerts((prevAlerts) => [
77 <Alert
78 variant={variant}
79 title={title}
80 timeout={alertTimeout}
81 onTimeout={() => removeAlert(key)}
82 isLiveRegion
83 actionClose={
84 <AlertActionCloseButton title={title} variantLabel={`${variant} alert`} onClose={() => removeAlert(key)} />
85 }
86 key={key}
87 id={key.toString()}
88 >
89 <p>{description}</p>
90 </Alert>,
91 ...prevAlerts
92 ]);
93 }
94 };
95
96 const removeNotification = (key: React.Key) => {
97 setNotifications((prevNotifications) => prevNotifications.filter((notification) => notification.key !== key));
98 };
99
100 const removeAllNotifications = () => {
101 setNotifications([]);
102 };
103
104 const isNotificationRead = (key: React.Key) =>
105 notifications.find((notification) => notification.key === key)?.isNotificationRead;
106
107 const markNotificationRead = (key: React.Key) => {
108 setNotifications((prevNotifications) =>
109 prevNotifications.map((notification) =>
110 notification.key === key ? { ...notification, isNotificationRead: true } : notification
111 )
112 );
113 };
114
115 const markAllNotificationsRead = () => {
116 setNotifications((prevNotifications) =>
117 prevNotifications.map((notification) => ({ ...notification, isNotificationRead: true }))
118 );
119 };
120
121 const getUnreadNotificationsNumber = () =>
122 notifications.filter((notification) => notification.isNotificationRead === false).length;
123
124 const containsUnreadAlertNotification = () =>
125 notifications.filter(
126 (notification) => notification.isNotificationRead === false && notification.variant === 'danger'
127 ).length > 0;
128
129 const getNotificationBadgeVariant = () => {
130 if (getUnreadNotificationsNumber() === 0) {
131 return NotificationBadgeVariant.read;
132 }
133 if (containsUnreadAlertNotification()) {
134 return NotificationBadgeVariant.attention;
135 }
136 return NotificationBadgeVariant.unread;
137 };
138
139 const onNotificationBadgeClick = () => {
140 removeAllAlerts();
141 setDrawerExpanded(!isDrawerExpanded);
142 };
143
144 const onDropdownToggle = (id: React.Key) => {
145 if (id && openDropdownKey !== id) {
146 setOpenDropdownKey(id);
147 return;
148 }
149 setOpenDropdownKey(null);
150 };
151
152 const onDropdownSelect = () => {
153 setOpenDropdownKey(null);
154 };
155
156 const buildOverflowMessage = () => {
157 const overflow = alerts.length - maxDisplayed;
158 if (overflow > 0 && maxDisplayed > 0) {
159 return `View ${overflow} more notification(s) in notification drawer`;
160 }
161 return '';
162 };
163
164 const getUniqueId = () => new Date().getTime();
165
166 const getTimeCreated = () => {
167 const dateCreated = new Date();
168 return (
169 dateCreated.toDateString() +
170 ' at ' +
171 ('00' + dateCreated.getHours().toString()).slice(-2) +
172 ':' +
173 ('00' + dateCreated.getMinutes().toString()).slice(-2)
174 );
175 };
176
177 const removeAlert = (key: React.Key) => {
178 setAlerts((prevAlerts) => prevAlerts.filter((alert) => alert.props.id !== key.toString()));
179 };
180
181 const removeAllAlerts = () => {
182 setAlerts([]);
183 };
184
185 const onAlertGroupOverflowClick = () => {
186 removeAllAlerts();
187 setDrawerExpanded(true);
188 };
189
190 const onMaxDisplayedAlertsMinus = () => {
191 setMaxDisplayed(normalizeAlertsNumber(maxDisplayed - 1));
192 };
193
194 const onMaxDisplayedAlertsChange = (event: any) => {
195 setMaxDisplayed(normalizeAlertsNumber(Number(event.target.value)));
196 };
197
198 const onMaxDisplayedAlertsPlus = () => {
199 setMaxDisplayed(normalizeAlertsNumber(maxDisplayed + 1));
200 };
201
202 const normalizeAlertsNumber = (value: number) => Math.max(Math.min(value, maxAlerts), minAlerts);
203
204 const alertButtonStyle = { marginRight: '8px', marginTop: '8px' };
205
206 const notificationBadge = (
207 <ToolbarItem>
208 <NotificationBadge
209 variant={getNotificationBadgeVariant()}
210 onClick={onNotificationBadgeClick}
211 aria-label="Notifications"
212 ></NotificationBadge>
213 </ToolbarItem>
214 );
215
216 const notificationDrawerActions = (
217 <>
218 <DropdownItem key="markAllRead" onClick={markAllNotificationsRead}>
219 Mark all read
220 </DropdownItem>
221 <DropdownItem key="clearAll" onClick={removeAllNotifications}>
222 Clear all
223 </DropdownItem>
224 </>
225 );
226 const notificationDrawerDropdownItems = (key: React.Key) => [
227 <DropdownItem key={`markRead-${key}`} onClick={() => markNotificationRead(key)}>
228 Mark as read
229 </DropdownItem>,
230 <DropdownItem key={`clear-${key}`} onClick={() => removeNotification(key)}>
231 Clear
232 </DropdownItem>
233 ];
234
235 const notificationDrawer = (
236 <NotificationDrawer>
237 <NotificationDrawerHeader count={getUnreadNotificationsNumber()} onClose={(_event) => setDrawerExpanded(false)}>
238 <Dropdown
239 id="notification-drawer-0"
240 isOpen={openDropdownKey === 'dropdown-toggle-id-0'}
241 onSelect={onDropdownSelect}
242 popperProps={{ position: 'right' }}
243 onOpenChange={(isOpen: boolean) => !isOpen && setOpenDropdownKey(null)}
244 toggle={(toggleRef: React.Ref<MenuToggleElement>) => (
245 <MenuToggle
246 ref={toggleRef}
247 isExpanded={openDropdownKey === 'dropdown-toggle-id-0'}
248 variant="plain"
249 onClick={() => onDropdownToggle('dropdown-toggle-id-0')}
250 aria-label="Notification drawer actions"
251 icon={<RhUiEllipsisVerticalFillIcon />}
252 />
253 )}
254 >
255 <DropdownList>{notificationDrawerActions}</DropdownList>
256 </Dropdown>
257 </NotificationDrawerHeader>
258 <NotificationDrawerBody>
259 {notifications.length !== 0 && (
260 <NotificationDrawerList>
261 {notifications.map(({ key, variant, title, srTitle, description, timestamp }, index) => (
262 <NotificationDrawerListItem
263 key={key}
264 variant={variant}
265 isRead={isNotificationRead(key)}
266 onClick={() => markNotificationRead(key)}
267 >
268 <NotificationDrawerListItemHeader variant={variant} title={title} srTitle={srTitle}>
269 <Dropdown
270 id={key.toString()}
271 isOpen={openDropdownKey === key}
272 onSelect={onDropdownSelect}
273 popperProps={{ position: 'right' }}
274 onOpenChange={(isOpen: boolean) => !isOpen && setOpenDropdownKey(null)}
275 toggle={(toggleRef: React.Ref<MenuToggleElement>) => (
276 <MenuToggle
277 ref={toggleRef}
278 isExpanded={openDropdownKey === key}
279 variant="plain"
280 onClick={() => onDropdownToggle(key)}
281 aria-label={`Notification ${index + 1} actions`}
282 icon={<RhUiEllipsisVerticalFillIcon />}
283 />
284 )}
285 >
286 <DropdownList>{notificationDrawerDropdownItems(key)}</DropdownList>
287 </Dropdown>
288 </NotificationDrawerListItemHeader>
289 <NotificationDrawerListItemBody timestamp={timestamp}> {description} </NotificationDrawerListItemBody>
290 </NotificationDrawerListItem>
291 ))}
292 </NotificationDrawerList>
293 )}
294 {notifications.length === 0 && (
295 <EmptyState
296 headingLevel="h2"
297 titleText="No notifications found"
298 icon={SearchIcon}
299 variant={EmptyStateVariant.full}
300 >
301 <EmptyStateBody>There are currently no notifications.</EmptyStateBody>
302 </EmptyState>
303 )}
304 </NotificationDrawerBody>
305 </NotificationDrawer>
306 );
307
308 return (
309 <DashboardWrapper
310 masthead={<DashboardHeader notificationBadge={notificationBadge} />}
311 mainContainerId="main-content-page-layout-default-nav"
312 notificationDrawer={notificationDrawer}
313 isNotificationDrawerExpanded={isDrawerExpanded}
314 >
315 <PageSection aria-labelledby="alert-group-title">
316 <Content>
317 <h1 id="alert-group-title">Alert group with notification drawer demo</h1>
318 <p>
319 New alerts can be added with the following buttons. Each alert has a timeout of 7 seconds, however, even
320 after the timeout expires, all alerts are still visible in the notification drawer. By default, only 3
321 alerts are displayed. The rest can be accessed in the notification drawer after clicking on the bell icon in
322 the header or by clicking on the overflow message.
323 </p>
324 </Content>
325 </PageSection>
326
327 <PageSection aria-label="Alert Buttons">
328 <Button variant="secondary" onClick={() => addNewNotification('success')} style={alertButtonStyle}>
329 Add toast success alert
330 </Button>
331 <Button variant="secondary" onClick={() => addNewNotification('danger')} style={alertButtonStyle}>
332 Add toast danger alert
333 </Button>
334 <Button variant="secondary" onClick={() => addNewNotification('info')} style={alertButtonStyle}>
335 Add toast info alert
336 </Button>
337 <br />
338 <br />
339 <Button variant="secondary" onClick={() => addNewNotification('warning')} style={alertButtonStyle}>
340 Add toast warning alert
341 </Button>
342 <Button variant="secondary" onClick={() => addNewNotification('custom')} style={alertButtonStyle}>
343 Add toast custom alert
344 </Button>
345 </PageSection>
346
347 <PageSection aria-labelledby="max-displayed-alerts-title">
348 <Content>
349 <br />
350 <h2 id="max-displayed-alerts-title">Max displayed alerts</h2>
351 <p>Adjust the maximum number of displayed alerts.</p>
352 </Content>
353 <NumberInput
354 value={maxDisplayed}
355 min={minAlerts}
356 max={maxAlerts}
357 onMinus={onMaxDisplayedAlertsMinus}
358 onChange={onMaxDisplayedAlertsChange}
359 onPlus={onMaxDisplayedAlertsPlus}
360 inputName="input"
361 inputAriaLabel="max displayed alerts number input"
362 minusBtnAriaLabel="minus"
363 plusBtnAriaLabel="plus"
364 style={{ margin: '12px 0' }}
365 />
366 </PageSection>
367 <PageSection component="div">
368 <AlertGroup
369 hasAnimations
370 isToast
371 isLiveRegion
372 onOverflowClick={onAlertGroupOverflowClick}
373 overflowMessage={overflowMessage}
374 >
375 {alerts.slice(0, maxDisplayed)}
376 </AlertGroup>
377 </PageSection>
378 </DashboardWrapper>
379 );
380 };