-
-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathscript.js
More file actions
1080 lines (969 loc) · 32.3 KB
/
script.js
File metadata and controls
1080 lines (969 loc) · 32.3 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
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* 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 isDataLoaded = false;
// ============================================================================
// INITIALIZATION
// ============================================================================
document.addEventListener('DOMContentLoaded', initializeApp);
/**
* Initialize the application on page load
*/
async function initializeApp() {
showLoadingState();
setupEventListeners();
await Promise.all([fetchAndPrepareUsers(), loadFeaturedUser()]);
// Do these if data is loaded
if (isDataLoaded) {
applyFilters();
updateVisibilityAndSort();
hideLoadingState();
}
}
/**
* Show a toast notification message
* @param {string} message - The message to display
*/
function showToast(message) {
const msg = document.createElement('div');
msg.className = 'toast-notification';
msg.textContent = message;
document.body.appendChild(msg);
setTimeout(() => msg.remove(), 3000);
}
/**
* Pick and highlight a random user from the filtered and sorted list
*/
function pickRandomUser(event) {
// Prevent any default behavior or navigation
if (event) {
event.preventDefault();
event.stopPropagation();
event.stopImmediatePropagation();
}
const usersToPickFrom = getVisibleSortedUsers();
if (usersToPickFrom.length === 0) {
showToast('🎲 No developers found! Try adjusting your filters.');
return false;
}
const filtersAside = document.getElementById('filtersAside');
if (filtersAside && filtersAside.classList.contains('open')) {
toggleFiltersPanel();
}
const randomIndex = Math.floor(Math.random() * usersToPickFrom.length);
const randomUser = usersToPickFrom[randomIndex];
// Find the card element for the random user
if (!randomUser.card || !randomUser.card.isConnected) {
// Attempt to find the card in the DOM by data-login as a fallback
const fallbackCard = document.querySelector(
`[data-login="${randomUser.login}"]`,
);
if (fallbackCard) {
randomUser.card = fallbackCard;
} else {
showToast('🎲 Could not locate the selected developer card. Try again.');
return false;
}
}
// Find and disable ALL links in the card to prevent any navigation
const cardLinks = randomUser.card.querySelectorAll('a');
const originalPointerEvents = [];
cardLinks.forEach((link, index) => {
originalPointerEvents[index] = link.style.pointerEvents;
link.style.pointerEvents = 'none';
});
// Scroll near the card (with a small offset to avoid landing exactly on it)
const cardRect = randomUser.card.getBoundingClientRect();
const scrollOffset = cardRect.top + window.scrollY - 100; // 100px offset from top
window.scrollTo({top: Math.max(0, scrollOffset), behavior: 'smooth'});
// Highlight the card
randomUser.card.classList.remove('highlight');
void randomUser.card.offsetWidth; // Force reflow
randomUser.card.classList.add('highlight');
// Re-enable the links and remove highlight after 3 seconds
setTimeout(() => {
cardLinks.forEach((link, index) => {
link.style.pointerEvents = originalPointerEvents[index] || '';
});
randomUser.card.classList.remove('highlight');
}, 3000);
}
async function fetchAndPrepareUsers() {
try {
const res = await fetch('users.json', {cache: 'no-store'});
if (!res.ok) throw new Error(`Failed to fetch users.json: ${res.status}`);
const users = await res.json();
const prepared = users.map(prepareUserFromJson);
allUsers = prepared;
filteredUsers = [...allUsers];
isDataLoaded = true;
const total = allUsers.length;
document.getElementById('totalCount').textContent = total.toLocaleString();
} catch (err) {
console.error(err);
const loadingStates = document.querySelectorAll('.loading-state');
loadingStates.forEach((state) => {
const spinner = state.querySelector('.loading-spinner');
const errorMessage = state.querySelector('.error-message');
const loadingMessage = state.querySelector('p:not(.error-message)');
if (spinner) spinner.style.display = 'none';
if (loadingMessage) loadingMessage.style.display = 'none';
if (errorMessage) {
errorMessage.textContent =
'Unable to load users. Please try again later.';
errorMessage.style.display = 'block';
}
});
}
}
/**
* Load and display the featured user of the month
*/
async function loadFeaturedUser() {
try {
const res = await fetch('featured.json', {cache: 'no-store'});
if (!res.ok) {
return;
}
const data = await res.json();
if (data?.user?.login) {
renderFeaturedUser(data.user);
}
} catch (err) {
// Silently fail - featured user is optional
}
}
/**
* Render featured user to DOM
*/
function renderFeaturedUser(user) {
const elements = getFeaturedUserElements();
if (!elements.section) return;
updateFeaturedAvatar(elements, user);
updateFeaturedInfo(elements, user);
updateFeaturedStats(elements, user);
updateFeaturedLanguages(elements, user);
elements.section.style.display = 'block';
}
/**
* Get all featured user DOM elements
*/
function getFeaturedUserElements() {
return {
section: document.getElementById('featuredUserSection'),
avatar: document.getElementById('featuredUserAvatar'),
link: document.getElementById('featuredUserLink'),
name: document.getElementById('featuredUserName'),
loginLink: document.getElementById('featuredUserLoginLink'),
location: document.getElementById('featuredUserLocation'),
followers: document.getElementById('featuredUserFollowers'),
stars: document.getElementById('featuredUserStars'),
repos: document.getElementById('featuredUserRepos'),
sponsors: document.getElementById('featuredUserSponsors'),
languages: document.getElementById('featuredUserLanguages'),
};
}
/**
* Update featured user avatar and links
*/
function updateFeaturedAvatar(elements, user) {
const avatarUrl = `images/faces/${user.login.toLowerCase()}.png`;
elements.avatar.src = avatarUrl;
elements.avatar.alt = `${user.login}'s avatar`;
elements.link.href = user.html_url;
elements.loginLink.href = user.html_url;
elements.loginLink.textContent = `@${user.login}`;
}
/**
* Update featured user info (name and location)
*/
function updateFeaturedInfo(elements, user) {
elements.name.textContent = user.name || user.login;
if (user.location) {
elements.location.querySelector('.location-text').textContent =
user.location;
elements.location.style.display = 'flex';
} else {
elements.location.style.display = 'none';
}
}
/**
* Update featured user stats
*/
function updateFeaturedStats(elements, user) {
elements.followers.textContent = formatDisplay(user.followers);
elements.stars.textContent = formatDisplay(user.total_stars);
elements.repos.textContent = formatDisplay(user.public_repos);
elements.sponsors.textContent = formatDisplay(user.sponsors_count);
}
/**
* Update featured user languages
*/
function updateFeaturedLanguages(elements, user) {
elements.languages.innerHTML = '';
if (Array.isArray(user.top_languages) && user.top_languages.length > 0) {
user.top_languages.slice(0, 5).forEach((lang) => {
const badge = document.createElement('div');
badge.className = 'featured-language-badge';
badge.textContent = lang.name;
elements.languages.appendChild(badge);
});
}
}
function prepareUserFromJson(user) {
const getNum = (v, def = 0) =>
v === 'N/A' || v == null ? def : parseInt(v, 10);
const safeLower = (v) => (v ? String(v).toLowerCase() : '');
const normalizeDate = (v) => (v ? new Date(v).toISOString() : '');
const topLangs = Array.isArray(user.top_languages) ? user.top_languages : [];
return {
name: safeLower(user.name || user.login),
login: safeLower(user.login),
location: safeLower(user.location || ''),
html_url: user.html_url,
avatar_updated_at: normalizeDate(user.avatar_updated_at),
last_repo_pushed_at: normalizeDate(user.last_repo_pushed_at),
last_public_commit_at: normalizeDate(user.last_public_commit_at),
followers: getNum(user.followers),
following: getNum(user.following),
repos: getNum(user.public_repos),
gists: getNum(user.public_gists),
forks: 0,
sponsors: getNum(user.sponsors_count),
sponsoring: getNum(user.sponsoring_count),
total_stars: getNum(user.total_stars),
top_languages: topLangs.map((l) => ({
name: safeLower(l.name),
label: l.name,
bytes: getNum(l.bytes),
percent: l.percent,
})),
followers_display: user.followers_display || formatDisplay(user.followers),
following_display: user.following_display || formatDisplay(user.following),
repos_display: user.repos_display || formatDisplay(user.public_repos),
gists_display: user.gists_display || formatDisplay(user.public_gists),
sponsors_display:
user.sponsors_display || formatDisplay(user.sponsors_count),
sponsoring_display:
user.sponsoring_display || formatDisplay(user.sponsoring_count),
stars_display: formatDisplay(user.total_stars),
raw: user,
};
}
function formatDisplay(val) {
if (val === 'N/A' || val == null) return 'N/A';
const num = parseInt(val, 10);
return Number.isNaN(num) ? String(val) : num.toLocaleString();
}
function formatDateDisplay(val) {
if (!val) return 'N/A';
const dt = new Date(val);
if (Number.isNaN(dt.getTime())) return 'N/A';
return dt.toISOString().split('T')[0];
}
/**
* Extract location emoji and text from card
* @param {HTMLElement} card - The card element
* @returns {string} Location text in lowercase
*/
function extractLocation() {
return '';
}
/**
* Extract sponsors and sponsoring counts from stats
* @param {HTMLElement} card - The card element
* @returns {Object} Object with sponsors and sponsoring counts
*/
function extractStats() {
return {sponsors: 0, sponsoring: 0};
}
// ============================================================================
// 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',
'minStarsFilter',
'languageFilter',
'lastRepoActivityFilter',
'lastCommitFilter',
];
filterIds.forEach((id) => {
const element = document.getElementById(id);
if (element) {
element.addEventListener('input', onFilterChange);
element.addEventListener('change', onFilterChange);
}
});
const randomBtn = document.getElementById('randomUserBtn');
if (randomBtn) {
// Change button type to prevent form submission
randomBtn.type = 'button';
randomBtn.addEventListener('click', pickRandomUser);
}
}
/**
* Get currently visible sorted users matching the displayed order
* Uses the same filtering and sorting logic as the display
* @returns {Array} Array of visible user objects in displayed order
*/
function getVisibleSortedUsers() {
const sortBy = document.getElementById('sortBy').value;
return getSortedUsers(sortBy);
}
/**
* 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);
});
}
// Export JSON
function exportFilteredJSON() {
if (!filteredUsers.length) {
alert('No users to export');
return;
}
const userData = filteredUsers.map((user) => user.raw);
const jsonString = JSON.stringify(userData, null, 2);
const blob = new Blob([jsonString], {type: 'application/json'});
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'github-faces.json';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
// Export CSV
function exportFilteredCSV() {
if (!filteredUsers.length) {
alert('No users to export');
return;
}
const rows = filteredUsers.map((user) => user.raw);
const headers = Object.keys(rows[0]);
const escapeCSV = (value) => {
if (value == null) return '';
// if object or array, stringify it
const str =
typeof value === 'object'
? JSON.stringify(value).replace(/"/g, '""')
: String(value).replace(/"/g, '""');
return `"${str}"`;
};
const csv = [
headers.join(','),
...rows.map((row) => headers.map((h) => escapeCSV(row[h])).join(',')),
].join('\n');
const blob = new Blob([csv], {type: 'text/csv;charset=utf-8'});
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'github-faces.csv';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
/**
* 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,
minStars: parseInt(document.getElementById('minStarsFilter').value),
languageFilter: document
.getElementById('languageFilter')
.value.toLowerCase()
.trim(),
lastRepoActivityFilter: document.getElementById('lastRepoActivityFilter')
.value,
lastCommitFilter: document.getElementById('lastCommitFilter').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) &&
matchesStars(user, filters.minStars) &&
matchesLanguage(user, filters.languageFilter) &&
matchesRepoActivity(user, filters.lastRepoActivityFilter, dateRanges) &&
matchesCommitActivity(user, filters.lastCommitFilter, 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.avatar_updated_at) return true;
const avatarDate = new Date(user.avatar_updated_at);
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;
}
function matchesStars(user, minStars) {
return user.total_stars >= (Number.isNaN(minStars) ? 0 : minStars);
}
function matchesLanguage(user, languageFilter) {
if (!languageFilter) return true;
return user.top_languages.some((l) => l.name.includes(languageFilter));
}
function matchesRepoActivity(user, activityFilter, dateRanges) {
if (activityFilter === 'any' || !user.last_repo_pushed_at) return true;
return matchesDateByRange(
user.last_repo_pushed_at,
activityFilter,
dateRanges,
);
}
function matchesCommitActivity(user, commitFilter, dateRanges) {
if (commitFilter === 'any' || !user.last_public_commit_at) return true;
return matchesDateByRange(
user.last_public_commit_at,
commitFilter,
dateRanges,
);
}
function matchesDateByRange(dateString, rangeKey, dateRanges) {
const dt = new Date(dateString);
const ranges = {
week: dt >= dateRanges.oneWeekAgo,
month: dt >= dateRanges.oneMonthAgo,
'6months': dt >= dateRanges.sixMonthsAgo,
year: dt >= dateRanges.oneYearAgo,
'2years': dt >= dateRanges.twoYearsAgo,
'5years': dt >= dateRanges.fiveYearsAgo,
old: dt < dateRanges.fiveYearsAgo,
};
return ranges[rangeKey] !== undefined ? ranges[rangeKey] : 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,
'gists-desc': (a, b) => b.gists - a.gists,
'gists-asc': (a, b) => a.gists - b.gists,
'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,
'stars-desc': (a, b) => b.total_stars - a.total_stars,
'stars-asc': (a, b) => a.total_stars - b.total_stars,
'last-repo-desc': (a, b) =>
new Date(b.last_repo_pushed_at || 0) -
new Date(a.last_repo_pushed_at || 0),
'last-repo-asc': (a, b) =>
new Date(a.last_repo_pushed_at || 0) -
new Date(b.last_repo_pushed_at || 0),
'last-commit-desc': (a, b) =>
new Date(b.last_public_commit_at || 0) -
new Date(a.last_public_commit_at || 0),
'last-commit-asc': (a, b) =>
new Date(a.last_public_commit_at || 0) -
new Date(b.last_public_commit_at || 0),
'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');
if (!grid) return;
grid.innerHTML = '';
const frag = document.createDocumentFragment();
sortedUsers.forEach((user) => {
const card = buildCardElement(user);
frag.appendChild(card);
});
grid.appendChild(frag);
}
function buildCardElement(user) {
const card = document.createElement('div');
card.className = 'card visible';
card.setAttribute('data-followers', user.followers);
card.setAttribute('data-repos', user.repos);
card.setAttribute('data-forks', user.forks);
card.setAttribute('data-name', user.name);
card.setAttribute('data-login', user.login);
card.setAttribute('data-location', user.location);
card.setAttribute('data-avatar-updated', user.avatar_updated_at || '');
card.setAttribute('data-stars', user.total_stars || 0);
const link = document.createElement('a');
link.href = user.html_url;
link.target = '_blank';
link.rel = 'noopener';
const img = document.createElement('img');
img.src = `images/faces/${user.login}.png`;
img.alt = user.login;
img.title = user.login;
img.loading = 'lazy';
img.decoding = 'async';
link.appendChild(img);
const box = document.createElement('div');
box.className = 'details-box';
const strong = document.createElement('strong');
strong.textContent = user.raw.name || user.raw.login;
const atSpan = document.createElement('span');
atSpan.textContent = `@${user.raw.login}`;
box.appendChild(strong);
box.appendChild(atSpan);
box.appendChild(
buildLabeledSpan(
'Followers:',
user.raw.followers !== 'N/A',
`${user.html_url}?tab=followers`,
user.followers_display,
),
);
box.appendChild(
buildLabeledSpan(
'Following:',
user.raw.following !== 'N/A',
`${user.html_url}?tab=following`,
user.following_display,
),
);
if (user.raw.location) {
const locSpan = document.createElement('span');
locSpan.textContent = `🌐 ${user.raw.location}`;
box.appendChild(locSpan);
}
const statsRow = document.createElement('div');
statsRow.className = 'stats-row';
statsRow.appendChild(
buildStat(
user.raw.public_repos !== 'N/A',
`${user.html_url}?tab=repositories`,
user.repos_display,
'Repos',
),
);
statsRow.appendChild(
buildStat(
user.raw.public_gists !== 'N/A',
`https://gist.github.com/${user.raw.login}`,
user.gists_display,
'Gists',
),
);
statsRow.appendChild(
buildStat(
user.raw.sponsors_count !== 'N/A',
`${user.html_url}?tab=sponsors`,
user.sponsors_display,
'Public Sponsors',
),
);
statsRow.appendChild(
buildStat(
user.raw.sponsoring_count !== 'N/A',
`${user.html_url}?tab=sponsoring`,
user.sponsoring_display,
'Public Sponsoring',
),
);
statsRow.appendChild(
buildStat(
true,
`${user.html_url}?tab=repositories`,
user.stars_display,
'Total Stars',
),
);
box.appendChild(statsRow);
const activity = document.createElement('div');
activity.className = 'activity-row';
let commitText = `Last commit: ${formatDateDisplay(user.last_repo_pushed_at)}`;
if (user.last_public_commit_at)
commitText += `<br>Last public commit: ${formatDateDisplay(user.last_public_commit_at)}`;
activity.innerHTML = commitText;
box.appendChild(activity);
if (user.top_languages.length) {
const langRow = document.createElement('div');
langRow.className = 'lang-row';
user.top_languages.slice(0, 3).forEach((lang) => {
const pill = document.createElement('span');
pill.className = 'lang-pill';
pill.textContent = `${lang.label}${lang.percent ? ` (${lang.percent}%)` : ''}`;
langRow.appendChild(pill);
});
box.appendChild(langRow);
}
card.appendChild(link);
card.appendChild(box);
user.card = card;
return card;
}
function buildLabeledSpan(labelText, hasLink, href, valueText) {
const span = document.createElement('span');
const labelNode = document.createTextNode(`${labelText} `);
span.appendChild(labelNode);
if (hasLink) {
const a = document.createElement('a');
a.href = href;
a.target = '_blank';
a.rel = 'noopener';
a.textContent = valueText;
span.appendChild(a);
} else {
span.appendChild(document.createTextNode(valueText));
}
return span;
}
function buildStat(hasLink, href, valueText, label) {
const stat = document.createElement('div');
stat.className = 'stat';
if (hasLink) {
const a = document.createElement('a');
a.href = href;
a.target = '_blank';
a.rel = 'noopener';
a.textContent = valueText;
stat.appendChild(a);
} else {
stat.appendChild(document.createTextNode(valueText));
}
const lbl = document.createElement('span');
lbl.className = 'stat-label';
lbl.textContent = label;
stat.appendChild(lbl);
return stat;
}
/**
* 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();
}
/**
* Update results found/no results message
* @param {Array} sortedUsers - Sorted users array