-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathstackunderflow.js
More file actions
335 lines (323 loc) · 12.4 KB
/
stackunderflow.js
File metadata and controls
335 lines (323 loc) · 12.4 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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
(function() {
// some API urls
var google = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&callback={callback}&rsz=large&q={query}",
questions = "http://api.stackoverflow.com/1.0/questions/{id}?key={key}&body=true&jsonp={callback}",
questionsTagged = "http://api.stackoverflow.com/1.0/questions/?key={key}&tagged={tagged}&body=true&jsonp={callback}",
search = "http://api.stackoverflow.com/1.0/search/?key={key}&intitle={intitle}¬tagged={nottagged}&tagged={tagged}&body=true&jsonp={callback}",
unansweredQuestionsTagged = "http://api.stackoverflow.com/1.0/questions/unanswered/?key={key}&tagged={tagged}&body=true&jsonp={callback}",
questionsByUser = "http://api.stackoverflow.com/1.0/users/{id}/questions?key={key}&body=true&jsonp={callback}",
// prevent loading more than once
isLoaded,
// each call creates a unique jsonp callback
jsonpCount = 0,
// for matching the question id inside a stackexchange question url
regexQuestion = /\/questions\/([0-9]*)\//ig,
// those listening for the loaded event
callbacks = [];
function domLoaded() {
// based on the proven method of simulating DOMContentLoaded in IE
if (window.addEventListener) {
window.addEventListener("load", loaded, false);
}
else {
window.attachEvent("onload", loaded);
}
var check;
if (window.attachEvent) {
if ((window == window.top) && document.documentElement.doScroll) {
var timeout, er, el = document.createElement("div");
check = function() {
try {
el.doScroll("left");
}
catch (er) {
timeout = window.setTimeout(check, 0);
return;
}
el = null;
loaded();
}
check();
}
else {
document.onreadystatechange = function() {
if (/loaded|complete/.test(document.readyState)) {
loaded();
}
};
}
}
else if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", loaded, false);
}
}
function loaded() {
// called when the DOM is ready
if (!isLoaded) {
isLoaded = true;
for (var i = 0, l = callbacks.length; i < l; i++) {
callbacks[i]();
}
}
}
function jsonp(url, params, callback) {
// begin a jsonp request and foward the response
var jsonp = "_jsonp" + jsonpCount++;
url = url
.replace("{callback}", "stackunderflow." + jsonp)
.replace("{key}", su.appId);
if (params) {
for (var name in params) {
url = url.replace("{" + name + "}", params[name]);
}
}
su[jsonp] = function(data) {
delete su[jsonp];
su.loaded(function() {
callback(data);
});
};
var scr = document.createElement("script");
scr.type = "text/javascript";
scr.src = url;
// insertBefore in case this is performed inline in the head
var head = document.getElementsByTagName("head")[0];
head.insertBefore(scr, head.firstChild);
}
function getUniqueQuestions(searchResults) {
// created an array of unique question ids
// from a set of google search results
var questions = [], index = {};
for (var i = 0, l = searchResults.length; i < l; i++) {
regexQuestion.lastIndex = 0;
var url = searchResults[i].unescapedUrl,
match = regexQuestion.exec(url);
if ( match && match[1] ) {
var questionId = parseInt(match[1]);
if (!index[questionId]) {
questions.push(questionId);
index[questionId] = 1;
}
}
}
return questions;
}
function pad(num) {
var s = num+"";
return s.length === 2 ? s : ("0" + s);
}
function applyTemplate(html, obj) {
var i, l, regexTokens = new RegExp("\\{([^}]*)\\}", "g"), match, token,
tokenValues = {
site: su.site
};
do {
match = regexTokens.exec(html);
token = match ? match[1] : null;
if (token) {
var index = token.indexOf(":"),
filter = null;
if (index > -1) {
filter = token.substr(0, index);
token = token.substr(index + 1);
}
var parts = token === "=" ? [] : token.split('.'),
step = obj;
for (var i = 0, l = parts.length; i < l; i++) {
step = step[parts[i]];
if (typeof step === "undefined") break;
}
if (filter) {
var template;
if (filter.indexOf("template-") > -1) {
template = filter.substr("template-".length);
filter = "template";
}
filter = su.filters[filter];
if (filter) {
step = filter(step, template);
}
}
if (typeof step !== "undefined") {
tokenValues[match[1]] = step;
}
}
}
while (token);
for (token in tokenValues) {
html = html.replace(new RegExp("\\{" + token.replace(/([\.\:\-])/g, '\\$1') + "\\}","g"), tokenValues[token]);
}
return html;
}
function append(target, html) {
var div = document.createElement("div");
div.innerHTML = html;
while(div.firstChild) {
target.appendChild(div.firstChild);
}
}
function execQuestions(url, params, complete) {
var renderArgs,
ctx = { render: function() { renderArgs = arguments; } };
jsonp(url, params, function(questions) {
if (complete) complete(questions);
if (renderArgs) {
renderArgs = Array.prototype.slice.apply(renderArgs);
renderArgs.splice(0, 0, questions);
su.render.questions.apply(null, renderArgs);
}
});
return ctx;
}
var su = window.stackunderflow = {
appId: "oxXcnoD51kKE-crj7TadaA",
site: "http://stackoverflow.com",
loaded: function(callback) {
if (isLoaded) {
callback();
}
else {
callbacks.push(callback);
}
},
googleQuestions: function(term, complete) {
var renderArgs,
ctx = { render: function() { renderArgs = arguments; } };
var site = su.site + "/questions";
term = term || ('"' + window.location + '"');
jsonp(google, {
query: "site:" + site + " " + term
},
function(data) {
var questions = getUniqueQuestions(data.responseData.results);
if (questions.length) {
su.getQuestions(questions, function(questions) {
if (complete) complete(questions);
if (renderArgs) {
renderArgs = Array.prototype.slice.apply(renderArgs);
renderArgs.splice(0, 0, questions);
su.render.questions.apply(null, renderArgs);
}
});
}
});
return ctx;
},
getQuestions: function(questionIds, complete) {
return execQuestions(questions, { id: questionIds.join(';') }, complete);
},
searchQuestions: function(intitle, tagged, notTagged, complete) {
return execQuestions(search, { tagged: tagged, nottagged: notTagged, intitle: intitle }, complete);
},
getQuestionsWithTags: function(tags, onlyUnanswered, complete) {
return execQuestions(onlyUnanswered ? unansweredQuestionsTagged : questionsTagged,
{ tagged: tags }, complete);
},
getQuestionsByUser: function(userIds, complete) {
return execQuestions(questionsByUser, { id: userIds instanceof Array ? userIds.join(';') : userIds }, complete);
},
render: {
questions: function(questions, target, template) {
template = template || "question";
if (typeof target === "string") {
if (target.charAt(0) === "#") target = target.substr(1);
target = document.getElementById(target);
}
var html = "";
questions = questions.questions;
if (questions) {
for (var i = 0, l = questions.length; i < l; i++) {
html += applyTemplate(su.templates[template], questions[i]);
}
}
append(target, html);
}
},
templates: {
tag: '<a href="{site}/questions/tagged/{=}" class="se-post-tag" title="show questions tagged \'{=}\'" rel="tag">{=}</a> ',
question: '<div class="se-question-summary" id="question-summary-{question_id}"> \
<div onclick="window.location.href=\'{site}{question_answers_url}\'" class="se-cp se-statscontainer"> \
<div class="statsarrow"></div> \
<div class="se-stats"> \
<div class="se-vote"> \
<div class="se-votes"> \
<span class="se-mini-counts vote-count-post"><strong>{up_vote_count}</strong></span> \
<div class="viewcount">vote{pluralize:up_vote_count}</div> \
</div> \
</div> \
<div class="se-status {acceptedclass:=}"> \
<strong>{answer_count}</strong>answer{pluralize:answer_count} \
</div> \
</div> \
<div class="se-views {viewcountcolor:view_count}" title="{view_count}{viewcountk:view_count} view{pluralize:view_count}">{view_count} views</div> \
</div> \
<div class="se-summary"> \
<h3><a href="{site}{question_answers_url}" class="se-question-hyperlink" title="{title}">{title}</a></h3> \
<div class="excerpt"> {summarize:body} </div> \
<div class="se-tags"> {template-tag:tags} </div> \
<div class="se-started"> \
<div class="se-user-info"><div class="user-action-time">asked <span title="{date:last_activity_date}">{date:last_activity_date}</span></div> \
<div class="user-gravatar32"><a href="{site}/users/{owner.user_id}/{owner.display_name}"><div><img src="http://www.gravatar.com/avatar/{owner.email_hash}?s=32&d=identicon&r=PG" alt=""></div></a></div> \
<div class="se-user-details"><a style="display:{ifdef:owner}" href="{site}/users/{owner.user_id}/{owner.display_name}">{owner.display_name}</a> <br/> <span style="display:{ifdef:owner}" class="se-reputation-score" title="reputation score">{owner.reputation}</span></div> \
</div> \
</div> \
</div> \
</div> '
},
filters: {
date: function(value) {
var date = new Date(parseInt(value)*1000);
return date.getFullYear() + "-" + pad(date.getMonth()+1) + "-" + pad(date.getDate());
},
template: function(value, templateName) {
var template = su.templates[templateName],
html = "";
if (template) {
for (i = 0, l = value.length; i < l; i++) {
html += applyTemplate(template, value[i]);
}
}
return html;
},
acceptedclass: function(value) {
return value.accepted_answer_id ? "se-answered-accepted" :
(value.answer_count ? "se-answered" : "se-unanswered");
},
viewcountnumber: function(value) {
return value > 999 ? Math.round(value/1000) : value;
},
viewcountk: function(value) {
return value > 999 ? "k" : "";
},
summarize: function(value){
var max_desc = 220;
var strip_lines = /(\n|\r|<br>|<br\/>|<br \/>|<p>|<\/p>|<\/a>|<code>|<\/code>|<pre>|<\/pre>)/img;
var strip_links = /<a href="[^>]*>/img;
value = value.replace(strip_lines, " ");
value = value.replace(strip_links, " ");
if(value.length > max_desc){
return value.substr(0, max_desc);
}else{
return value;
}
},
pluralize: function(value){
return value == 1 || value == "1" ? "" : "s";
},
viewcountcolor: function(value) {
if(value >= 100000)
return "se-views-100k";
else if (value >= 10000)
return "se-views-10k";
else if (value >= 1000)
return "se-views-1k"
else
return "";
},
ifdef: function(value) {
return typeof value === "undefined" ? "none" : "";
}
}
};
domLoaded();
})();