toast-message.js 2.2 KB

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