UNPKG

dora-ui

Version:

A React.js Mobile UI Library

95 lines (81 loc) 2.24 kB
import React from 'react'; import ReactDOM from 'react-dom'; import ToastContent from './content'; import { TOAST_TYPES } from './config'; import { isBrowser } from '../utils'; // 容器节点 var container; // 当前正在展示的Toast类型 var currentToastType; // 是否存在正在展示的toast var isShowing = false; /** * 创建容器节点 */ var createContainer = function createContainer() { container = document.createElement('div'); container.className = 'dora-toast-container'; document.body.appendChild(container); }; /** * 销毁toast */ var destroy = function destroy(type, onClose) { if (container && (type === currentToastType || typeof type === 'undefined')) { ReactDOM.unmountComponentAtNode(container); } isShowing = false; typeof onClose === 'function' && onClose(); }; /** * 核心展示方法 * @param type toast类型 * @param content toast内容 * @param duration 持续时间 * @param onClose 关闭后回调方法 * @param mask 是否展示mask */ var show = function show(type, content, duration, onClose, mask) { if (!isBrowser || isShowing) return; isShowing = true; currentToastType = type; !container && createContainer(); ReactDOM.render(React.createElement(ToastContent, { container: container, type: type, content: content, mask: mask, duration: duration, onClose: function (_onClose) { function onClose() { return _onClose.apply(this, arguments); } onClose.toString = function () { return _onClose.toString(); }; return onClose; }(function () { destroy(currentToastType, onClose); }) }), container); }; /** * 生成固定类型toast方法 * @param type toast类型 */ var createFn = function createFn(type) { var fn = function fn(content, duration, onClose, mask) { show(type, content, duration, onClose, mask); }; return fn; }; var Toast = { useIcons: ToastContent.useIcons, success: createFn(TOAST_TYPES.SUCCESS), error: createFn(TOAST_TYPES.ERROR), info: createFn(TOAST_TYPES.INFO), loading: createFn(TOAST_TYPES.LOADING), loaded: function loaded() { destroy(TOAST_TYPES.LOADING); }, destroy: destroy }; export default Toast;