From 1293f4e52b4600cb9ddfde89adacc2363b477f3a Mon Sep 17 00:00:00 2001 From: "Carlos E. Feria Vila" Date: Tue, 27 Sep 2022 15:10:40 +0200 Subject: [PATCH] feat(notifications): add notifications (#41) --- src/context/NotificationContext.tsx | 87 +++++++++++++++++++++++++++++ src/context/index.ts | 1 + 2 files changed, 88 insertions(+) create mode 100644 src/context/NotificationContext.tsx diff --git a/src/context/NotificationContext.tsx b/src/context/NotificationContext.tsx new file mode 100644 index 0000000..974b2a0 --- /dev/null +++ b/src/context/NotificationContext.tsx @@ -0,0 +1,87 @@ +import * as React from 'react'; +import { Alert, AlertActionCloseButton, AlertGroup } from '@patternfly/react-core'; + +// Notifications + +export type notificationType = 'success' | 'info' | 'warning' | 'danger' | 'default'; + +export interface INotification { + title: string; + message: string | JSX.Element; + variant: notificationType; + key: string; + actionClose?: boolean; + timeout?: number | boolean; +} + +export const Notifications: React.FunctionComponent = () => { + const appContext = React.useContext(NotificationContext); + return ( + + {appContext.notifications.map((notification) => { + return ( + { + appContext.dismissNotification(notification.key); + }} + /> + ), + })} + timeout={notification.timeout} + > + {notification.message} + + ); + })} + + ); +}; + +// Context + +interface INotificationContext { + pushNotification: (notification: INotification) => void; + dismissNotification: (key: string) => void; + notifications: INotification[]; +} + +const appContextDefaultValue = {} as INotificationContext; +export const NotificationContext = + React.createContext(appContextDefaultValue); + +interface INotificationContextProvider { + children: React.ReactNode; +} + +export const NotificationContextProvider: React.FunctionComponent = ({ + children, +}: INotificationContextProvider) => { + const [notifications, setNotifications] = React.useState([]); + + const pushNotification = (notification: INotification) => { + setNotifications([...notifications, notification]); + }; + + const dismissNotification = (key: string) => { + const remainingNotifications = notifications.filter((n) => n.key !== key); + setNotifications(remainingNotifications); + }; + + return ( + + {children} + + ); +}; diff --git a/src/context/index.ts b/src/context/index.ts index ed287a8..bd5efc2 100644 --- a/src/context/index.ts +++ b/src/context/index.ts @@ -1 +1,2 @@ export * from "./ConfirmationContext"; +export * from "./NotificationContext";