forked from up-for-grabs/up-for-grabs.net
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
351 lines (316 loc) · 9.95 KB
/
main.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
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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
// @ts-nocheck
/* eslint no-var: [ "error" ] */
define([
'jquery',
'projectLoader',
'projectsService',
'fetchIssueCount',
'underscore',
'sammy',
// this will auto-run and apply the event listeners for dark mode checks
'dark-mode',
// chosen is listed here as a dependency because it's used from a jQuery
// selector, and needs to be ready before this code runs
'chosen',
], (
$,
loadProjects,
ProjectsService,
fetchIssueCount,
_,
sammy,
setupDarkModeListener
) => {
let compiledtemplateFn = null,
projectsPanel = null;
setupDarkModeListener();
const getFilterUrl = function () {
return location.href.indexOf('/#/filters') > -1
? location.href
: `${location.href}filters`;
};
// inspired by https://stackoverflow.com/a/6109105/1363815 until I have a better
// idea of what we want to do here
function relativeTime(current, previous) {
const msPerMinute = 60 * 1000;
const msPerHour = msPerMinute * 60;
const msPerDay = msPerHour * 24;
const msPerMonth = msPerDay * 30;
const msPerYear = msPerDay * 365;
const elapsed = current - previous;
if (elapsed < msPerMinute) {
return `${Math.round(elapsed / 1000)} seconds ago`;
}
if (elapsed < msPerHour) {
return `${Math.round(elapsed / msPerMinute)} minutes ago`;
}
if (elapsed < msPerDay) {
return `${Math.round(elapsed / msPerHour)} hours ago`;
}
if (elapsed < msPerMonth) {
return `about ${Math.round(elapsed / msPerDay)} days ago`;
}
if (elapsed < msPerYear) {
return `about ${Math.round(elapsed / msPerMonth)} months ago`;
}
return `about ${Math.round(elapsed / msPerYear)} years ago`;
}
const renderProjects = function (projectService, tags, names, labels, date) {
const allTags = projectService.getTags();
projectsPanel.html(
compiledtemplateFn({
projects: projectService.get(tags, names, labels, date),
relativeTime,
tags: allTags,
popularTags: projectService.getPopularTags(6),
selectedTags: tags,
names: projectService.getNames(),
selectedNames: names,
labels: projectService.getLabels(),
selectedLabels: labels,
})
);
date = date || 'invalid';
projectsPanel
.find(`button.radio-btn[id=${date}]`)
.addClass('radio-btn-selected');
projectsPanel
.find('select.tags-filter')
.chosen({
no_results_text: 'No tags found by that name.',
width: '95%',
})
.val(tags)
.trigger('chosen:updated')
.change(function () {
location.href = updateQueryStringParameter(
getFilterUrl(),
'tags',
encodeURIComponent($(this).val() || '')
);
});
projectsPanel
.find('select.names-filter')
.chosen({
search_contains: true,
no_results_text: 'No project found by that name.',
width: '95%',
})
.val(names)
.trigger('chosen:updated')
.change(function () {
location.href = updateQueryStringParameter(
getFilterUrl(),
'names',
encodeURIComponent($(this).val() || '')
);
});
// Logic for checking/unchecking date-buttons
projectsPanel.find('button.radio-btn').each(function () {
$(this).click(function () {
let { id } = this;
const currentSelected = projectsPanel.find(
'button.radio-btn-selected'
)[0];
// Uncheck
if (currentSelected && currentSelected.id == id) {
id = '';
}
location.href = updateQueryStringParameter(
getFilterUrl(),
'date',
encodeURIComponent(id || '')
);
});
});
projectsPanel
.find('select.labels-filter')
.chosen({
no_results_text: 'No project found by that label.',
width: '95%',
})
.val(labels)
.trigger('chosen:updated')
.change(function () {
location.href = updateQueryStringParameter(
getFilterUrl(),
'labels',
encodeURIComponent($(this).val() || '')
);
});
projectsPanel.find('ul.popular-tags li a').each((i, elem) => {
$(elem).on('click', function () {
selTags = $('.tags-filter').val() || [];
selectedTag = preparePopTagName($(this).text() || '');
if (selectedTag) {
tagID = allTags
.map((tag) => tag.name.toLowerCase())
.indexOf(selectedTag);
if (tagID !== -1) {
selTags.push(selectedTag);
location.href = updateQueryStringParameter(
getFilterUrl(),
'tags',
encodeURIComponent(selTags)
);
}
}
});
});
};
/*
This is a utility method to help update a list items Name parameter to make
it fit URL specification
@return string - The value of the Name
*/
let preparePopTagName = function (name) {
if (name === '') return '';
return name.toLowerCase().split(' ')[0];
};
/**
* This is a utility method to help update URL Query Parameters
* @return string - The value of the URL when adding/removing values to it.
*/
let updateQueryStringParameter = function (uri, key, value) {
const re = new RegExp(`([?&])${key}=.*?(&|$)`, 'i');
const separator = uri.indexOf('?') !== -1 ? '&' : '?';
if (uri.match(re)) {
return uri.replace(re, `$1${key}=${value}$2`);
}
return `${uri + separator + key}=${value}`;
};
/**
* This function help getting all params in url queryString
* Taken from here
* https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript
*
* @return string - value of url params
*/
const getParameterByName = function (name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, '\\$&');
const regex = new RegExp(`[?&]${name}(=([^&#]*)|&|#|$)`),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, ' '));
};
/**
* This function adds a button to scroll to top
* after navigating through a certain screen length
* Also has corresponding fade-in and fade-out fetaure
*/
$(window).scroll(() => {
const height = $(window).scrollTop();
if (height > 100) {
$('#back2Top').fadeIn();
} else {
$('#back2Top').fadeOut();
}
});
$(document).ready(() => {
$('#back2Top').click((event) => {
event.preventDefault();
$('html, body').animate({ scrollTop: 0 }, 'slow');
return false;
});
});
/*
* This is a helper method that prepares the chosen labels/tags/names
* For HTML and helps display the selected values of each
* @params String text - The text given, indices or names. As long as it is a string
* @return Array - Returns an array of splitted values if given a text. Otherwise undefined
*/
const prepareForHTML = function (text) {
return text ? text.toLowerCase().split(',') : text;
};
const issueCount = function (project) {
const a = $(project).find('.label a');
const gh = a
.attr('href')
.match(/github.com(\/[^\/]+\/[^\/]+\/)(?:issues\/)?labels\/([^\/]+)$/);
let count = a.find('.count');
if (count.length) {
return;
}
if (!gh) {
count = $(
'<span class="count" title="Issue count is only available for projects on GitHub.">?</span>'
).appendTo(a);
return;
}
count = $(
'<span class="count"><img src="images/octocat-spinner-32.gif" /></span>'
).appendTo(a);
const ownerAndName = gh[1];
const labelEncoded = gh[2];
fetchIssueCount(ownerAndName, labelEncoded).then(
(resultCount) => {
count.html(resultCount);
},
(error) => {
const message = error.message ? error.message : error;
count.html('?!');
count.attr('title', message);
}
);
};
$(() => {
const $window = $(window),
onScreen = function onScreen($elem) {
const docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
return (
(docViewTop <= elemTop && elemTop <= docViewBottom) ||
(docViewTop <= elemBottom && elemBottom <= docViewBottom)
);
};
$window.on('scroll chosen:updated', () => {
$('.projects tbody:not(.counted)').each(function () {
const project = $(this);
if (onScreen(project)) {
issueCount(project);
project.addClass('counted');
}
});
});
compiledtemplateFn = _.template($('#projects-panel-template').html());
projectsPanel = $('#projects-panel');
projectsPanel.on('click', 'a.remove-tag', function (e) {
e.preventDefault();
const tags = [];
projectsPanel
.find('a.remove-tag')
.not(this)
.each(function () {
tags.push($(this).data('tag'));
});
const tagsString = tags.join(',');
window.location.href = `#/tags/${tagsString}`;
});
loadProjects().then((p) => {
const projectsSvc = new ProjectsService(p);
const app = sammy(function () {
/*
* This is the route used to filter by tags/names/labels
* It ensures to read values from the URI query param and perform actions
* based on that. NOTE: It has major side effects on the browser.
*/
this.get(/\#\/filters/, () => {
const labels = prepareForHTML(getParameterByName('labels'));
const names = prepareForHTML(getParameterByName('names'));
const tags = prepareForHTML(getParameterByName('tags'));
const date = getParameterByName('date');
renderProjects(projectsSvc, tags, names, labels, date);
});
this.get('/', () => {
renderProjects(projectsSvc);
});
});
app.raise_errors = true;
app.run('#/');
});
});
});