-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
952 lines (796 loc) · 33.6 KB
/
Copy pathscript.js
File metadata and controls
952 lines (796 loc) · 33.6 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
// Cache Manager for localStorage with TTL
class CacheManager {
constructor(ttlMinutes = 60) {
this.ttl = ttlMinutes * 60 * 1000; // Convert to milliseconds
}
set(key, data) {
try {
localStorage.setItem(key, JSON.stringify({
data,
timestamp: Date.now()
}));
} catch (e) {
console.warn('Failed to cache data:', e);
}
}
get(key) {
try {
const cached = localStorage.getItem(key);
if (!cached) return null;
const { data, timestamp } = JSON.parse(cached);
// Check if cache is expired
if (Date.now() - timestamp > this.ttl) {
localStorage.removeItem(key);
return null;
}
return data;
} catch (e) {
console.warn('Failed to retrieve cached data:', e);
return null;
}
}
clear(key) {
try {
localStorage.removeItem(key);
} catch (e) {
console.warn('Failed to clear cache:', e);
}
}
clearAll() {
try {
// Clear all cache entries (those starting with 'gh_cache_')
Object.keys(localStorage).forEach(key => {
if (key.startsWith('gh_cache_')) {
localStorage.removeItem(key);
}
});
} catch (e) {
console.warn('Failed to clear all cache:', e);
}
}
}
class GitHubDashboard {
constructor() {
this.currentUser = null;
this.githubToken = this.loadToken();
this.pendingRequest = null;
this.isLoadingFromURL = false;
this.cache = new CacheManager(60); // 60 minute TTL
this.loadMoreDebounce = {}; // Debounce tracking for each PR type
this.userData = {
profile: null,
repos: [],
openPRs: [],
discardedPRs: [],
mergedPRs: []
};
// Pagination state for each PR type
this.paginationState = {
openPRs: { page: 1, hasMore: true, loading: false, totalCount: 0 },
discardedPRs: { page: 1, hasMore: true, loading: false, totalCount: 0 },
mergedPRs: { page: 1, hasMore: true, loading: false, totalCount: 0 }
};
// Constants for PR states
this.PR_STATES = {
open: { emoji: '🟡', label: 'open', query: 'state:open' },
discarded: { emoji: '🔴', label: 'discarded', query: 'state:closed+-is:merged' },
merged: { emoji: '🟢', label: 'merged', query: 'state:closed+is:merged' }
};
// Grid mapping constants
this.PR_GRID_MAP = {
'openPRs': 'openPRsGrid',
'discardedPRs': 'discardedPRsGrid',
'mergedPRs': 'mergedPRsGrid'
};
// PR type to state mapping
this.PR_TYPE_TO_STATE = {
'openPRs': 'open',
'discardedPRs': 'discarded',
'mergedPRs': 'merged'
};
// Virtualization settings
this.ITEMS_PER_PAGE = 100;
this.RENDER_BUFFER = 20; // Number of items to render beyond viewport
this.initializeEventListeners();
this.updateTokenIndicator();
this.setupBrowserNavigation();
this.loadUsernameFromURL();
}
// Sanitize data before caching to reduce localStorage usage
sanitizeDataForCache(userData) {
const sanitized = {
profile: null,
openPRs: [],
discardedPRs: [],
mergedPRs: []
};
// Keep only essential profile fields
if (userData.profile) {
sanitized.profile = {
login: userData.profile.login,
avatar_url: userData.profile.avatar_url,
name: userData.profile.name,
created_at: userData.profile.created_at,
location: userData.profile.location,
company: userData.profile.company
};
}
// Keep only essential PR fields
const sanitizePR = (pr) => ({
created_at: pr.created_at,
html_url: pr.html_url,
title: pr.title
});
sanitized.openPRs = userData.openPRs?.map(sanitizePR) || [];
sanitized.discardedPRs = userData.discardedPRs?.map(sanitizePR) || [];
sanitized.mergedPRs = userData.mergedPRs?.map(sanitizePR) || [];
return sanitized;
}
// Restore full structure from sanitized cache
restoreFromCache(cachedData) {
this.userData = {
profile: cachedData.profile,
repos: [], // Empty array when loading from cache
openPRs: cachedData.openPRs || [],
discardedPRs: cachedData.discardedPRs || [],
mergedPRs: cachedData.mergedPRs || []
};
this.syncPaginationStateFromCache();
}
syncPaginationStateFromCache() {
Object.keys(this.paginationState).forEach(prType => {
const cachedItems = this.userData[prType] || [];
const pagesLoaded = Math.floor(cachedItems.length / this.ITEMS_PER_PAGE);
const hasFullPage = cachedItems.length === 0 || cachedItems.length % this.ITEMS_PER_PAGE === 0;
this.paginationState[prType] = {
page: pagesLoaded + 1,
hasMore: hasFullPage,
loading: false,
totalCount: 0
};
});
}
// URL parsing helper methods
extractOrgName(url) {
return url.split('/')[3]; // Extract org from https://github.com/org/repo/pull/123
}
extractRepoName(url) {
return url.split('/')[4]; // Extract repo from https://github.com/org/repo/pull/123
}
extractPRNumber(url) {
return url.split('/').pop(); // Extract PR number from URL
}
// Get total count for a PR type (from API or loaded data)
getTotalCount(prType) {
const state = this.paginationState[prType];
return state.totalCount > 0 ? state.totalCount : this.userData[prType].length;
}
loadToken() {
try {
return localStorage.getItem('github_token') || null;
} catch (e) {
console.warn('Failed to load token from localStorage:', e);
return null;
}
}
saveToken(token) {
try {
if (token) {
localStorage.setItem('github_token', token);
} else {
localStorage.removeItem('github_token');
}
} catch (e) {
console.warn('Failed to save token to localStorage:', e);
}
}
updateTokenIndicator() {
const indicator = document.getElementById('tokenIndicator');
if (indicator) {
if (this.githubToken) {
indicator.style.display = 'flex';
} else {
indicator.style.display = 'none';
}
}
}
getUsernameFromURL() {
// 1. If local file, strictly use hash
if (window.location.protocol === 'file:') {
const hash = window.location.hash;
if (hash && hash.startsWith('#')) {
return hash.substring(1).split('/')[0] || null;
}
return null;
}
// 2. If on web server (GitHub Pages), strictly use path
const path = window.location.pathname;
const segments = path.split('/').filter(Boolean);
// On GitHub Pages: /opensource/username (segments[0] is repo name)
if (segments.length >= 2 && segments[0].toLowerCase() === 'opensource') {
return segments[1];
}
return null;
}
updateURL(username) {
if (!username) return;
if (window.location.protocol === 'file:') {
// Use hash for local file support
window.location.hash = username;
} else {
// Use clean path for hosted version
const newPath = `/opensource/${username}`;
// Update if path is different OR if there's an unnecessary hash to clear
if (window.location.pathname !== newPath || window.location.hash) {
window.history.pushState({ username }, '', newPath);
}
}
}
loadUsernameFromURL() {
const username = this.getUsernameFromURL();
if (username) {
// Prefill the search box
document.getElementById('usernameInput').value = username;
// Set flag to prevent URL update during initial load
this.isLoadingFromURL = true;
// Automatically trigger analysis
this.analyzeUser();
}
}
setupBrowserNavigation() {
// Handle hash changes (back/forward or manual editing)
window.addEventListener('hashchange', () => {
const username = this.getUsernameFromURL();
if (username && username !== this.currentUser) {
document.getElementById('usernameInput').value = username;
this.isLoadingFromURL = true;
this.analyzeUser();
}
});
}
initializeEventListeners() {
const handlers = [
{ id: 'analyzeBtn', event: 'click', handler: () => this.analyzeUser() },
{ id: 'usernameInput', event: 'keypress', handler: (e) => e.key === 'Enter' && this.analyzeUser() },
{ id: 'retryBtn', event: 'click', handler: () => this.analyzeUser() },
{ id: 'submitTokenBtn', event: 'click', handler: () => this.handleTokenSubmit() },
{ id: 'cancelTokenBtn', event: 'click', handler: () => this.hideTokenModal() },
{ id: 'clearTokenBtn', event: 'click', handler: () => this.clearToken() }
];
handlers.forEach(({ id, event, handler }) => {
document.getElementById(id).addEventListener(event, handler);
});
// Token input enter key
document.getElementById('tokenInput').addEventListener('keypress', (e) => {
if (e.key === 'Enter') this.handleTokenSubmit();
});
// Tab switching
document.querySelectorAll('.tab').forEach(tab => {
tab.addEventListener('click', () => this.switchTab(tab.dataset.tab));
});
}
async analyzeUser() {
const username = document.getElementById('usernameInput').value.trim();
if (!username) {
this.showError('Please enter a GitHub username', '');
return;
}
this.currentUser = username;
this.setState('loading');
// Update URL with the username (skip if loading from URL initially)
if (!this.isLoadingFromURL) {
this.updateURL(username);
}
this.isLoadingFromURL = false;
try {
await this.fetchAllData(username);
this.setState('dashboard');
this.renderDashboard();
} catch (error) {
console.error('Error fetching data:', error);
this.showError('Failed to fetch GitHub data', error.message);
}
}
async fetchAllData(username) {
const cacheKey = `gh_cache_${username}`;
// Try to get cached data
const cachedData = this.cache.get(cacheKey);
if (cachedData) {
console.log('Loading from cache for user:', username);
this.restoreFromCache(cachedData.userData);
return; // Skip API calls!
}
console.log('Fetching fresh data for user:', username);
const baseURL = 'https://api.github.com';
// Fetch user profile
const profileResponse = await this.fetchWithAuth(`${baseURL}/users/${username}`);
if (!profileResponse.ok) {
throw new Error(profileResponse.status === 404 ? 'User not found' : 'Failed to fetch user profile');
}
this.userData.profile = await profileResponse.json();
// Fetch repositories
const reposResponse = await this.fetchWithAuth(`${baseURL}/users/${username}/repos?type=source&sort=updated&per_page=100`);
if (!reposResponse.ok) {
throw new Error('Failed to fetch repositories');
}
this.userData.repos = await reposResponse.json();
// Fetch PRs (using search API)
await this.fetchPRs(username);
// Cache the complete data after fetching (sanitized to reduce size)
this.cache.set(cacheKey, {
userData: this.sanitizeDataForCache(this.userData)
});
}
async fetchPRs(username) {
// Reset pagination state and data for initial load
this.resetPaginationState();
this.userData.openPRs = [];
this.userData.discardedPRs = [];
this.userData.mergedPRs = [];
const baseURL = 'https://api.github.com/search/issues';
const prTypes = ['openPRs', 'discardedPRs', 'mergedPRs'];
const states = Object.keys(this.PR_STATES);
// Fetch first page for all PR types in parallel
await Promise.all(states.map(async (state, index) => {
await this.fetchPRPage(username, prTypes[index], state, baseURL);
}));
}
async fetchPRPage(username, prType, state, baseURL = 'https://api.github.com/search/issues') {
const paginationState = this.paginationState[prType];
// Don't fetch if already loading or no more results
if (paginationState.loading || !paginationState.hasMore) {
return;
}
paginationState.loading = true;
this.updateLoadMoreButton(prType);
try {
const query = `author:${username}+-owner:${username}+type:pr+${this.PR_STATES[state].query}`;
const url = `${baseURL}?q=${query}&per_page=${this.ITEMS_PER_PAGE}&page=${paginationState.page}`;
const response = await this.fetchWithAuth(url);
if (response.ok) {
const data = await response.json();
const newItems = data.items || [];
const existingUrls = new Set(this.userData[prType].map(pr => pr.html_url));
const uniqueNewItems = newItems.filter(pr => !existingUrls.has(pr.html_url));
// Update total count
paginationState.totalCount = data.total_count || 0;
// Append new items to existing data
this.userData[prType] = [...this.userData[prType], ...uniqueNewItems];
// Check if there are more pages
// GitHub Search API caps at 1000 results (10 pages)
const hasMorePages = newItems.length === this.ITEMS_PER_PAGE &&
paginationState.page < 10 &&
this.userData[prType].length < paginationState.totalCount;
paginationState.hasMore = hasMorePages;
paginationState.page++;
// Progressively render the new items
this.renderPRGridProgressive(prType, state);
this.updateTabCounts();
this.renderInsights();
}
} catch (e) {
console.warn(`Failed to fetch ${state} PRs page ${paginationState.page}:`, e);
} finally {
paginationState.loading = false;
this.updateLoadMoreButton(prType);
}
}
resetPaginationState() {
Object.keys(this.paginationState).forEach(key => {
this.paginationState[key] = { page: 1, hasMore: true, loading: false, totalCount: 0 };
});
}
async loadMorePRs(prType) {
// Debounce: prevent rapid clicking
if (this.loadMoreDebounce[prType]) {
return;
}
this.loadMoreDebounce[prType] = true;
setTimeout(() => {
this.loadMoreDebounce[prType] = false;
}, 300); // 300ms debounce
await this.fetchPRPage(this.currentUser, prType, this.PR_TYPE_TO_STATE[prType]);
// Update cache with new data (sanitized to reduce size)
const cacheKey = `gh_cache_${this.currentUser}`;
this.cache.set(cacheKey, {
userData: this.sanitizeDataForCache(this.userData)
});
}
setState(state) {
const states = {
loading: { loading: 'block', error: 'none', dashboard: 'none', button: true },
error: { loading: 'none', error: 'block', dashboard: 'none', button: false },
dashboard: { loading: 'none', error: 'none', dashboard: 'block', button: false }
};
const config = states[state];
document.getElementById('loadingState').style.display = config.loading;
document.getElementById('errorState').style.display = config.error;
document.getElementById('dashboardContent').style.display = config.dashboard;
document.getElementById('analyzeBtn').disabled = config.button;
}
showError(title, message) {
document.getElementById('errorTitle').textContent = title;
document.getElementById('errorMessage').textContent = message;
this.setState('error');
}
renderDashboard() {
this.renderUserProfile();
this.renderInsights();
this.renderPRs();
this.updateMetaTags();
}
updateMetaTags() {
const profile = this.userData.profile;
if (!profile) return;
const username = profile.login;
const displayName = profile.name || username;
// Use actual total counts from API, not just loaded data
const totalPRs = this.getTotalCount('openPRs') + this.getTotalCount('discardedPRs') + this.getTotalCount('mergedPRs');
const mergedPRs = this.getTotalCount('mergedPRs');
// Create dynamic title and description
const pageTitle = `@${username} - ${totalPRs} Open Source Contributions | ForkLift`;
const pageDescription = `${displayName} has contributed ${totalPRs} pull requests to open source projects on GitHub, with ${mergedPRs} successfully merged. Track your GitHub contributions with ForkLift.`;
const pageUrl = `https://ankitpandey2708.github.io/opensource/${username}`;
const profileImage = profile.avatar_url || 'https://ankitpandey2708.github.io/opensource/og-image.png';
// Update document title
document.title = pageTitle;
// Update meta description
this.updateMetaTag('meta-description', 'content', pageDescription);
// Update canonical URL
this.updateMetaTag('canonical-url', 'href', pageUrl);
// Update Open Graph tags
this.updateMetaTag('og-title', 'content', pageTitle);
this.updateMetaTag('og-description', 'content', pageDescription);
this.updateMetaTag('og-url', 'content', pageUrl);
this.updateMetaTag('og-image', 'content', profileImage);
// Update Twitter Card tags
this.updateMetaTag('twitter-title', 'content', pageTitle);
this.updateMetaTag('twitter-description', 'content', pageDescription);
this.updateMetaTag('twitter-image', 'content', profileImage);
}
updateMetaTag(id, attribute, value) {
const element = document.getElementById(id);
if (element) {
element.setAttribute(attribute, value);
}
}
renderUserProfile() {
const profile = this.userData.profile;
const joinDate = new Date(profile.created_at).toLocaleDateString('en-US', {
year: 'numeric',
month: 'long'
});
const metaItems = [
{ icon: '📅', value: `Joined ${joinDate}`, show: true },
{ icon: '📍', value: profile.location, show: !!profile.location },
{ icon: '🏢', value: profile.company, show: !!profile.company }
];
const metaHTML = metaItems
.filter(item => item.show)
.map(item => `<span>${item.icon} ${item.value}</span>`)
.join('');
document.getElementById('userProfile').innerHTML = `
<img src="${profile.avatar_url}" alt="${profile.name || profile.login}" class="user-avatar">
<div class="user-info">
<h2>@${profile.login}</h2>
<div class="user-meta">${metaHTML}</div>
</div>
`;
}
renderInsights() {
// Use actual total counts from API, not just loaded data
const openTotal = this.getTotalCount('openPRs');
const discardedTotal = this.getTotalCount('discardedPRs');
const mergedTotal = this.getTotalCount('mergedPRs');
const totalPRs = openTotal + discardedTotal + mergedTotal;
const mergeRate = totalPRs > 0 ? ((mergedTotal / totalPRs) * 100).toFixed(1) : 0;
// Toggle section visibility
const showEncouragement = totalPRs === 0;
this.toggleElement('encouragementSection', showEncouragement);
this.toggleElement('prsSection', totalPRs > 0);
if (showEncouragement) {
this.personalizeEncouragement();
}
const insights = document.getElementById('insights');
const shouldShowInsights = totalPRs > 0;
if (!shouldShowInsights) {
insights.style.display = 'none';
return;
}
const insightItems = [
{ label: 'Merge Rate', value: `${mergeRate}%`, show: totalPRs > 0 },
{ label: 'Total Contributions', value: totalPRs, show: totalPRs > 0 }
];
const insightsHTML = insightItems
.filter(item => item.show)
.map(item => `<span>${item.label}: ${item.value}</span>`)
.join('');
insights.style.display = 'block';
insights.innerHTML = `
<div class="insight-stats">${insightsHTML}</div>
`;
}
personalizeEncouragement() {
const profile = this.userData.profile;
if (!profile) return;
const fullName = profile.name || profile.login;
const name = fullName.split(' ')[0];
const createdAt = new Date(profile.created_at);
const now = new Date();
// Calculate diff in years and months
let years = now.getFullYear() - createdAt.getFullYear();
let months = now.getMonth() - createdAt.getMonth();
if (months < 0 || (months === 0 && now.getDate() < createdAt.getDate())) {
years--;
months += 12;
}
const subtitle = document.getElementById('encouragementSubtitle');
if (subtitle) {
let message = '';
if (years >= 1) {
message = `Hey ${name}, it's been almost ${years} ${years === 1 ? 'year' : 'years'} since you joined the GitHub community! Why not make today the day for your 1st contribution?`;
} else {
const displayMonths = months || 1; // Default to 1 month if brand new
message = `Hey ${name}, you've been on GitHub for ${displayMonths} ${displayMonths === 1 ? 'month' : 'months'} now. Taking the leap into open source is a massive milestone—why not start with a small contribution today?`;
}
subtitle.textContent = `${message}`;
}
}
updateTabCounts() {
const getCountText = (prType) => {
const count = this.userData[prType].length;
const state = this.paginationState[prType];
if (state.totalCount > count) {
return `${count}/${state.totalCount}`;
}
return count;
};
document.getElementById('openCount').textContent = getCountText('openPRs');
document.getElementById('discardedCount').textContent = getCountText('discardedPRs');
document.getElementById('mergedCount').textContent = getCountText('mergedPRs');
}
renderPRs() {
const prGrids = [
{ gridId: 'openPRsGrid', prs: this.userData.openPRs, state: 'open', prType: 'openPRs' },
{ gridId: 'discardedPRsGrid', prs: this.userData.discardedPRs, state: 'discarded', prType: 'discardedPRs' },
{ gridId: 'mergedPRsGrid', prs: this.userData.mergedPRs, state: 'merged', prType: 'mergedPRs' }
];
prGrids.forEach(({ gridId, prs, state, prType }) => {
this.renderPRGrid(gridId, prs, state);
this.addLoadMoreButton(gridId, prType);
});
this.updateTabCounts();
}
renderPRGridProgressive(prType, state) {
const gridId = this.PR_GRID_MAP[prType];
const prs = this.userData[prType];
// Full re-render with updated data
this.renderPRGrid(gridId, prs, state);
this.addLoadMoreButton(gridId, prType);
}
// Helper method to render a single PR card
renderPRCard(pr, state) {
const repoName = this.extractRepoName(pr.html_url);
const prNumber = this.extractPRNumber(pr.html_url);
const createdDate = new Date(pr.created_at).toLocaleDateString();
return `
<a href="${pr.html_url}" target="_blank" class="item-card">
<div class="item-title">
${repoName} #${prNumber}
<span class="pr-state ${state}">${state.charAt(0).toUpperCase() + state.slice(1)}</span>
</div>
<p class="item-description">${pr.title}</p>
<div class="item-meta">
<span class="meta-item">Created ${createdDate}</span>
</div>
</a>
`;
}
renderPRGrid(gridId, prs, state) {
const grid = document.getElementById(gridId);
const stateConfig = this.PR_STATES[state];
if (prs.length === 0) {
grid.innerHTML = `
<div class="empty-state">
<div class="empty-state-icon">${stateConfig.emoji}</div>
<h4>No ${stateConfig.label} pull requests</h4>
<p>No ${stateConfig.label} pull requests found for this user.</p>
</div>
`;
return;
}
// Group PRs by organization
const groupedPRs = prs.reduce((groups, pr) => {
const orgName = this.extractOrgName(pr.html_url);
if (!groups[orgName]) groups[orgName] = [];
groups[orgName].push(pr);
return groups;
}, {});
// Sort organizations by PR count (descending) and separate
const sortedOrgs = Object.entries(groupedPRs)
.sort((a, b) => b[1].length - a[1].length);
const multiPROrgs = sortedOrgs.filter(([_, orgPRs]) => orgPRs.length > 1);
const singlePROrgs = sortedOrgs.filter(([_, orgPRs]) => orgPRs.length === 1);
let htmlContent = '';
// Render organizations with 2+ PRs (with org headers)
htmlContent += multiPROrgs.map(([orgName, orgPRs]) => {
const itemsHTML = orgPRs.map(pr => this.renderPRCard(pr, state)).join('');
return `
<div class="org-group">
<div class="org-header">
<span class="org-icon">🏢</span>
<span class="org-name">${orgName}</span>
<span class="pr-count">${orgPRs.length} PRs</span>
</div>
<div class="items-grid">
${itemsHTML}
</div>
</div>
`;
}).join('');
// Render "Other Contributions" section for single-PR orgs
if (singlePROrgs.length > 0) {
const singlePRsHTML = singlePROrgs.map(([orgName, orgPRs]) => {
const pr = orgPRs[0];
return this.renderPRCard(pr, state);
}).join('');
htmlContent += `
<div class="other-contributions">
<div class="other-contributions-header">
<span class="section-line"></span>
<span class="section-text">Other Contributions</span>
<span class="section-line"></span>
</div>
<div class="items-grid">
${singlePRsHTML}
</div>
</div>
`;
}
grid.innerHTML = htmlContent;
}
addLoadMoreButton(gridId, prType) {
const grid = document.getElementById(gridId);
const paginationState = this.paginationState[prType];
// Remove existing button if present
const existingButton = grid.querySelector('.load-more-container');
if (existingButton) {
existingButton.remove();
}
// Only add button if there are more items to load
if (paginationState.hasMore || paginationState.loading) {
const buttonContainer = document.createElement('div');
buttonContainer.className = 'load-more-container';
buttonContainer.innerHTML = `
<button class="load-more-btn" data-pr-type="${prType}" ${paginationState.loading ? 'disabled' : ''}>
${paginationState.loading ?
'<span class="loading-spinner"></span> Loading...' :
'Load More'
}
</button>
`;
grid.appendChild(buttonContainer);
// Add click handler
const button = buttonContainer.querySelector('.load-more-btn');
button.addEventListener('click', () => this.loadMorePRs(prType));
}
}
updateLoadMoreButton(prType) {
const gridId = this.PR_GRID_MAP[prType];
this.addLoadMoreButton(gridId, prType);
}
switchTab(tabName) {
this.toggleClass('.tab', 'active', `[data-tab="${tabName}"]`);
this.toggleClass('.tab-content', 'active', `#${tabName}Content`);
}
toggleClass(selector, className, activeSelector) {
document.querySelectorAll(selector).forEach(el => el.classList.remove(className));
const activeEl = document.querySelector(activeSelector);
if (activeEl) activeEl.classList.add(className);
}
toggleElement(id, show) {
document.getElementById(id).style.display = show ? 'block' : 'none';
}
showTokenModal(errorMessage = '') {
const modal = document.getElementById('tokenModal');
const input = document.getElementById('tokenInput');
const error = document.getElementById('tokenError');
modal.classList.add('active');
input.value = '';
input.focus();
if (errorMessage) {
error.textContent = errorMessage;
error.style.display = 'block';
} else {
error.style.display = 'none';
}
}
hideTokenModal() {
document.getElementById('tokenModal').classList.remove('active');
document.getElementById('tokenError').style.display = 'none';
this.pendingRequest = null;
}
handleTokenSubmit() {
const input = document.getElementById('tokenInput');
const errorContainer = document.getElementById('tokenError');
const token = input.value.trim();
// Basic validation
if (!token) {
errorContainer.textContent = 'Please enter a GitHub token';
errorContainer.style.display = 'block';
return;
}
if (token.length < 20) {
errorContainer.textContent = 'Token seems too short. Please check it.';
errorContainer.style.display = 'block';
return;
}
this.githubToken = token;
this.saveToken(token);
this.updateTokenIndicator();
errorContainer.style.display = 'none';
// Clear cache when token changes since data might be different
this.cache.clearAll();
// Retry the pending request
if (this.pendingRequest) {
this.pendingRequest();
}
}
clearToken() {
this.githubToken = null;
this.saveToken(null);
this.updateTokenIndicator();
// Clear cache when token changes since data might be different
this.cache.clearAll();
}
getFetchHeaders() {
const headers = {
'Accept': 'application/vnd.github.v3+json'
};
if (this.githubToken) {
// Using Bearer prefix as it is preferred for modern PATs
headers['Authorization'] = `Bearer ${this.githubToken}`;
}
return headers;
}
async fetchWithAuth(url) {
const response = await fetch(url, {
headers: this.getFetchHeaders()
});
if ((response.status === 401 || response.status === 403)) {
// If we have a token and it failed, it might be expired/invalid
if (this.githubToken) {
console.warn(`Request failed with ${response.status}. Clearing token and retrying.`);
this.clearToken();
}
return new Promise((resolve, reject) => {
this.pendingRequest = async () => {
try {
const retryResponse = await fetch(url, {
headers: this.getFetchHeaders()
});
if (retryResponse.ok) {
this.hideTokenModal();
resolve(retryResponse);
} else {
// If it still fails, show error in modal
this.showTokenModal(`Request failed (${retryResponse.status}). Please check your token.`);
}
} catch (error) {
this.showTokenModal('Network error. Please try again.');
reject(error);
}
};
const message = response.status === 403
? 'API rate limit reached or access denied.'
: 'Your GitHub token is invalid or expired.';
this.showTokenModal(`${message} Please provide a valid token.`);
});
}
return response;
}
}
// Initialize the dashboard when the page loads
document.addEventListener('DOMContentLoaded', () => {
new GitHubDashboard();
});