Skip to content

Commit

Permalink
feat(notifications): add notifications (#41)
Browse files Browse the repository at this point in the history
  • Loading branch information
carlosthe19916 authored Sep 27, 2022
1 parent 4be16a5 commit 1293f4e
Show file tree
Hide file tree
Showing 2 changed files with 88 additions and 0 deletions.
87 changes: 87 additions & 0 deletions src/context/NotificationContext.tsx
Original file line number Diff line number Diff line change
@@ -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 (
<AlertGroup isToast aria-live="polite">
{appContext.notifications.map((notification) => {
return (
<Alert
title={notification.title}
variant={notification.variant}
key={notification.key}
{...(notification.actionClose && {
actionClose: (
<AlertActionCloseButton
onClose={() => {
appContext.dismissNotification(notification.key);
}}
/>
),
})}
timeout={notification.timeout}
>
{notification.message}
</Alert>
);
})}
</AlertGroup>
);
};

// Context

interface INotificationContext {
pushNotification: (notification: INotification) => void;
dismissNotification: (key: string) => void;
notifications: INotification[];
}

const appContextDefaultValue = {} as INotificationContext;
export const NotificationContext =
React.createContext<INotificationContext>(appContextDefaultValue);

interface INotificationContextProvider {
children: React.ReactNode;
}

export const NotificationContextProvider: React.FunctionComponent<INotificationContextProvider> = ({
children,
}: INotificationContextProvider) => {
const [notifications, setNotifications] = React.useState<INotification[]>([]);

const pushNotification = (notification: INotification) => {
setNotifications([...notifications, notification]);
};

const dismissNotification = (key: string) => {
const remainingNotifications = notifications.filter((n) => n.key !== key);
setNotifications(remainingNotifications);
};

return (
<NotificationContext.Provider
value={{
pushNotification,
dismissNotification,
notifications,
}}
>
{children}
</NotificationContext.Provider>
);
};
1 change: 1 addition & 0 deletions src/context/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export * from "./ConfirmationContext";
export * from "./NotificationContext";

0 comments on commit 1293f4e

Please sign in to comment.