UNPKG

apeman-react-mixins

Version:
107 lines (88 loc) 1.94 kB
/** * Mixin to handle toast. * @mixin ApToastMixin */ 'use strict' import React, {PropTypes as types} from 'react' const TOAST_TOASTER_KEY = "_apToastToaster"; /** @lends ApToastMixin */ const ApToastMixin = { // -------------------- // Custom // -------------------- $apToastMixed: true, /** * Get current toast messages. * @returns {object} - Messages object. */ getToaster () { const s = this let toaster = s[ TOAST_TOASTER_KEY ] || s.context[ TOAST_TOASTER_KEY ] if (!toaster) { let msg = "Toaster no initialized. You need to call `.registerToaster()` on this component or one of it's parents" throw new Error(msg) } return toaster }, /** * Set toast message. * @param {string} message - Message to set * @param {string} [level="default"] - Level of message. */ toast (message, level) { const s = this let toaster = s.getToaster() level = level || 'default' toaster.emit('toast', { level: level, message: message }) }, /** * Set info toast message */ infoToast (message) { const s = this s.toast(message, 'info') }, /** * Set warn toast message */ warnToast (message) { const s = this s.toast(message, 'warn') }, /** * Set error toast message */ errorToast (message) { const s = this s.toast(message, 'error') }, /** * Decorate toast context. */ registerToaster (toaster) { const s = this s[ TOAST_TOASTER_KEY ] = toaster }, // -------------------- // Specs // -------------------- contextTypes: { [TOAST_TOASTER_KEY]: types.object }, childContextTypes: { [TOAST_TOASTER_KEY]: types.object }, getChildContext () { const s = this return { [TOAST_TOASTER_KEY]: s.getToaster() } } // -------------------- // Lifecycle // -------------------- } export default Object.freeze(ApToastMixin)