-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathapp.js
More file actions
2750 lines (2322 loc) · 75.4 KB
/
app.js
File metadata and controls
2750 lines (2322 loc) · 75.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
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 Repository Showcase Application
* Modern, interactive web application for displaying GitHub repositories
*/
// Browser compatibility: Define process if it doesn't exist
if (typeof process === 'undefined') {
window.process = {
env: {},
browser: true
};
}
class GitHubShowcase {
constructor() {
this.state = {
repositories: [],
filteredRepositories: [],
searchTerm: '',
selectedLanguage: '',
sortBy: 'recent-likes',
sortOrder: 'desc',
isLoading: true,
languages: [],
error: null,
languageCategory: 'recently' // 'popular' or 'recently'
};
this.elements = {};
this.debounceTimer = null;
this.animationFrame = null;
this.performanceMetrics = {
loadStartTime: performance.now(),
searchTimes: [],
renderTimes: []
};
this.intersectionObserver = null;
this.mutationObserver = null;
}
/**
* Initialize the application
*/
async init() {
try {
this.cacheElements();
this.bindEvents();
this.initializeAnimations();
this.initializeAccessibility();
this.initializeOptimizations();
await this.loadData();
this.render();
this.initializeScrollAnimations();
} catch (error) {
console.error('Failed to initialize application:', error);
this.handleError(error);
}
}
/**
* Cache DOM elements for better performance
*/
cacheElements() {
this.elements = {
searchInput: document.getElementById('searchInput'),
searchClear: document.getElementById('searchClear'),
languageFilter: document.getElementById('languageFilter'),
sortSelect: document.getElementById('sortSelect'),
repositoryGrid: document.getElementById('repositoryGrid'),
loadingState: document.getElementById('loadingState'),
emptyState: document.getElementById('emptyState'),
errorState: document.getElementById('errorState'),
statsBar: document.getElementById('statsBar'),
totalCount: document.getElementById('totalCount'),
filteredCount: document.getElementById('filteredCount'),
languageCount: document.getElementById('languageCount'),
resetFilters: document.getElementById('resetFilters'),
retryButton: document.getElementById('retryButton'),
quickFilters: document.getElementById('quickFilters'),
quickFilterButtons: document.getElementById('quickFilterButtons'),
categorizationButtons: document.querySelectorAll('.categorization-btn'),
};
}
/**
* Bind event listeners
*/
bindEvents() {
// Search functionality
this.elements.searchInput.addEventListener('input', (e) => {
this.handleSearch(e.target.value);
});
this.elements.searchClear.addEventListener('click', () => {
this.clearSearch();
});
// Filter functionality
this.elements.languageFilter.addEventListener('change', (e) => {
// this.handleLanguageFilter(e.target.value);
this.handleSearch(e.target.value);
});
// Sort functionality
this.elements.sortSelect.addEventListener('change', (e) => {
this.handleSort(e.target.value);
});
// Reset filters
this.elements.resetFilters.addEventListener('click', () => {
this.resetFilters();
});
// Retry button
this.elements.retryButton.addEventListener('click', () => {
this.retry();
});
// Categorization buttons
this.elements.categorizationButtons.forEach(btn => {
btn.addEventListener('click', (e) => {
this.handleCategorization(e.target.getAttribute('data-category'));
});
});
// Keyboard shortcuts and navigation
document.addEventListener('keydown', (e) => {
this.handleKeyboardNavigation(e);
});
}
/**
* Load repository data from JSON file
*/
async loadData() {
try {
this.setState({ isLoading: true, error: null });
// Add timeout for better error handling
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 10000); // 10 second timeout
const response = await fetch('data.json', {
signal: controller.signal,
cache: 'default' // Enable caching for better performance
});
clearTimeout(timeoutId);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
const repositories = this.processRepositoryData(data);
const languages = this.extractLanguages(repositories);
this.setState({
repositories,
filteredRepositories: repositories,
languages,
isLoading: false
});
this.populateLanguageFilter(languages);
this.populateQuickFilters();
} catch (error) {
console.error('Error loading data:', error);
let errorMessage = 'Failed to load repository data';
if (error.name === 'AbortError') {
errorMessage = 'Request timed out. Please check your connection and try again.';
} else if (error.message.includes('HTTP error')) {
errorMessage = 'Server error. Please try again later.';
}
this.setState({
isLoading: false,
error: errorMessage
});
throw error;
}
}
/**
* Process raw repository data into normalized format
*/
processRepositoryData(data) {
const repositories = [];
let originalIndex = 0;
const languageOrder = {}; // Track the order languages appear in data.json
let languageOrderIndex = 0;
// Handle both object format (grouped by language) and array format
if (Array.isArray(data)) {
repositories.push(...data);
} else if (typeof data === 'object') {
// Flatten repositories from language groups while preserving order
Object.keys(data).forEach(language => {
// Track language order for "Recently" categorization
if (!languageOrder[language]) {
languageOrder[language] = languageOrderIndex++;
}
const languageRepos = data[language];
if (Array.isArray(languageRepos)) {
repositories.push(...languageRepos);
}
});
}
// Store language order for later use
this.languageOrder = languageOrder;
// Normalize and validate repository data
return repositories
.filter(repo => repo && repo.id && repo.name)
.map(repo => ({
...repo,
// Ensure required fields have defaults
description: repo.description || '',
stargazers_count: repo.stargazers_count || 0,
language: repo.language || 'Unknown',
topics: Array.isArray(repo.topics) ? repo.topics : [],
created_at: repo.created_at || new Date().toISOString(),
updated_at: repo.updated_at || new Date().toISOString(),
// Add computed fields
originalIndex: originalIndex++, // Track original order for "Recent Likes" sorting
searchText: this.createSearchText(repo),
formattedStars: this.formatNumber(repo.stargazers_count || 0),
relativeTime: this.getRelativeTime(repo.updated_at),
languageColor: this.getLanguageColor(repo.language)
}))
.sort((a, b) => b.stargazers_count - a.stargazers_count); // Default sort by stars
}
/**
* Create searchable text from repository data
*/
createSearchText(repo) {
return [
repo.name,
repo.full_name,
repo.description,
repo.language,
...(repo.topics || []),
repo.owner?.login
].filter(Boolean).join(' ').toLowerCase();
}
/**
* Extract unique languages from repositories
*/
extractLanguages(repositories) {
const languageSet = new Set();
repositories.forEach(repo => {
if (repo.language && repo.language !== 'Unknown') {
languageSet.add(repo.language);
}
});
return Array.from(languageSet).sort();
}
/**
* Populate language filter dropdown with counts
*/
populateLanguageFilter(languages) {
const fragment = document.createDocumentFragment();
// Calculate repository count for each language
const languageCounts = this.calculateLanguageCounts();
// Sort languages by count (descending) then alphabetically
const sortedLanguages = languages.sort((a, b) => {
const countA = languageCounts[a] || 0;
const countB = languageCounts[b] || 0;
if (countA !== countB) {
return countB - countA; // Sort by count descending
}
return a.localeCompare(b); // Then alphabetically
});
sortedLanguages.forEach(language => {
const option = document.createElement('option');
option.value = language;
const count = languageCounts[language] || 0;
option.textContent = `${language} (${count})`;
// Add data attribute for styling
option.setAttribute('data-count', count);
fragment.appendChild(option);
});
// Clear existing options except "All Languages"
while (this.elements.languageFilter.children.length > 1) {
this.elements.languageFilter.removeChild(this.elements.languageFilter.lastChild);
}
this.elements.languageFilter.appendChild(fragment);
}
/**
* Calculate repository count for each language
*/
calculateLanguageCounts() {
const counts = {};
this.state.repositories.forEach(repo => {
const language = repo.language || 'Unknown';
counts[language] = (counts[language] || 0) + 1;
});
return counts;
}
/**
* Handle language filter change with analytics
*/
handleLanguageFilter(language) {
this.setState({ selectedLanguage: language });
this.render();
// Track filter usage
if (language) {
console.log('Language filter applied:', language);
}
}
/**
* Get languages for quick filters based on categorization mode
*/
getLanguagesForQuickFilters(limit = 6) {
const languageCounts = this.calculateLanguageCounts();
const { languageCategory } = this.state;
if (languageCategory === 'recently') {
// Sort by the order languages appear in data.json
return Object.keys(languageCounts)
.sort((langA, langB) => {
const orderA = this.languageOrder[langA] ?? 999;
const orderB = this.languageOrder[langB] ?? 999;
return orderA - orderB;
})
.slice(0, limit);
} else {
// Default: Sort by popularity (repository count)
return Object.entries(languageCounts)
.sort(([, a], [, b]) => b - a)
.slice(0, limit)
.map(([language]) => language);
}
}
/**
* Populate quick filter buttons
*/
populateQuickFilters() {
const languages = this.getLanguagesForQuickFilters(6);
const languageCounts = this.calculateLanguageCounts();
const { languageCategory } = this.state;
if (languages.length === 0) {
this.elements.quickFilters.style.display = 'none';
return;
}
// Update the label based on categorization mode
const label = this.elements.quickFilters.querySelector('.quick-filters-label');
if (label) {
label.textContent = languageCategory === 'recently' ? 'Recently:' : 'Popular:';
}
const fragment = document.createDocumentFragment();
languages.forEach(language => {
const button = document.createElement('button');
button.className = 'quick-filter-btn';
button.setAttribute('data-language', language);
button.innerHTML = `
<span class="language-dot ${language.toLowerCase()}" style="background-color: ${this.getLanguageColor(language)}"></span>
<span>${language}</span>
<span class="quick-filter-count">${languageCounts[language] || 0}</span>
`;
button.addEventListener('click', () => {
this.handleQuickFilter(language);
});
fragment.appendChild(button);
});
this.elements.quickFilterButtons.innerHTML = '';
this.elements.quickFilterButtons.appendChild(fragment);
this.elements.quickFilters.style.display = 'flex';
}
/**
* Handle quick filter button click
*/
handleQuickFilter(language) {
// Update the main language filter
this.elements.languageFilter.value = language;
// Update active state of quick filter buttons
this.elements.quickFilterButtons.querySelectorAll('.quick-filter-btn').forEach(btn => {
btn.classList.toggle('active', btn.getAttribute('data-language') === language);
});
// Apply the filter
this.handleLanguageFilter(language);
}
/**
* Update application state
*/
setState(newState) {
this.state = { ...this.state, ...newState };
// Update filtered repositories when relevant state changes
if (newState.hasOwnProperty('repositories') ||
newState.hasOwnProperty('searchTerm') ||
newState.hasOwnProperty('selectedLanguage')) {
this.updateFilteredRepositories();
}
// Sort repositories when sort criteria changes
if (newState.hasOwnProperty('sortBy') || newState.hasOwnProperty('sortOrder')) {
this.sortRepositories();
}
}
/**
* Update filtered repositories based on current filters
*/
updateFilteredRepositories() {
let filtered = [...this.state.repositories];
// Apply search filter with advanced search
if (this.state.searchTerm) {
filtered = this.performAdvancedSearch(filtered, this.state.searchTerm);
}
// Apply language filter
if (this.state.selectedLanguage) {
filtered = filtered.filter(repo =>
repo.language === this.state.selectedLanguage
);
}
this.state.filteredRepositories = filtered;
this.sortRepositories();
}
/**
* Sort repositories based on current sort criteria
*/
sortRepositories() {
const { sortBy } = this.state;
this.state.filteredRepositories.sort((a, b) => {
let comparison = 0;
switch (sortBy) {
case 'stars':
comparison = b.stargazers_count - a.stargazers_count;
break;
case 'recent-likes':
// Sort by original order in data.json (recent likes order)
comparison = (a.originalIndex || 0) - (b.originalIndex || 0);
break;
case 'stars-asc':
comparison = a.stargazers_count - b.stargazers_count;
break;
case 'name':
comparison = a.name.localeCompare(b.name, undefined, { sensitivity: 'base' });
break;
case 'name-desc':
comparison = b.name.localeCompare(a.name, undefined, { sensitivity: 'base' });
break;
case 'updated':
comparison = new Date(b.updated_at) - new Date(a.updated_at);
break;
case 'created':
comparison = new Date(b.created_at) - new Date(a.created_at);
break;
default:
// Default to stars descending
comparison = b.stargazers_count - a.stargazers_count;
}
return comparison;
});
}
/**
* Handle sort change with enhanced logic
*/
handleSort(sortBy) {
this.setState({ sortBy });
this.render();
// Track sorting usage
console.log('Sort applied:', sortBy);
// Add visual feedback
this.addSortFeedback(sortBy);
}
/**
* Add visual feedback for sorting
*/
addSortFeedback(sortBy) {
const sortSelect = this.elements.sortSelect;
sortSelect.classList.add('sorting');
setTimeout(() => {
sortSelect.classList.remove('sorting');
}, 300);
}
/**
* Get sort display name for UI
*/
getSortDisplayName(sortBy) {
const sortNames = {
'stars': 'Most Stars',
'stars-asc': 'Least Stars',
'name': 'Name A-Z',
'name-desc': 'Name Z-A',
'updated': 'Recently Updated',
'created': 'Recently Created'
};
return sortNames[sortBy] || 'Most Stars';
}
/**
* Handle search input with advanced features
*/
handleSearch(searchTerm) {
// Clear existing debounce timer
if (this.debounceTimer) {
clearTimeout(this.debounceTimer);
}
// Update search clear button visibility
this.elements.searchClear.classList.toggle('visible', searchTerm.length > 0);
// Show immediate feedback for empty search
if (searchTerm.trim() === '') {
this.setState({ searchTerm: '' });
this.render();
return;
}
// Add loading indicator for search
this.elements.searchInput.classList.add('searching');
// Reduced debounce time for better responsiveness
this.debounceTimer = setTimeout(() => {
this.setState({ searchTerm: searchTerm.trim() });
this.elements.searchInput.classList.remove('searching');
this.render();
// Track search analytics (if needed)
this.trackSearch(searchTerm.trim());
}, 200);
}
/**
* Advanced search with multiple criteria
*/
performAdvancedSearch(repositories, searchTerm) {
if (!searchTerm) return repositories;
const terms = searchTerm.toLowerCase().split(/\s+/).filter(term => term.length > 0);
return repositories.filter(repo => {
// Calculate relevance score
let score = 0;
const searchableText = repo.searchText;
// Check if all terms are present
const hasAllTerms = terms.every(term => searchableText.includes(term));
if (!hasAllTerms) return false;
// Boost score for exact matches in important fields
terms.forEach(term => {
if (repo.name.toLowerCase().includes(term)) score += 10;
if (repo.description.toLowerCase().includes(term)) score += 5;
if (repo.topics.some(topic => topic.toLowerCase().includes(term))) score += 8;
if (repo.language.toLowerCase().includes(term)) score += 6;
if (repo.owner.login.toLowerCase().includes(term)) score += 4;
});
// Store score for potential sorting
repo.searchScore = score;
return score > 0;
}).sort((a, b) => (b.searchScore || 0) - (a.searchScore || 0));
}
/**
* Track search for analytics (placeholder)
*/
trackSearch(searchTerm) {
// This could be used to track popular searches
console.log('Search performed:', searchTerm);
}
/**
* Clear search input and filters
*/
clearSearch() {
this.elements.searchInput.value = '';
this.elements.searchClear.classList.remove('visible');
this.setState({ searchTerm: '' });
this.render();
}
/**
* Handle language filter change
*/
handleLanguageFilter(language) {
this.setState({ selectedLanguage: language });
this.render();
// this.showToast(`🎉 Found ${resultCount} repositories matching "${searchTerm.trim()}"`, 'success', 1000);
}
/**
* Handle sort change
*/
handleSort(sortBy) {
this.setState({ sortBy });
this.render();
}
/**
* Reset all filters
*/
resetFilters() {
this.elements.searchInput.value = '';
this.elements.searchClear.classList.remove('visible');
this.elements.languageFilter.value = '';
this.elements.sortSelect.value = 'recent-likes';
// Reset quick filter buttons
this.elements.quickFilterButtons.querySelectorAll('.quick-filter-btn').forEach(btn => {
btn.classList.remove('active');
});
// Reset categorization to "Recently"
this.elements.categorizationButtons.forEach(btn => {
btn.classList.toggle('active', btn.getAttribute('data-category') === 'recently');
});
this.setState({
searchTerm: '',
selectedLanguage: '',
sortBy: 'recent-likes',
languageCategory: 'recently'
});
// Update quick filters to reflect the reset categorization
this.populateQuickFilters();
this.render();
}
/**
* Retry loading data
*/
async retry() {
try {
await this.loadData();
this.render();
} catch (error) {
// Error is already handled in loadData
}
}
/**
* Handle categorization change
*/
handleCategorization(category) {
// Update active state of categorization buttons
this.elements.categorizationButtons.forEach(btn => {
btn.classList.toggle('active', btn.getAttribute('data-category') === category);
});
this.setState({ languageCategory: category });
// Update quick filters to reflect the new categorization
this.populateQuickFilters();
this.render();
// Track categorization usage
console.log('Language categorization changed:', category);
}
/**
* Handle application errors
*/
handleError(error) {
this.setState({
error: error.message || 'An unexpected error occurred',
isLoading: false
});
this.render();
}
/**
* Render the application
*/
render() {
// Cancel any pending animation frame
if (this.animationFrame) {
cancelAnimationFrame(this.animationFrame);
}
// Use requestAnimationFrame for smooth rendering
this.animationFrame = requestAnimationFrame(() => {
this.updateUI();
});
}
/**
* Update the UI based on current state
*/
updateUI() {
const { isLoading, error, filteredRepositories, repositories, languages } = this.state;
// Update statistics
this.updateStatistics();
// Show/hide different states
this.elements.loadingState.style.display = isLoading ? 'flex' : 'none';
this.elements.errorState.style.display = error ? 'flex' : 'none';
this.elements.emptyState.style.display =
!isLoading && !error && filteredRepositories.length === 0 ? 'flex' : 'none';
this.elements.repositoryGrid.style.display =
!isLoading && !error && filteredRepositories.length > 0 ? 'grid' : 'none';
this.elements.statsBar.style.display =
!isLoading && !error ? 'block' : 'none';
// Show skeleton loading or render repositories
if (isLoading) {
this.renderSkeletonCards();
} else if (!error && filteredRepositories.length > 0) {
this.renderRepositories();
}
}
/**
* Render skeleton loading cards
*/
renderSkeletonCards() {
this.elements.repositoryGrid.innerHTML = '';
this.elements.repositoryGrid.className = 'repository-grid skeleton-grid';
this.elements.repositoryGrid.style.display = 'grid';
const skeletonCards = this.createSkeletonCards(9);
this.elements.repositoryGrid.appendChild(skeletonCards);
}
/**
* Update statistics display
*/
updateStatistics() {
const { repositories, filteredRepositories, languages } = this.state;
this.elements.totalCount.textContent = this.formatNumber(repositories.length);
this.elements.filteredCount.textContent = this.formatNumber(filteredRepositories.length);
this.elements.languageCount.textContent = languages.length;
}
/**
* Format numbers for display (e.g., 1000 -> 1K)
*/
formatNumber(num) {
if (num >= 1000000) {
return (num / 1000000).toFixed(1) + 'M';
}
if (num >= 1000) {
return (num / 1000).toFixed(1) + 'K';
}
return num.toString();
}
/**
* Get relative time string (e.g., "2 days ago")
*/
getRelativeTime(dateString) {
const date = new Date(dateString);
const now = new Date();
const diffInSeconds = Math.floor((now - date) / 1000);
const intervals = [
{ label: 'year', seconds: 31536000 },
{ label: 'month', seconds: 2592000 },
{ label: 'day', seconds: 86400 },
{ label: 'hour', seconds: 3600 },
{ label: 'minute', seconds: 60 }
];
for (const interval of intervals) {
const count = Math.floor(diffInSeconds / interval.seconds);
if (count >= 1) {
return `${count} ${interval.label}${count > 1 ? 's' : ''} ago`;
}
}
return 'Just now';
}
/**
* Get language color for styling
*/
getLanguageColor(language) {
const colors = {
'TypeScript': '#3178c6',
'JavaScript': '#f1e05a',
'Python': '#3572a5',
'Java': '#b07219',
'HTML': '#e34c26',
'CSS': '#563d7c',
'SCSS': '#c6538c',
'Vue': '#4fc08d',
'Go': '#00add8',
'Rust': '#dea584',
'PHP': '#4f5d95',
'Ruby': '#701516',
'Swift': '#fa7343',
'Kotlin': '#a97bff',
'Dart': '#00b4ab',
'Shell': '#89e051',
'Dockerfile': '#384d54'
};
return colors[language] || '#64748b';
}
/**
* Render repositories in the grid
*/
renderRepositories() {
const { filteredRepositories } = this.state;
// Performance optimization: use requestAnimationFrame for smooth rendering
requestAnimationFrame(() => {
const fragment = document.createDocumentFragment();
// Group repositories by language for better organization
const groupedRepos = this.groupRepositoriesByLanguage(filteredRepositories);
// Render each language section
Object.entries(groupedRepos).forEach(([language, repos]) => {
// Create language section header
const languageSection = this.createLanguageSection(language, repos.length);
fragment.appendChild(languageSection);
// Create repository cards with staggered animation
repos.forEach((repo, index) => {
const card = this.createRepositoryCard(repo, index);
fragment.appendChild(card);
});
});
// Clear existing content and append new content
this.elements.repositoryGrid.innerHTML = '';
this.elements.repositoryGrid.appendChild(fragment);
// Trigger entrance animations
this.triggerCardAnimations();
});
}
/**
* Group repositories by programming language
*/
groupRepositoriesByLanguage(repositories) {
const grouped = {};
repositories.forEach(repo => {
const language = repo.language || 'Other';
if (!grouped[language]) {
grouped[language] = [];
}
grouped[language].push(repo);
});
// Sort languages based on categorization mode
const { languageCategory } = this.state;
let sortedEntries;
if (languageCategory === 'recently') {
// Sort by the order languages appear in data.json
sortedEntries = Object.entries(grouped)
.sort(([langA], [langB]) => {
const orderA = this.languageOrder[langA] ?? 999;
const orderB = this.languageOrder[langB] ?? 999;
return orderA - orderB;
});
} else {
// Default: Sort by repository count (descending) - Popular
sortedEntries = Object.entries(grouped)
.sort(([, a], [, b]) => b.length - a.length);
}
return Object.fromEntries(sortedEntries);
}
/**
* Create language section header
*/
createLanguageSection(language, count) {
const section = document.createElement('div');
section.className = 'language-section';
section.innerHTML = `
<div class="language-header">
<h2 class="language-title">
<span class="language-dot ${language.toLowerCase()}" style="background-color: ${this.getLanguageColor(language)}"></span>
${language}
</h2>
<span class="language-count">${count} ${count === 1 ? 'repository' : 'repositories'}</span>
</div>
`;
return section;
}
/**
* Create a repository card element
*/
createRepositoryCard(repo, index = 0) {
const card = document.createElement('article');
card.className = 'repo-card';
card.style.animationDelay = `${Math.min(index * 100, 600)}ms`;
// Create card content
card.innerHTML = `
<div class="repo-header">
<div class="repo-title">
<a href="${repo.html_url}" target="_blank" rel="noopener noreferrer" class="repo-name">
${this.escapeHtml(repo.name)}
</a>
<div class="repo-full-name">${this.escapeHtml(repo.full_name)}</div>
</div>
<div class="repo-stars">
<span class="star-icon">⭐</span>
<span class="star-count">${repo.formattedStars}</span>
</div>
</div>
${repo.description ? `<p class="repo-description">${this.escapeHtml(repo.description)}</p>` : ''}
<div class="repo-topics">
${repo.topics.slice(0, 6).map(topic =>
`<a href="https://github.com/topics/${encodeURIComponent(topic)}"
target="_blank"
rel="noopener noreferrer"
class="topic-tag">${this.escapeHtml(topic)}</a>`
).join('')}
${repo.topics.length > 6 ? `<span class="topic-tag">+${repo.topics.length - 6} more</span>` : ''}
</div>
${repo.homepage ? `
<a href="${repo.homepage}" target="_blank" rel="noopener noreferrer" class="repo-homepage">
<svg class="homepage-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"></path>
<polyline points="15,3 21,3 21,9"></polyline>
<line x1="10" y1="14" x2="21" y2="3"></line>
</svg>
Visit Website
</a>
` : ''}
<div class="repo-footer">
<a href="${repo.owner.html_url}" target="_blank" rel="noopener noreferrer" class="repo-owner">
<img src="${repo.owner.avatar_url}" alt="${this.escapeHtml(repo.owner.login)}" class="owner-avatar" loading="lazy" decoding="async">
<span class="owner-name">${this.escapeHtml(repo.owner.login)}</span>
</a>
<div class="repo-meta">
<div class="repo-language">
<span class="language-dot ${repo.language.toLowerCase()}" style="background-color: ${repo.languageColor}"></span>
<span>${this.escapeHtml(repo.language)}</span>
</div>
<div class="repo-updated" title="Last updated: ${new Date(repo.updated_at).toLocaleDateString()}">
${repo.relativeTime}
</div>
</div>
</div>