-
-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathscript.js
More file actions
562 lines (507 loc) · 19.5 KB
/
Copy pathscript.js
File metadata and controls
562 lines (507 loc) · 19.5 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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
/**
* GitHub Faces - Developer Discovery Tool
* Client-side filtering and sorting functionality
*
* @author Seyyed Ali Mohammadiyeh
* @repository https://github.com/john-bampton/faces
* @license MIT
* @version 1.0.0
*
* Description:
* Provides dynamic filtering, searching, and sorting capabilities for discovering
* GitHub developers based on followers, repositories, forks, sponsors, and more.
*
* Features:
* - Real-time search across name, login, and location
* - Multi-range filtering (followers, repos, forks)
* - Sponsor and sponsoring filters
* - Avatar age-based filtering
* - Dynamic sorting options
* - Responsive card rendering
* - Mobile-optimized filter panel
*
* Dependencies:
* - HTML DOM with elements: searchInput, sortBy, filter dropdowns, grid, counts, messages
* - Card elements with data attributes: data-followers, data-repos, data-forks, data-avatar-updated
*
* Usage:
* Initialize with: document.addEventListener('DOMContentLoaded', initializeApp)
* All filtering happens automatically via event listeners on filter controls.
*/
let allUsers = [];
let filteredUsers = [];
let darkModeToggleElement = null;
// Dark mode constants
const DARK_MODE_KEY = 'darkMode';
const THEME_ENABLED = 'enabled';
const THEME_DISABLED = 'disabled';
// ============================================================================
// INITIALIZATION
// ============================================================================
document.addEventListener('DOMContentLoaded', initializeApp);
/**
* Initialize the application on page load
*/
function initializeApp() {
initializeDarkMode();
const cards = document.querySelectorAll('.card');
showLoadingState();
document.getElementById('totalCount').textContent = cards.length.toLocaleString();
document.getElementById('totalCountDesktop').textContent = cards.length.toLocaleString();
cards.forEach(card => allUsers.push(parseUserCard(card)));
filteredUsers = [...allUsers];
setupEventListeners();
applyFilters();
updateVisibilityAndSort();
hideLoadingState();
}
/**
* Parse user data from a card element
* @param {HTMLElement} card - The card element to parse
* @returns {Object} User object with extracted data
*/
function parseUserCard(card) {
const name = card.querySelector('strong').textContent.toLowerCase();
const login = card.querySelector('span:nth-of-type(2)').textContent.toLowerCase();
const location = extractLocation(card);
const followers = parseInt(card.getAttribute('data-followers') || '0');
const following = parseInt(card.getAttribute('data-following') || '0');
const repos = parseInt(card.getAttribute('data-repos') || '0');
const forks = parseInt(card.getAttribute('data-forks') || '0');
const { sponsors, sponsoring } = extractStats(card);
const avatarUpdated = card.getAttribute('data-avatar-updated') || '';
return { card, name, login, location, followers, following, repos, forks, sponsors, sponsoring, avatarUpdated };
}
/**
* Extract location emoji and text from card
* @param {HTMLElement} card - The card element
* @returns {string} Location text in lowercase
*/
function extractLocation(card) {
const spans = card.querySelectorAll('span');
for (let span of spans) {
if (span.textContent.includes('🌐')) {
return span.textContent.toLowerCase();
}
}
return '';
}
/**
* Extract sponsors and sponsoring counts from stats
* @param {HTMLElement} card - The card element
* @returns {Object} Object with sponsors and sponsoring counts
*/
function extractStats(card) {
let sponsors = 0;
let sponsoring = 0;
const statSpans = card.querySelectorAll('.stat a, .stat');
statSpans.forEach(stat => {
const label = stat.nextElementSibling;
if (label && label.classList.contains('stat-label')) {
const text = stat.textContent.trim();
const value = text === 'N/A' ? 0 : parseInt(text.replace(/,/g, ''));
if (label.textContent === 'Public Sponsors') sponsors = value;
if (label.textContent === 'Sponsoring') sponsoring = value;
}
});
return { sponsors, sponsoring };
}
// ============================================================================
// EVENT LISTENER SETUP
// ============================================================================
/**
* Setup all event listeners for filter controls
*/
function setupEventListeners() {
const filterIds = [
'searchInput', 'sortBy', 'followersFilter', 'maxFollowersFilter',
'minReposFilter', 'maxReposFilter', 'minForksFilter', 'maxForksFilter',
'sponsorsFilter', 'sponsoringFilter', 'avatarAgeFilter'
];
filterIds.forEach(id => {
const element = document.getElementById(id);
if (element) {
const eventType = id === 'searchInput' ? 'input' : 'change';
element.addEventListener(eventType, onFilterChange);
}
});
}
/**
* Handle any filter change event
*/
function onFilterChange() {
showLoadingState();
applyFilters();
updateVisibilityAndSort();
hideLoadingState();
}
/**
* Toggle the mobile filters panel
*/
function toggleFiltersPanel() {
const filtersAside = document.getElementById('filtersAside');
filtersAside.classList.toggle('open');
document.body.classList.toggle('filters-open');
}
// ============================================================================
// FILTER LOGIC
// ============================================================================
/**
* Apply all active filters to the user list
*/
function applyFilters() {
const filters = getActiveFilters();
validateRangeFilters(filters);
const dateRanges = getDateRanges();
filteredUsers = allUsers.filter(user => {
return matchesAllFilters(user, filters, dateRanges);
});
}
/**
* Get all active filter values from DOM
* @returns {Object} Active filter values
*/
function getActiveFilters() {
return {
searchTerm: document.getElementById('searchInput').value.toLowerCase(),
minFollowers: parseInt(document.getElementById('followersFilter').value),
maxFollowers: parseInt(document.getElementById('maxFollowersFilter').value),
minRepos: parseInt(document.getElementById('minReposFilter').value),
maxRepos: parseInt(document.getElementById('maxReposFilter').value),
minForks: parseInt(document.getElementById('minForksFilter').value),
maxForks: parseInt(document.getElementById('maxForksFilter').value),
sponsorsFilter: document.getElementById('sponsorsFilter').value,
sponsoringFilter: document.getElementById('sponsoringFilter').value,
avatarAgeFilter: document.getElementById('avatarAgeFilter').value
};
}
/**
* Validate and fix inverted min/max filters
* @param {Object} filters - The filters object
*/
function validateRangeFilters(filters) {
if (filters.minFollowers > filters.maxFollowers) {
document.getElementById('maxFollowersFilter').value = '999999999';
filters.maxFollowers = 999999999;
}
if (filters.minRepos > filters.maxRepos) {
document.getElementById('maxReposFilter').value = '999999';
filters.maxRepos = 999999;
}
if (filters.minForks > filters.maxForks) {
document.getElementById('maxForksFilter').value = '999999';
filters.maxForks = 999999;
}
}
/**
* Get date range objects for avatar age filtering
* @returns {Object} Date range objects
*/
function getDateRanges() {
const now = new Date();
return {
oneWeekAgo: new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000),
oneMonthAgo: new Date(now.getFullYear(), now.getMonth() - 1, now.getDate()),
sixMonthsAgo: new Date(now.getFullYear(), now.getMonth() - 6, now.getDate()),
oneYearAgo: new Date(now.getFullYear() - 1, now.getMonth(), now.getDate()),
twoYearsAgo: new Date(now.getFullYear() - 2, now.getMonth(), now.getDate()),
fiveYearsAgo: new Date(now.getFullYear() - 5, now.getMonth(), now.getDate())
};
}
/**
* Check if a user matches all active filters
* @param {Object} user - User object
* @param {Object} filters - Active filters
* @param {Object} dateRanges - Date range objects
* @returns {boolean} True if user matches all filters
*/
function matchesAllFilters(user, filters, dateRanges) {
return matchesSearch(user, filters.searchTerm) &&
matchesFollowerRange(user, filters) &&
matchesRepoRange(user, filters) &&
matchesForkRange(user, filters) &&
matchesPublicSponsors(user, filters.sponsorsFilter) &&
matchesSponsoring(user, filters.sponsoringFilter) &&
matchesAvatarAge(user, filters.avatarAgeFilter, dateRanges);
}
/**
* Check if user matches search term
* @param {Object} user - User object
* @param {string} searchTerm - Search term
* @returns {boolean} True if matches
*/
function matchesSearch(user, searchTerm) {
if (!searchTerm) return true;
return user.name.includes(searchTerm) ||
user.login.includes(searchTerm) ||
user.location.includes(searchTerm);
}
/**
* Check if user matches follower range
* @param {Object} user - User object
* @param {Object} filters - Filters object
* @returns {boolean} True if within range
*/
function matchesFollowerRange(user, filters) {
return user.followers >= filters.minFollowers && user.followers <= filters.maxFollowers;
}
/**
* Check if user matches repository range
* @param {Object} user - User object
* @param {Object} filters - Filters object
* @returns {boolean} True if within range
*/
function matchesRepoRange(user, filters) {
return user.repos >= filters.minRepos && user.repos <= filters.maxRepos;
}
/**
* Check if user matches forks range
* @param {Object} user - User object
* @param {Object} filters - Filters object
* @returns {boolean} True if within range
*/
function matchesForkRange(user, filters) {
return user.forks >= filters.minForks && user.forks <= filters.maxForks;
}
/**
* Check if user matches sponsors filter
* @param {Object} user - User object
* @param {string} sponsorsFilter - Public Sponsors filter value
* @returns {boolean} True if matches
*/
function matchesPublicSponsors(user, sponsorsFilter) {
if (sponsorsFilter === 'any') return true;
if (sponsorsFilter === 'has-sponsors') return user.sponsors > 0;
if (sponsorsFilter.startsWith('min-')) {
const minPublicSponsors = parseInt(sponsorsFilter.split('-')[1]);
return user.sponsors >= minPublicSponsors;
}
return true;
}
/**
* Check if user matches sponsoring filter
* @param {Object} user - User object
* @param {string} sponsoringFilter - Sponsoring filter value
* @returns {boolean} True if matches
*/
function matchesSponsoring(user, sponsoringFilter) {
if (sponsoringFilter === 'any') return true;
if (sponsoringFilter === 'is-sponsoring') return user.sponsoring > 0;
if (sponsoringFilter.startsWith('min-')) {
const minSponsoring = parseInt(sponsoringFilter.split('-')[1]);
return user.sponsoring >= minSponsoring;
}
return true;
}
/**
* Check if user matches avatar age filter
* @param {Object} user - User object
* @param {string} ageFilter - Avatar age filter value
* @param {Object} dateRanges - Date range objects
* @returns {boolean} True if matches
*/
function matchesAvatarAge(user, ageFilter, dateRanges) {
if (ageFilter === 'any' || !user.avatarUpdated) return true;
const avatarDate = new Date(user.avatarUpdated);
const ranges = {
'week': avatarDate >= dateRanges.oneWeekAgo,
'month': avatarDate >= dateRanges.oneMonthAgo,
'6months': avatarDate >= dateRanges.sixMonthsAgo,
'year': avatarDate >= dateRanges.oneYearAgo,
'2years': avatarDate >= dateRanges.twoYearsAgo,
'5years': avatarDate >= dateRanges.fiveYearsAgo,
'old': avatarDate < dateRanges.fiveYearsAgo
};
return ranges[ageFilter] !== undefined ? ranges[ageFilter] : true;
}
// ============================================================================
// SORTING AND VISIBILITY
// ============================================================================
/**
* Update visibility and sort the user cards
*/
function updateVisibilityAndSort() {
const sortBy = document.getElementById('sortBy').value;
const sortedUsers = getSortedUsers(sortBy);
renderCards(sortedUsers);
updateCounts(sortedUsers);
updateResultsMessage(sortedUsers);
}
/**
* Get sorted copy of filtered users
* @param {string} sortBy - Sort option
* @returns {Array} Sorted users array
*/
function getSortedUsers(sortBy) {
const sorted = [...filteredUsers];
const sorters = {
'followers-desc': (a, b) => b.followers - a.followers,
'followers-asc': (a, b) => a.followers - b.followers,
'following-desc': (a, b) => b.following - a.following,
'following-asc': (a, b) => a.following - b.following,
'repos-desc': (a, b) => b.repos - a.repos,
'repos-asc': (a, b) => a.repos - b.repos,
'forks-desc': (a, b) => b.forks - a.forks,
'forks-asc': (a, b) => a.forks - b.forks,
'sponsors-desc': (a, b) => b.sponsors - a.sponsors,
'sponsors-asc': (a, b) => a.sponsors - b.sponsors,
'sponsoring-desc': (a, b) => b.sponsoring - a.sponsoring,
'sponsoring-asc': (a, b) => a.sponsoring - b.sponsoring,
'name-asc': (a, b) => a.name.localeCompare(b.name),
'name-desc': (a, b) => b.name.localeCompare(a.name),
'ratio-followers-following': (a, b) => {
const ratioA = a.following > 0 ? a.followers / a.following : a.followers;
const ratioB = b.following > 0 ? b.followers / b.following : b.followers;
return ratioB - ratioA;
}
};
if (sorters[sortBy]) {
sorted.sort(sorters[sortBy]);
}
return sorted;
}
/**
* Render cards in DOM with sorted order
* @param {Array} sortedUsers - Sorted users array
*/
function renderCards(sortedUsers) {
const grid = document.getElementById('grid');
allUsers.forEach(user => user.card.classList.remove('visible'));
sortedUsers.forEach(user => {
user.card.classList.add('visible');
grid.appendChild(user.card);
});
}
/**
* Update visible and total counts
* @param {Array} sortedUsers - Sorted users array
*/
function updateCounts(sortedUsers) {
const visibleCount = sortedUsers.length;
const totalCount = allUsers.length;
document.getElementById('visibleCount').textContent = visibleCount.toLocaleString();
document.getElementById('totalCount').textContent = totalCount.toLocaleString();
document.getElementById('visibleCountDesktop').textContent = visibleCount.toLocaleString();
document.getElementById('totalCountDesktop').textContent = totalCount.toLocaleString();
}
/**
* Update results found/no results message
* @param {Array} sortedUsers - Sorted users array
*/
function updateResultsMessage(sortedUsers) {
const visibleCount = sortedUsers.length;
const totalCount = allUsers.length;
const resultsFound = document.getElementById('resultsFound');
const noResults = document.getElementById('noResults');
const resultsFoundDesktop = document.getElementById('resultsFoundDesktop');
const noResultsDesktop = document.getElementById('noResultsDesktop');
if (visibleCount === 0) {
if (resultsFound) resultsFound.style.display = 'none';
if (noResults) noResults.style.display = 'block';
if (resultsFoundDesktop) resultsFoundDesktop.style.display = 'none';
if (noResultsDesktop) noResultsDesktop.style.display = 'block';
} else if (visibleCount === totalCount) {
if (resultsFound) resultsFound.style.display = 'none';
if (noResults) noResults.style.display = 'none';
if (resultsFoundDesktop) resultsFoundDesktop.style.display = 'none';
if (noResultsDesktop) noResultsDesktop.style.display = 'none';
} else {
if (resultsFound) resultsFound.style.display = 'block';
if (noResults) noResults.style.display = 'none';
if (resultsFoundDesktop) resultsFoundDesktop.style.display = 'block';
if (noResultsDesktop) noResultsDesktop.style.display = 'none';
}
}
// ============================================================================
// RESET FILTERS
// ============================================================================
/**
* Reset all filters to default values
*/
function resetFilters() {
const defaults = {
searchInput: '',
sortBy: 'followers-desc',
followersFilter: '0',
maxFollowersFilter: '999999999',
minReposFilter: '0',
maxReposFilter: '999999',
minForksFilter: '0',
maxForksFilter: '999999',
sponsorsFilter: 'any',
sponsoringFilter: 'any',
avatarAgeFilter: 'any'
};
Object.entries(defaults).forEach(([id, value]) => {
const element = document.getElementById(id);
if (element) element.value = value;
});
applyFilters();
updateVisibilityAndSort();
}
// ============================================================================
// LOADING STATE
// ============================================================================
/**
* Show loading spinner
*/
function showLoadingState() {
const loadingState = document.getElementById('loadingState');
const loadingStateDesktop = document.getElementById('loadingStateDesktop');
const resultsInfo = document.getElementById('resultsInfo');
const resultsInfoDesktop = document.getElementById('resultsInfoDesktop');
if (loadingState) loadingState.style.display = 'block';
if (loadingStateDesktop) loadingStateDesktop.style.display = 'block';
if (resultsInfo) resultsInfo.style.display = 'none';
if (resultsInfoDesktop) resultsInfoDesktop.style.display = 'none';
}
/**
* Hide loading spinner
*/
function hideLoadingState() {
const loadingState = document.getElementById('loadingState');
const loadingStateDesktop = document.getElementById('loadingStateDesktop');
if (loadingState) loadingState.style.display = 'none';
if (loadingStateDesktop) loadingStateDesktop.style.display = 'none';
}
// ============================================================================
// DARK MODE TOGGLE
// ============================================================================
/**
* Initialize dark mode functionality
* - Load saved preference from localStorage
* - Set up toggle button listener
* - Apply dark mode class if preference is set
* - Cache DOM element for performance
*/
function initializeDarkMode() {
darkModeToggleElement = document.getElementById('darkModeToggle');
const isDarkMode = localStorage.getItem(DARK_MODE_KEY) === THEME_ENABLED;
if (isDarkMode) {
document.body.classList.add('dark-mode');
updateDarkModeIcon(true);
}
if (darkModeToggleElement) {
darkModeToggleElement.addEventListener('click', toggleDarkMode);
}
}
/**
* Toggle dark mode on/off
* - Saves preference to localStorage
* - Applies/removes dark-mode class from body
*/
function toggleDarkMode() {
const isDarkMode = document.body.classList.toggle('dark-mode');
localStorage.setItem(DARK_MODE_KEY, isDarkMode ? THEME_ENABLED : THEME_DISABLED);
updateDarkModeIcon(isDarkMode);
}
/**
* Update dark mode toggle icon
* @param {boolean} isDarkMode - Whether dark mode is currently enabled
*/
function updateDarkModeIcon(isDarkMode) {
if (darkModeToggleElement) {
darkModeToggleElement.textContent = isDarkMode ? '☀️' : '🌙';
darkModeToggleElement.title = isDarkMode ? 'Switch to Light Mode' : 'Switch to Dark Mode';
}
}