piral-notifications
Version:
Plugin for triggering notifications in Piral.
79 lines • 2.82 kB
JavaScript
import * as actions from './actions';
import { isValidElement } from 'react';
import { withApi, defaultRender, withAll, withRootExtension, } from 'piral-core';
import { DefaultHost, DefaultToast } from './default';
import { Notifications } from './Notifications';
function isElement(element) {
return isValidElement(element);
}
function toComponent(component) {
if (typeof component === 'string') {
const text = component;
return () => defaultRender(text);
}
else if (isValidElement(component)) {
const element = component;
return () => element;
}
return component;
}
function createNotification(context, id, content, defaultOptions, customOptions = {}) {
const options = {
...defaultOptions,
...customOptions,
};
const notification = {
id,
component: toComponent(content),
options,
close() {
setTimeout(() => context.closeNotification(notification), 0);
},
};
if (typeof options.autoClose === 'number' && options.autoClose > 0) {
setTimeout(notification.close, options.autoClose);
}
return notification;
}
function getNotifications(context, messages, defaultOptions) {
const notifications = [];
let i = 0;
for (const { content, options } of messages) {
notifications.push(createNotification(context, `global-${i++}`, content, defaultOptions, options));
}
return notifications;
}
function withNotifications(notifications) {
return (state) => ({
...state,
components: {
NotificationsHost: DefaultHost,
NotificationsToast: DefaultToast,
...state.components,
},
notifications,
});
}
/**
* Creates new Pilet API extensions for showing notifications.
*/
export function createNotificationsApi(config = {}) {
const { defaultOptions = {}, selectId = () => `${~~(Math.random() * 10000)}`, messages = [] } = config;
return (context) => {
context.defineActions(actions);
context.dispatch(withAll(withNotifications(getNotifications(context, messages, defaultOptions)), withRootExtension('piral-notifications', Notifications)));
return (api) => ({
showNotification(content, customOptions) {
const Component = typeof content === 'string'
? content
: isElement(content)
? content
: withApi(context, content, api, 'extension');
const notification = createNotification(context, selectId(), Component, defaultOptions, customOptions);
context.openNotification(notification);
return notification.close;
},
});
};
}
//# sourceMappingURL=create.js.map