toast-message.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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.setProperties({
  15. 'type': type,
  16. 'message': message,
  17. 'isVisible': true
  18. });
  19. var displayTime = ENV.APP.TOAST_BASE_DISPLAY_TIME;
  20. displayTime += message.length * ENV.APP.TOAST_LENGTH_FACTOR;
  21. var self = this;
  22. Ember.run.later(function () {
  23. if (self.get('id') === toastId) {
  24. self.set('isVisible', false);
  25. }
  26. }, displayTime);
  27. },
  28. _setToast: function(type, message) {
  29. var self = this;
  30. if (this.get('isVisible')) {
  31. this.set('isVisible', false);
  32. Ember.run.later(function () {
  33. self._showToast(type, message);
  34. }, ENV.APP.TOAST_HIDE_ANIMATION_LENGTH);
  35. } else {
  36. this._showToast(type, message);
  37. }
  38. },
  39. // Public api
  40. info: function(message) {
  41. this._setToast('info', message);
  42. },
  43. success: function(message) {
  44. this._setToast('success', message);
  45. },
  46. warning: function(message) {
  47. this._setToast('warning', message);
  48. },
  49. error: function(message) {
  50. this._setToast('error', message);
  51. },
  52. apiError: function(reason) {
  53. reason = Ember.Object.create(reason);
  54. var errorMessage = gettext('Unknown error has occured.');
  55. if (reason.get('status') === 0) {
  56. errorMessage = gettext('Lost connection with application.');
  57. }
  58. if (reason.get('status') === 403) {
  59. errorMessage = reason.get('responseJSON.detail');
  60. if (errorMessage === 'Permission denied') {
  61. errorMessage = gettext("You don't have permission to perform this action.");
  62. }
  63. }
  64. if (reason.get('status') === 404) {
  65. errorMessage = gettext('Action link is invalid.');
  66. }
  67. this.error(errorMessage);
  68. }
  69. });