UNPKG

@dune2/mantine-notifications

Version:

Mantine notifications system

78 lines (75 loc) 2.43 kB
'use client'; import { randomId } from '@mantine/hooks'; import { createStore, useStore } from '@mantine/store'; const createNotificationsStore = () => createStore({ notifications: [], queue: [], limit: 5 }); const notificationsStore = createNotificationsStore(); const useNotifications = (t0) => { const store = t0 === void 0 ? notificationsStore : t0; return useStore(store); }; function updateNotificationsState(store, update) { const state = store.getState(); const notifications2 = update([...state.notifications, ...state.queue]); store.setState({ notifications: notifications2.slice(0, state.limit), queue: notifications2.slice(state.limit), limit: state.limit }); } function showNotification(notification, store = notificationsStore) { const id = notification.id || randomId(); updateNotificationsState(store, (notifications2) => { if (notification.id && notifications2.some((n) => n.id === notification.id)) { return notifications2; } return [...notifications2, { ...notification, id }]; }); return id; } function hideNotification(id, store = notificationsStore) { updateNotificationsState( store, (notifications2) => notifications2.filter((notification) => { if (notification.id === id) { notification.onClose?.(notification); return false; } return true; }) ); return id; } function updateNotification(notification, store = notificationsStore) { updateNotificationsState( store, (notifications2) => notifications2.map((item) => { if (item.id === notification.id) { return { ...item, ...notification }; } return item; }) ); return notification.id; } function cleanNotifications(store = notificationsStore) { updateNotificationsState(store, () => []); } function cleanNotificationsQueue(store = notificationsStore) { updateNotificationsState( store, (notifications2) => notifications2.slice(0, store.getState().limit) ); } const notifications = { show: showNotification, hide: hideNotification, update: updateNotification, clean: cleanNotifications, cleanQueue: cleanNotificationsQueue, updateState: updateNotificationsState }; export { cleanNotifications, cleanNotificationsQueue, createNotificationsStore, hideNotification, notifications, notificationsStore, showNotification, updateNotification, updateNotificationsState, useNotifications };