toast-message.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import Ember from 'ember';
  2. import ENV from '../config/environment';
  3. export default Ember.Service.extend({
  4. id: null,
  5. type: null,
  6. message: null,
  7. isVisible: false,
  8. isInfo: Ember.computed.equal('type', 'info'),
  9. isSuccess: Ember.computed.equal('type', 'success'),
  10. isWarning: Ember.computed.equal('type', 'warning'),
  11. isError: Ember.computed.equal('type', 'error'),
  12. _showToast: function(type, message) {
  13. var toastId = this.incrementProperty('id');
  14. this.set('type', type);
  15. this.set('message', message);
  16. this.set('isVisible', true);
  17. var displayTime = ENV.APP.TOAST_BASE_DISPLAY_TIME;
  18. displayTime += message.length * ENV.APP.TOAST_LENGTH_FACTOR;
  19. var self = this;
  20. Ember.run.later(function () {
  21. if (self.get('id') === toastId) {
  22. self.set('isVisible', false);
  23. }
  24. }, displayTime);
  25. },
  26. _setToast: function(type, message) {
  27. var self = this;
  28. if (this.get('isVisible')) {
  29. this.set('isVisible', false);
  30. Ember.run.later(function () {
  31. self._showToast(type, message);
  32. }, ENV.APP.TOAST_HIDE_ANIMATION_LENGTH);
  33. } else {
  34. this._showToast(type, message);
  35. }
  36. },
  37. // Public api
  38. info: function(message) {
  39. this._setToast('info', message);
  40. },
  41. success: function(message) {
  42. this._setToast('success', message);
  43. },
  44. warning: function(message) {
  45. this._setToast('warning', message);
  46. },
  47. error: function(message) {
  48. this._setToast('error', message);
  49. },
  50. apiError: function(reason) {
  51. reason = Ember.Object.create(reason);
  52. var errorMessage = gettext('Unknown error has occured.');
  53. if (reason.get('status') === 0) {
  54. errorMessage = gettext('Lost connection with application.');
  55. }
  56. if (reason.get('status') === 403) {
  57. errorMessage = reason.get('responseJSON.detail');
  58. if (errorMessage === 'Permission denied') {
  59. errorMessage = gettext("You don't have permission to perform this action.");
  60. }
  61. }
  62. if (reason.get('status') === 404) {
  63. errorMessage = gettext('Action link is invalid.');
  64. }
  65. this.error(errorMessage);
  66. }
  67. });