-
Notifications
You must be signed in to change notification settings - Fork 0
/
popup.js
256 lines (213 loc) · 6.7 KB
/
popup.js
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
// Copyright 2016 José Varela
var $aLoadMore;
var $errorMessage;
var $gifsHomeWrapper;
var $gifWrapperTemplate;
var $historyTabTemplate;
let $historyGifsWrapper;
var $homeTemplate;
var pager = 0;
var term = '';
const initTerms = [
"cute", "shocked", "suprised", "angry", "hungry", "funny", "hilarious", "omg",
"wtf", "nigga", "insult", "offended", "no way", "psycho", "beauty", "love",
"peace", "hate", "evil", "metal", "dance", "scream", "hurry"
];
document.addEventListener('DOMContentLoaded', function () {
$('#f-search').on('submit', searchTerm.bind(null, {}));
$(window).on('scroll', debounce(loadMore, 500));
$('.open-tab').on('click', openTab);
$('#clear-history').on('click', clearHistory);
if (!window.localStorage.history) window.localStorage.history = '[]';
// document.oncontextmenu =
// document.body.oncontextmenu = function () { return false; }
$aLoadMore = $('a[name="#loadMore"]');
$errorMessage = $('#error-message');
$gifsHomeWrapper = $('.tab-home').find('.gifs-wrapper');
$gifWrapperTemplate = $($('#image-template').html());
$historyTabTemplate = $('.tab-history');
$historyGifsWrapper = $historyTabTemplate.find('.gifs-wrapper');
$homeTemplate = $($('.tab-home').html());
addExamplesToHome(6);
}, false);
function clearHistory(e) {
window.localStorage.history = '[]';
$historyGifsWrapper.html('');
}
function addExamplesToHome(totalExamples) {
var randNum = 0;
var randNums = [];
for(var i = 0; i < totalExamples; i++) {
do {
randNum = randInt(0, initTerms.length)
} while(randNums.indexOf(randNum) > -1);
randNums[i] = randNum;
searchTerm({ random: initTerms[randNums[i]] });
}
}
function searchTerm(opts, event) {
var qs = '';
var path = 'search';
var paramSearch = 'q';
for(var param in opts) {
switch (param) {
case 'random':
path = 'random';
paramSearch = 'tag';
break;
default:
qs = '&' + param + '=' + opts[param];
}
}
if (event) {
$errorMessage.html('');
$gifsHomeWrapper.html('');
term = (typeof(event) === 'string') ? event : event.currentTarget.term.value;
pager = 0;
//Show only first results
// $.get('http://www.reactiongifs.com/?s=' + term)
// .then( function(htmlRsp) {
// handleReactiongifApi(htmlRsp);
// })
// .catch(function () {
// $errorMessage.html('[Reactiongif] Service Unavailable');
// });
}
$('.spinner').show();
$.get(`http://api.giphy.com/v1/gifs/${path}?${paramSearch}=${term}${qs}&api_key=dc6zaTOxFJmzC`)
.then(handleGiffyApi)
.catch(function () {
pager = -1;
$errorMessage.html('[Giphy] Service Unavailable');
})
.always(function () {
$('.spinner').hide();
});
return false;
}
function handleReactiongifApi(htmlRsp) {
var $imgsReactiongif = $(htmlRsp).find('.entry img');
var imgsReactionGif = [];
$imgsReactiongif.each(function() {
imgsReactionGif.push(this.src);
});
imgsReactionGif.forEach(function (gifUrl) {
var $gifWrapper = $gifWrapperTemplate.clone();
var $gif = $gifWrapper.find('.gif');
$gif.attr('src', gifUrl);
$gifWrapper.on('click', handleGifClick);
$gifsHomeWrapper.append($gifWrapper);
});
}
function handleGiffyApi(jsonRsp) {
if (jsonRsp.data) {
if (jsonRsp.data.length == 0) {
pager = -1;
$errorMessage.html('Sorry. No results!');
return false;
}
const data = (jsonRsp.data instanceof Array) ? jsonRsp.data : [jsonRsp.data];
data.forEach((gif, index) => {
var gifUrl;
try {
gifUrl = gif.images.downsized_medium.url;
} catch (e) {
gifUrl = gif.fixed_width_downsampled_url;
}
var $gifWrapper = $gifWrapperTemplate.clone();
$gifWrapper.attr('data-key', pager++);
var $gif = $gifWrapper.find('.gif');
$gif.attr('src', gifUrl);
$gifWrapper.on('click', handleGifClick);
$gifsHomeWrapper.append($gifWrapper);
});
} else {
pager = -1;
$errorMessage.html('Can\'t handle the response');
}
};
function putGifsOnWrapper(gifUrl) {
var $gifWrapper = $gifWrapperTemplate.clone();
var $gif = $gifWrapper.find('.gif');
$gif.attr('src', gifUrl);
$gifWrapper.on('click', handleGifClick);
$gifsHomeWrapper.append($gifWrapper);
}
function handleGifClick(event) {
var $gif = $(event.currentTarget).find('.gif');
var $shareIcon = $(event.currentTarget).find('.share .icon');
var $shareMessage = $(event.currentTarget).find('.share .message');
var url = $gif.attr('src');
$('#clipboard').val('');
if (url) {
$('#clipboard').val(url);
$('#clipboard').select();
document.execCommand('copy');
$shareIcon.hide();
$shareMessage.fadeIn();
const history = JSON.parse(window.localStorage.history);
if (history.indexOf(url) === -1) history.push(url);
window.localStorage.history = JSON.stringify(history);
setTimeout(function () {
$shareMessage.hide();
$shareIcon.fadeIn();
}, 2000);
}
};
function loadMore() {
if ($(window).scrollTop() > $aLoadMore.offset().top) {
pager += 25;
if (pager > 0) {
searchTerm({ offset: pager }, undefined);
}
}
}
function debounce(func, wait, immediate) {
var timeout;
return function () {
var context = this;
var args = arguments;
var later = function () {
timeout = null;
if (!immediate) {
func.apply(context, args);
}
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
function randInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function openTab(e) {
tabName = $(e.currentTarget).data('tab');
if (tabName === 'history') buildHistoryTab(tabName);
$('.active-tab').hide();
$(`.tab-${tabName}`).addClass('active-tab').show();
}
function buildHistoryTab(tabName) {
const history = JSON.parse(window.localStorage.history);
if ($historyGifsWrapper.children().length === history.length)
return;
$historyGifsWrapper.html('');
history.reverse().forEach((gifUrl, idx) => {
const $gifWrapper = $gifWrapperTemplate.clone();
const $check = $gifWrapper.find('.remove');
$check.removeClass('hide');
const $gif = $gifWrapper.find('.gif');
$gif.attr('src', gifUrl);
$gifWrapper.find('.btn-remove').on('click', removeFromHistory.bind(this, gifUrl, $gifWrapper));
$gifWrapper.find('.image-wrapper').on('click', handleGifClick);
$historyGifsWrapper.append($gifWrapper);
});
return $historyTabTemplate;
}
function removeFromHistory(url, $toRemove, ev){
const history = JSON.parse(window.localStorage.history);
const indexToRemove = history.indexOf(url)
history.splice(url, 1);
$toRemove.remove();
}