|
| 1 | +import Ember from 'ember'; |
| 2 | + |
| 3 | +const { computed, isEmpty } = Ember; |
| 4 | + |
| 5 | +const IMAGE_HOST = 'https://images$x$.uhura.io'; |
| 6 | +const DEFAULT_IMAGE = '/assets/channel-placeholder.png'; |
| 7 | + |
| 8 | +export default Ember.Component.extend({ |
| 9 | + tagName: 'img', |
| 10 | + classNames: ['channel-img'], |
| 11 | + attributeBindings: 'src', |
| 12 | + imageURL: false, |
| 13 | + |
| 14 | + src: computed('imageURL', function() { |
| 15 | + return this.get('imageURL') || DEFAULT_IMAGE; |
| 16 | + }), |
| 17 | + |
| 18 | + didInsertElement() { |
| 19 | + const that = this; |
| 20 | + let image = new Image(); |
| 21 | + image.src = this.get('cachedImageSource'); |
| 22 | + image.onload = function() { |
| 23 | + if (typeof this.naturalWidth !== 'undefined' && this.naturalWidth !== 0) { |
| 24 | + Ember.run(() => { |
| 25 | + if (!that.get('isDestroyed')) { |
| 26 | + that.set('imageURL', this.src); |
| 27 | + } |
| 28 | + }); |
| 29 | + } |
| 30 | + }; |
| 31 | + }, |
| 32 | + |
| 33 | + cachedImageSource: computed('channel.imageURL', 'channel.image_url', function() { |
| 34 | + const imageURL = this.get('channel.imageURL') || this.get('channel.image_url'); |
| 35 | + |
| 36 | + if (isEmpty(imageURL)) { |
| 37 | + return DEFAULT_IMAGE; |
| 38 | + } |
| 39 | + |
| 40 | + const isCached = imageURL.indexOf('.uhura.io') !== -1; |
| 41 | + if (isCached) { |
| 42 | + return imageURL; |
| 43 | + } |
| 44 | + |
| 45 | + const hostIndex = Math.floor(Math.random() * (2 - 1 + 1)) + 1; |
| 46 | + const imageHost = IMAGE_HOST.replace('$x$', hostIndex); |
| 47 | + return `${imageHost}/resolve?url=${imageURL}`; |
| 48 | + }) |
| 49 | +}); |
0 commit comments