-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtenor.js
123 lines (97 loc) · 3.6 KB
/
tenor.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
var tenor = (function () {
var apiKey = '';
var getAnonIdUrl = "https://api.tenor.com/v1/anonid?key=" + apiKey;
var lastAnonId;
var limit = 24;
var last_position = 0;
var locale = 'en_US' // todo: auto-detect
var tenorViewModel = new function () {
var self = this;
self.gifs = ko.observableArray().extend( {rateLimit : 50 });
self.currentSearchTerm = ko.observable().extend({ rateLimit: 500 });
self.messages = ko.observableArray();
self.isLoading = ko.observable(false);
self.errorMessage = ko.observable();
self.search = function () {
last_position = 0;
self.gifs.removeAll();
if(self.currentSearchTerm()) {
GetIdAndThenGetGifs();
}
};
self.getMore = function () {
GetIdAndThenGetGifs();
};
self.checkIfBottom = function (data, event) {
var element = event.target;
if ($(element).scrollTop() + $(element).innerHeight() >= element.scrollHeight) {
self.getMore();
}
};
self.addToMessageList = function(element){
self.messages.push(element);
};
self.handleMouseUp = function(data,event){
var container = $("#gif-list");
if (!container.is(event.target) && container.has(event.target).length === 0)
{
container.hide();
}
};
// todo: detect when the component is hidden and dispose subscrition
var subscriptionToInputChange = self.currentSearchTerm.subscribe(function (data) {
if( !data ) {
self.gifs.removeAll();
return;
}
self.search();
});
function GetIdAndThenGetGifs() {
self.errorMessage("");
if (lastAnonId != undefined) {
getGifs();
return;
}
$.get(getAnonIdUrl).done(function (data) {
if(!data.anon_id) {
console.log(data.error);
self.errorMessage(data.error);
return;
}
lastAnonId = data.anon_id;
getGifs();
})
.fail(requestFailedHandler)
.always( function(){self.isLoading(false)});
};
function getGifs() {
var search_url = "https://api.tenor.com/v1/search?tag=" + self.currentSearchTerm()
+ "&key=" + apiKey
+ "&limit=" + limit
+ "&pos=" + last_position
+ "&locale=" + locale
+ "&anon_id=" + lastAnonId;
self.isLoading(true);
$.get(search_url).done(function (data) {
if(!data.results) {
self.errorMessage(data.error);
return;
}
data.results.forEach(element => {
self.gifs.push(element);
});
last_position = last_position + limit;
})
.fail(requestFailedHandler)
.always(function(){ self.isLoading(false)});
}
function requestFailedHandler(jqXHR, textStatus, errorThrown) {
console.log('Sorry.An error ocurred on the request:' + textStatus);
console.log(errorThrown);
self.errorMessage(errorThrown);
}
};
return {
tenorViewModel: tenorViewModel
}
})();