Created
October 19, 2021 15:36
-
-
Save Akiyamka/805a1c7372341f28cc461de89caa92fb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { createAtom } from '@reatom/core'; | |
export type NotificationType = 'error' | 'warning' | 'info'; | |
interface NotificationMessage { | |
title: string; | |
text?: string; | |
} | |
interface Notification { | |
id: number; | |
type: NotificationType; | |
message: NotificationMessage; | |
lifetimeSec: number; | |
onClose: () => void; | |
} | |
export const currentNotificationAtom = createAtom( | |
{ | |
showNotification: ( | |
type: NotificationType, | |
message: NotificationMessage, | |
lifetimeSec: number, | |
) => ({ type, message, lifetimeSec }), | |
removeNotification: (id: number) => id, | |
}, | |
({ onAction, schedule, create }, state: Notification[] = []) => { | |
onAction('showNotification', ({ type, message, lifetimeSec }) => { | |
const id = performance.now(); | |
const onClose= () => currentNotificationAtom.removeNotification.dispatch(id); | |
state = [...state, { id, type, message, lifetimeSec, onClose }]; | |
schedule((dispatch) => { | |
setTimeout(onClose, lifetimeSec * 1000); | |
}); | |
}); | |
onAction('removeNotification', (idForDelete) => state = state.filter(({ id }) => id !== idForDelete)); | |
return [ ...state ]; | |
}, | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment