@bubbles-ui/notifications
Version:
The Bubbles Design System is Leemonade's open-source design system for products and experiences.
71 lines (70 loc) • 2.02 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.useNotifications = useNotifications;
exports.useNotificationsState = useNotificationsState;
var _react = require("react");
var _hooks = require("@mantine/hooks");
var _context = require("../context");
function useNotifications() {
let type = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _context.CONTEXT_TYPES.DEFAULT;
const context = (0, _react.useContext)(type === _context.CONTEXT_TYPES.DEFAULT ? _context.NotificationsContext : _context.ChatContext);
if (!context) {
throw new Error('NotificationsProvider was not found in tree');
}
return context;
}
function useNotificationsState(_ref) {
let {
limit
} = _ref;
const {
state,
queue,
update,
cleanQueue
} = (0, _hooks.useQueue)({
initialValues: [],
limit
});
const showNotification = notification => {
const id = notification.id || (0, _hooks.randomId)();
update(notifications => {
if (notification.id && notifications.some(n => n.id === notification.id)) {
return notifications;
}
return [...notifications, {
...notification,
id
}];
});
return id;
};
const updateNotification = (id, notification) => update(notifications => {
const index = notifications.findIndex(n => n.id === id);
if (index === -1) {
return notifications;
}
const newNotifications = [...notifications];
newNotifications[index] = notification;
return newNotifications;
});
const hideNotification = id => update(notifications => notifications.filter(notification => {
if (notification.id === id) {
typeof notification.onClose === 'function' && notification.onClose(notification);
return false;
}
return true;
}));
const clean = () => update(() => []);
return {
notifications: state,
queue,
showNotification,
updateNotification,
hideNotification,
cleanQueue,
clean
};
}