/** * Class to show toast messages. **/ module.exports = { maxMessages: 6 ,timeout: 10 /* Seconds */ ,_container: null ,_timeouts: null ,_topHeap: [] /** * Shows a normal toast message. * * @param {String} message The message text **/ ,showMessage: function (message) { this._showText (message, 'message'); } /** * Shows a warning toast message. * * @param {String} message The message text **/ ,showWarning: function (message) { this._showText (message, 'warning'); } /** * Shows an error toast message. * * @param {String} message The message text **/ ,showError: function (message) { this._showText (message, 'error'); } ,pushTop: function (top) { this._topHeap.push (top); this._refreshPosition (); } ,popTop: function () { var top = this._topHeap.pop (); this._refreshPosition (); return top; } ,_refreshPosition: function () { if (!this._container) return; var left; var heapLen = this._topHeap.length; if (heapLen > 0) { var top = this._topHeap[heapLen - 1]; var rect = top.getBoundingClientRect (); left = (rect.left + parseInt (rect.width / 2) - window.pageXOffset) +'px'; } else left = ''; this._container.style.left = left; } /** * Hides all currently displayed toast messages. **/ ,hide: function () { if (!this._container) return; if (this._timeouts) for (var i = 0; i < this._timeouts.length; i++) clearTimeout (this._timeouts[i]); this._timeouts = null; document.removeEventListener ('mousedown', this.hideHandler); Vn.Node.remove (this._container); this._container = null; this.nodes = []; } ,_createContainer: function () { if (!this._container) { var container = document.createElement ('div'); container.className = 'htk-toast'; document.body.appendChild (container); this.hideHandler = this.hide.bind (this); document.addEventListener ('mousedown', this.hideHandler); this._timeouts = []; this._container = container; } this._refreshPosition (); } ,_showText: function (message, className) { this._createContainer (); if (this._timeouts.length >= this.maxMessages) this._onMessageTimeout (); var toast = document.createElement ('div'); toast.className = className; toast.addEventListener ('mousedown', this._onMessageMouseDown); var textNode = document.createTextNode (message); toast.appendChild (textNode); this._container.appendChild (toast); var timeoutId = setTimeout (this._onMessageTimeout.bind (this), this.timeout * 1000); this._timeouts.push (timeoutId); setTimeout (this._onShowToastTimeout.bind (this, toast), 50); } ,_onShowToastTimeout: function (toast) { Vn.Node.addClass (toast, 'show'); } ,_onMessageTimeout: function () { if (!this._container) return; var nodes = this._container.childNodes; if (nodes.length > 0) { clearTimeout (this._timeouts.shift ()); Vn.Node.remove (nodes[0]); } if (nodes.length == 0) this.hide (); } ,_onMessageMouseDown: function (event) { event.stopPropagation (); } };