forked from TryGhost/Ghost
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathunsplash.js
More file actions
263 lines (207 loc) · 7.7 KB
/
Copy pathunsplash.js
File metadata and controls
263 lines (207 loc) · 7.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
import Service, {inject as service} from '@ember/service';
import fetch from 'fetch';
import {assign} from '@ember/polyfills';
import {isEmpty} from '@ember/utils';
import {or} from '@ember/object/computed';
import {reject, resolve} from 'rsvp';
import {task, taskGroup, timeout} from 'ember-concurrency';
const API_URL = 'https://api.unsplash.com';
const API_VERSION = 'v1';
const DEBOUNCE_MS = 600;
export default Service.extend({
settings: service(),
columnCount: 3,
columns: null,
error: '',
photos: null,
searchTerm: '',
_columnHeights: null,
_pagination: null,
applicationId: '8672af113b0a8573edae3aa3713886265d9bb741d707f6c01a486cde8c278980',
isLoading: or('_search.isRunning', '_loadingTasks.isRunning'),
init() {
this._super(...arguments);
this._reset();
this.loadNew();
},
loadNew() {
this._reset();
return this._loadNew.perform();
},
loadNextPage() {
// protect against scroll trigger firing when the photos are reset
if (this.get('_search.isRunning')) {
return;
}
if (isEmpty(this.photos)) {
return this._loadNew.perform();
}
if (this._pagination.next) {
return this._loadNextPage.perform();
}
// TODO: return error?
return reject();
},
updateSearch(term) {
if (term === this.searchTerm) {
return;
}
this.set('searchTerm', term);
this._reset();
if (term) {
return this._search.perform(term);
} else {
return this._loadNew.perform();
}
},
retryLastRequest() {
return this._retryLastRequest.perform();
},
changeColumnCount(newColumnCount) {
if (newColumnCount !== this.columnCount) {
this.set('columnCount', newColumnCount);
this._resetColumns();
}
},
// let Unsplash know that the photo was inserted
// https://medium.com/unsplash/unsplash-api-guidelines-triggering-a-download-c39b24e99e02
triggerDownload(photo) {
if (photo.links.download_location) {
this._makeRequest(photo.links.download_location, {ignoreErrors: true});
}
},
actions: {
updateSearch(term) {
return this.updateSearch(term);
}
},
_loadingTasks: taskGroup().drop(),
_loadNew: task(function* () {
let url = `${API_URL}/photos?per_page=30`;
yield this._makeRequest(url);
}).group('_loadingTasks'),
_loadNextPage: task(function* () {
yield this._makeRequest(this._pagination.next);
}).group('_loadingTasks'),
_retryLastRequest: task(function* () {
yield this._makeRequest(this._lastRequestUrl);
}).group('_loadingTasks'),
_search: task(function* (term) {
yield timeout(DEBOUNCE_MS);
let url = `${API_URL}/search/photos?query=${term}&per_page=30`;
yield this._makeRequest(url, {searchTermAtRequest: term});
}).restartable(),
_addPhotosFromResponse(response, searchTermAtRequest) {
// If a search term was provided at the time of the request,
// we only want to add photos if the search term matches the current one.
if (searchTermAtRequest && searchTermAtRequest !== this.searchTerm) {
return;
}
let photos = response.results || response;
photos.forEach(photo => this._addPhoto(photo));
},
_addPhoto(photo) {
// pre-calculate ratio for later use
photo.ratio = photo.height / photo.width;
// add to general photo list
this.photos.pushObject(photo);
// add to least populated column
this._addPhotoToColumns(photo);
},
_addPhotoToColumns(photo) {
let min = Math.min(...this._columnHeights);
let columnIndex = this._columnHeights.indexOf(min);
// use a fixed width when calculating height to compensate for different
// overall image sizes
this._columnHeights[columnIndex] += 300 * photo.ratio;
this.columns[columnIndex].pushObject(photo);
},
_reset() {
this.set('photos', []);
this._pagination = {};
this._resetColumns();
},
_resetColumns() {
let columns = [];
let columnHeights = [];
// pre-fill column arrays based on columnCount
for (let i = 0; i < this.columnCount; i += 1) {
columns[i] = [];
columnHeights[i] = 0;
}
this.set('columns', columns);
this._columnHeights = columnHeights;
if (!isEmpty(this.photos)) {
this.photos.forEach((photo) => {
this._addPhotoToColumns(photo);
});
}
},
_makeRequest(url, _options = {}) {
let defaultOptions = {ignoreErrors: false};
let headers = {};
let options = {};
assign(options, defaultOptions, _options);
// clear any previous error
this.set('error', '');
// store the url so it can be retried if needed
this._lastRequestUrl = url;
headers.Authorization = `Client-ID ${this.applicationId}`;
headers['Accept-Version'] = API_VERSION;
headers['App-Pragma'] = 'no-cache';
headers['X-Unsplash-Cache'] = true;
return fetch(url, {headers})
.then(response => this._checkStatus(response))
.then(response => this._extractPagination(response, options.searchTermAtRequest))
.then(response => response.json())
.then(response => this._addPhotosFromResponse(response, options.searchTermAtRequest))
.catch(() => {
// if the error text isn't already set then we've get a connection error from `fetch`
if (!options.ignoreErrors && !this.error) {
this.set('error', 'Uh-oh! Trouble reaching the Unsplash API, please check your connection');
}
});
},
_checkStatus(response) {
// successful request
if (response.status >= 200 && response.status < 300) {
return resolve(response);
}
let errorText = '';
let responseTextPromise = resolve();
if (response.headers.map['content-type'] === 'application/json') {
responseTextPromise = response.json().then(json => json.errors[0]);
} else if (response.headers.map['content-type'] === 'text/xml') {
responseTextPromise = response.text();
}
return responseTextPromise.then((responseText) => {
if (response.status === 403 && response.headers.map['x-ratelimit-remaining'] === '0') {
// we've hit the ratelimit on the API
errorText = 'Unsplash API rate limit reached, please try again later.';
}
errorText = errorText || responseText || `Error ${response.status}: Uh-oh! Trouble reaching the Unsplash API`;
// set error text for display in UI
this.set('error', errorText);
// throw error to prevent further processing
let error = new Error(errorText);
error.response = response;
throw error;
});
},
_extractPagination(response, searchTermAtRequest) {
if (searchTermAtRequest && searchTermAtRequest !== this.searchTerm) {
return response;
}
let pagination = {};
let linkRegex = new RegExp('<(.*)>; rel="(.*)"');
let {link: links} = response.headers.map;
if (links) {
links.split(',').forEach((link) => {
let [, url, rel] = linkRegex.exec(link);
pagination[rel] = url;
});
}
this._pagination = pagination;
return response;
}
});