-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Expand file tree
/
Copy pathmain.js
More file actions
472 lines (422 loc) · 13.9 KB
/
main.js
File metadata and controls
472 lines (422 loc) · 13.9 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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
// @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;
// Pagination constants
const PROJECTS_PER_PAGE = 15;
let currentPage = 1;
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();
const allFilteredProjects = projectService.get(tags, names, labels, date);
const totalProjects = allFilteredProjects.length;
const totalPages = Math.ceil(totalProjects / PROJECTS_PER_PAGE);
if (currentPage > totalPages) currentPage = 1;
// Slice projects to current page only
const pagedProjects = allFilteredProjects.slice(
(currentPage - 1) * PROJECTS_PER_PAGE,
currentPage * PROJECTS_PER_PAGE
);
projectsPanel.html(
compiledtemplateFn({
projects: pagedProjects, // [MODIFIED] was: 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 () {
currentPage = 1;
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 () {
currentPage = 1;
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 = '';
}
currentPage = 1;
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 () {
currentPage = 1;
location.href = updateQueryStringParameter(
getFilterUrl(),
'labels',
encodeURIComponent($(this).val() || '')
);
});
/*
Adds popular tags to the tag search query when a popular tag element is clicked.
*/
projectsPanel.find('ul.popular-tags li a').each((i, elem) => {
$(elem).on('click', function () {
let selTags = $('.tags-filter').val() || [];
let selectedTag = preparePopTagName($(this).text() || '');
if (selectedTag) {
let tagID = allTags
.map((tag) => tag.name.toLowerCase())
.indexOf(selectedTag);
if (tagID !== -1) {
selTags.push(selectedTag);
currentPage = 1;
location.href = updateQueryStringParameter(
getFilterUrl(),
'tags',
encodeURIComponent(selTags)
);
}
}
});
});
// Render pagination controls
const paginationEl = projectsPanel.find('#pagination-controls');
paginationEl.empty();
if (totalPages > 1) {
if (currentPage > 1) {
paginationEl.append(
`<button class="radio-btn pagination-btn" id="prev-page">← Prev</button>`
);
}
for (let i = 1; i <= totalPages; i++) {
if (
i === 1 ||
i === totalPages ||
(i >= currentPage - 1 && i <= currentPage + 1)
) {
paginationEl.append(
`<button class="radio-btn pagination-btn ${i === currentPage ? 'radio-btn-selected' : ''}" data-page="${i}">${i}</button>`
);
} else if (i === currentPage - 2 || i === currentPage + 2) {
paginationEl.append(
`<span class="pagination-ellipsis">…</span>`
);
}
}
if (currentPage < totalPages) {
paginationEl.append(
`<button class="radio-btn pagination-btn" id="next-page">Next →</button>`
);
}
paginationEl.append(
`<div class="pagination-goto">
<input
type="number"
id="goto-page-input"
class="pagination-goto-input"
min="1"
max="${totalPages}"
placeholder="Enter page number"
aria-label="Go to page"
/>
<button class="radio-btn pagination-btn" id="goto-page-btn">Go</button>
</div>`
);
paginationEl.find('#prev-page').on('click', () => {
currentPage -= 1;
renderProjects(projectService, tags, names, labels, date);
document
.querySelector('.projects')
.scrollIntoView({ behavior: 'smooth' });
});
paginationEl.find('#next-page').on('click', () => {
currentPage += 1;
renderProjects(projectService, tags, names, labels, date);
document
.querySelector('.projects')
.scrollIntoView({ behavior: 'smooth' });
});
paginationEl.find('.pagination-btn[data-page]').on('click', function () {
currentPage = parseInt($(this).data('page'));
renderProjects(projectService, tags, names, labels, date);
document
.querySelector('.projects')
.scrollIntoView({ behavior: 'smooth' });
});
paginationEl.find('#goto-page-btn').on('click', () => {
const val = parseInt(paginationEl.find('#goto-page-input').val());
if (!isNaN(val) && val >= 1 && val <= totalPages) {
currentPage = val;
renderProjects(projectService, tags, names, labels, date);
document
.querySelector('.projects')
.scrollIntoView({ behavior: 'smooth' });
}
});
paginationEl.find('#goto-page-input').on('keydown', function (e) {
if (e.key === 'Enter') {
paginationEl.find('#goto-page-btn').trigger('click');
}
});
}
};
/*
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 feature
*/
$(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 split 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.get('/beta/', (context, next) => {
const scheme = window.location.protocol;
const host = window.location.host;
const path = `${scheme}//${host}/beta/`;
window.location.href = path;
});
/*
* 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('#/');
});
});
});