UNPKG

zarm-web

Version:
85 lines (72 loc) 2.42 kB
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } import React from 'react'; import ReactDOM from 'react-dom'; import Notification from './Notification'; const NOTIFICATION_GAP = 12; const notificationInstances = []; const now = Date.now(); let seed = 0; function getNotificationKey() { const key = `notification-${now}-${seed += 1}`; return key; } function NotificationInstance(props, theme) { const className = props.isMessage ? '.za-message' : '.za-notification'; const div = document.createElement('div'); document.body.appendChild(div); if (typeof props === 'string' || React.isValidElement(props)) { props = { message: props }; } if (theme) { props.theme = theme; } const { key } = props; const instances = document.querySelectorAll(className); const lastInstance = instances[instances.length - 1]; props.top = (lastInstance ? parseInt(lastInstance.style.top, 10) + lastInstance.offsetHeight : 0) + NOTIFICATION_GAP; function willUnMount(lastHeight, lastTop) { setTimeout(() => { ReactDOM.unmountComponentAtNode(div); document.body.removeChild(div); }); const instancesDom = document.querySelectorAll(className); Array.from(instancesDom).forEach(instance => { const instanceTop = parseInt(instance.style.top, 10); if (instanceTop > lastTop) { instance.style.top = `${instanceTop - lastHeight - NOTIFICATION_GAP}px`; } }); } function ref(instance) { if (instance) { instance.key = instance.key || key || getNotificationKey(); notificationInstances.push(instance); } } ReactDOM.render(React.createElement(Notification, _extends({}, props, { willUnMount: willUnMount, ref: ref })), div); } const api = { open(props) { NotificationInstance(props); }, remove(key) { notificationInstances.forEach(instance => { if (instance.key === key) { instance.onClose(); } }); } }; ['primary', 'danger', 'success', 'warning', 'loading'].forEach(theme => { api[theme] = (options = {}) => { NotificationInstance(options, theme); }; }); export default api;