UNPKG

chowa

Version:

UI component library based on React

94 lines (93 loc) 3.45 kB
/** * @license chowa v1.1.3 * * Copyright (c) Chowa Techonlogies Co.,Ltd.(http://www.chowa.cn). * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const React = require("react"); const ReactDom = require("react-dom"); const classnames_1 = require("classnames"); const utils_1 = require("../utils"); const notification_1 = require("./notification"); const overlay_1 = require("../overlay"); class NotificationInstance extends React.PureComponent { constructor(props) { super(props); this.state = { topLeft: [], topRight: [], bottomLeft: [], bottomRight: [] }; } add(props) { const instacePlacement = this.getPlacement(props.placement); this.setState({ [instacePlacement]: this.state[instacePlacement].concat(props) }); } remove(index, placement) { const instacePlacement = this.getPlacement(placement); const componentsProps = [].concat(this.state[instacePlacement]); const arrIndex = componentsProps.findIndex((item) => item.key === index); componentsProps.splice(arrIndex, 1); this.setState({ [instacePlacement]: componentsProps }); } getPlacement(placement) { switch (placement) { case 'top-left': return 'topLeft'; case 'bottom-left': return 'bottomLeft'; case 'bottom-right': return 'bottomRight'; default: return 'topRight'; } } render() { const { topLeft, topRight, bottomLeft, bottomRight } = this.state; const nodes = []; [topLeft, topRight, bottomLeft, bottomRight].forEach((components, key) => { if (components.length > 0) { const { placement } = components[0]; const zIndex = overlay_1.default.getZIndex(); const wrapperClass = classnames_1.default({ [utils_1.preClass('notification-wrapper')]: true, [utils_1.preClass(`notification-wrapper-${placement || 'top-right'}`)]: true }); nodes.push(React.createElement("div", { className: wrapperClass, style: { zIndex }, key: key }, components.map((props) => { return (React.createElement(notification_1.default, Object.assign({}, props, { key: props.key, index: props.key }))); }))); } }); return nodes; } } let instance = null; let instanceKey = 0; function getInstance() { if (instance === null) { const rootEle = document.createElement('div'); document.body.appendChild(rootEle); ReactDom.render(React.createElement(NotificationInstance, { ref: (component) => instance = component }), rootEle); } instanceKey++; return instance; } function $notification(props) { const ins = getInstance(); ins.add(Object.assign(Object.assign({}, props), { key: instanceKey, onHide(index, placement) { ins.remove(index, placement); if (typeof props === 'object' && utils_1.hasProperty(props, 'onHide')) { props.onHide(index, placement); } } })); } exports.default = $notification;