-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathscript.js
More file actions
811 lines (685 loc) · 26 KB
/
script.js
File metadata and controls
811 lines (685 loc) · 26 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
// Configuration
const REPORTS_BASE_URL = '';
let currentReport = 'bob-weekly';
// Initialize on page load
document.addEventListener('DOMContentLoaded', () => {
loadReport(currentReport);
setupNavigation();
loadLastUpdated();
});
// Setup navigation
function setupNavigation() {
const navButtons = document.querySelectorAll('.nav-btn');
navButtons.forEach(btn => {
btn.addEventListener('click', () => {
const reportName = btn.dataset.report;
switchReport(reportName, btn);
});
});
}
// Switch to a different report
function switchReport(reportName, button) {
// Update active button
document.querySelectorAll('.nav-btn').forEach(btn => {
btn.classList.remove('active');
});
button.classList.add('active');
// Load new report
currentReport = reportName;
loadReport(reportName);
}
// Load and display report
async function loadReport(reportName) {
const loadingEl = document.getElementById('loading');
const contentEl = document.getElementById('report-content');
const shareEl = document.getElementById('share-section');
// Show loading
loadingEl.style.display = 'block';
contentEl.style.display = 'none';
shareEl.style.display = 'none';
try {
// Fetch markdown file
const response = await fetch(`${REPORTS_BASE_URL}${reportName}.md`);
if (!response.ok) {
throw new Error(`Failed to load report: ${response.status}`);
}
const markdown = await response.text();
// Convert markdown to HTML
const html = marked.parse(markdown);
// Display content
contentEl.innerHTML = html;
contentEl.style.display = 'block';
shareEl.style.display = 'block';
loadingEl.style.display = 'none';
// Update dynamic OG tags
updateOpenGraphTags(reportName, markdown);
// Scroll to top
window.scrollTo({ top: 0, behavior: 'smooth' });
} catch (error) {
console.error('Error loading report:', error);
contentEl.innerHTML = `
<div style="text-align: center; padding: 2rem;">
<h2>⚠️ Error Loading Report</h2>
<p>Could not load the report. Please try again later.</p>
<p style="color: var(--text-secondary); font-size: 0.9rem; margin-top: 1rem;">
${error.message}
</p>
</div>
`;
contentEl.style.display = 'block';
loadingEl.style.display = 'none';
}
}
// Update Open Graph meta tags dynamically
function updateOpenGraphTags(reportName, markdown) {
const reportNames = {
'bob-weekly': 'Bob',
'erik-weekly': 'Erik',
'gptme-team-weekly': 'gptme Team'
};
const name = reportNames[reportName] || 'User';
const stats = extractStats(markdown);
// Update title
const titleTag = document.querySelector('meta[property="og:title"]');
if (titleTag) {
titleTag.content = `${name}'s Weekly Activity - What Did You Get Done?`;
}
// Update description with stats
const descTag = document.querySelector('meta[property="og:description"]');
if (descTag) {
let desc = `${name}'s GitHub activity: `;
const parts = [];
if (stats.commits > 0) parts.push(`${stats.commits} commits`);
if (stats.prs > 0) parts.push(`${stats.prs} PRs`);
if (stats.repos > 0) parts.push(`${stats.repos} repos`);
desc += parts.join(', ');
descTag.content = desc;
}
}
// Extract stats from markdown content
function extractStats(content) {
const commitMatch = content.match(/(\d+)\s+commits?/i);
const prMatch = content.match(/(\d+)\s+pull requests?/i);
const repoMatch = content.match(/(\d+)\s+active repositories?/i);
return {
commits: commitMatch ? parseInt(commitMatch[1]) : 0,
prs: prMatch ? parseInt(prMatch[1]) : 0,
repos: repoMatch ? parseInt(repoMatch[1]) : 0
};
}
// Load last updated time
async function loadLastUpdated() {
try {
const response = await fetch(`${REPORTS_BASE_URL}index.md`);
const text = await response.text();
// Extract timestamp from index.md
const match = text.match(/Last updated: (.+)/);
if (match) {
document.getElementById('last-updated').textContent = match[1];
}
} catch (error) {
console.error('Error loading last updated time:', error);
document.getElementById('last-updated').textContent = 'Unknown';
}
}
// Generate share text with actual stats
function getShareText() {
const reportNames = {
'bob-weekly': 'Bob',
'erik-weekly': 'Erik',
'gptme-team-weekly': 'gptme Team'
};
const name = reportNames[currentReport] || 'My';
// Parse report content for stats
const content = document.getElementById('report-content').innerText;
const stats = extractStats(content);
// Generate engaging text with stats
let text = `📊 ${name}'s week in GitHub:\n\n`;
if (stats.commits > 0) text += `💻 ${stats.commits} commits\n`;
if (stats.prs > 0) text += `🔀 ${stats.prs} pull requests\n`;
if (stats.repos > 0) text += `📦 ${stats.repos} active repos\n`;
text += '\n#WhatDidYouGetDone #GitHub #OpenSource';
return text;
}
// Show share preview modal
function showSharePreview(platform) {
const text = getShareText();
const url = window.location.href;
// Create modal HTML
const modalHTML = `
<div class="share-modal-overlay" id="shareModal">
<div class="share-modal">
<div class="share-modal-header">
<h3>📢 Share Your Week</h3>
<button class="close-modal" onclick="closeShareModal()">✕</button>
</div>
<div class="share-modal-body">
<label for="shareText">Customize your share text:</label>
<textarea id="shareText" rows="8">${text}</textarea>
<div class="share-preview">
<strong>Link:</strong> ${url}
</div>
</div>
<div class="share-modal-footer">
<button class="btn-secondary" onclick="closeShareModal()">Cancel</button>
<button class="btn-primary" onclick="confirmShare('${platform}')">
Share on ${platform}
</button>
</div>
</div>
</div>
`;
// Add modal to page
document.body.insertAdjacentHTML('beforeend', modalHTML);
}
// Close share modal
function closeShareModal() {
const modal = document.getElementById('shareModal');
if (modal) {
modal.remove();
}
}
// Confirm and execute share
function confirmShare(platform) {
const text = document.getElementById('shareText').value;
const url = window.location.href;
closeShareModal();
if (platform === 'Twitter') {
const twitterUrl = `https://twitter.com/intent/tweet?text=${encodeURIComponent(text)}&url=${encodeURIComponent(url)}`;
window.open(twitterUrl, '_blank', 'width=550,height=420');
} else if (platform === 'LinkedIn') {
const linkedInUrl = `https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(url)}`;
window.open(linkedInUrl, '_blank', 'width=550,height=420');
}
}
// Share on Twitter/X with preview
function shareOnTwitter() {
showSharePreview('Twitter');
}
// Share on LinkedIn with preview
function shareOnLinkedIn() {
showSharePreview('LinkedIn');
}
// Copy link to clipboard
async function copyLink() {
const url = window.location.href;
try {
await navigator.clipboard.writeText(url);
showCopyFeedback();
} catch (error) {
console.error('Error copying to clipboard:', error);
// Fallback for older browsers
fallbackCopyToClipboard(url);
}
}
// Show copy feedback
function showCopyFeedback() {
const copyBtn = document.querySelector('.share-btn.copy');
const originalText = copyBtn.innerHTML;
copyBtn.innerHTML = `
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<polyline points="20 6 9 17 4 12"></polyline>
</svg>
Copied!
`;
copyBtn.style.background = 'var(--success-color)';
setTimeout(() => {
copyBtn.innerHTML = originalText;
copyBtn.style.background = '';
}, 2000);
}
// Fallback copy method for older browsers
function fallbackCopyToClipboard(text) {
const textArea = document.createElement('textarea');
textArea.value = text;
textArea.style.position = 'fixed';
textArea.style.left = '-999999px';
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
try {
document.execCommand('copy');
showCopyFeedback();
} catch (error) {
console.error('Fallback copy failed:', error);
alert('Failed to copy link. Please copy manually: ' + text);
}
document.body.removeChild(textArea);
}
// Configure marked options
marked.setOptions({
breaks: true,
gfm: true
});
// Team Dashboard functionality
function setupTeamDashboard() {
const teamForm = document.getElementById('team-form');
const teamDashboard = document.getElementById('team-dashboard');
const reportContent = document.getElementById('report-content');
const shareSection = document.getElementById('share-section');
// Handle view switching
const navButtons = document.querySelectorAll('.nav-btn');
navButtons.forEach(btn => {
btn.addEventListener('click', () => {
if (btn.dataset.view === 'custom-team') {
// Show team dashboard
teamDashboard.style.display = 'block';
reportContent.style.display = 'none';
shareSection.style.display = 'none';
document.getElementById('loading').style.display = 'none';
// Update active button
document.querySelectorAll('.nav-btn').forEach(b => {
b.classList.remove('active');
});
btn.classList.add('active');
}
});
});
// Handle form submission
teamForm.addEventListener('submit', async (e) => {
e.preventDefault();
const usernames = document.getElementById('team-usernames').value
.split(',')
.map(u => u.trim())
.filter(u => u.length > 0);
const days = parseInt(document.getElementById('team-days').value);
const startDate = document.getElementById('team-start-date').value;
const endDate = document.getElementById('team-end-date').value;
const token = document.getElementById('github-token').value.trim() || null;
if (usernames.length === 0) {
alert('Please enter at least one GitHub username');
return;
}
// Show loading
const resultSection = document.getElementById('team-result');
const resultContent = document.getElementById('team-content');
resultContent.innerHTML = `
<div style="text-align: center; padding: 2rem;">
<div class="spinner"></div>
<p>Generating team report...</p>
</div>
`;
resultSection.style.display = 'block';
// Generate team report using GitHub API
try {
const report = await generateTeamReport(usernames, days, startDate, endDate, token);
const html = marked.parse(report);
resultContent.innerHTML = html;
// Update rate limit display after API calls
await updateRateLimitDisplay(token);
} catch (error) {
// Update rate limit even on error (to show if rate limited)
await updateRateLimitDisplay(token);
console.error('Error generating team report:', error);
resultContent.innerHTML = `
<div style="text-align: center; padding: 2rem;">
<h3>⚠️ Error Generating Report</h3>
<p style="margin: 1rem 0; color: var(--text-secondary);">
${error.message}
</p>
<p style="margin-top: 1.5rem; font-size: 0.9rem; color: var(--text-secondary);">
<strong>Troubleshooting:</strong>
</p>
<ul style="text-align: left; max-width: 600px; margin: 1rem auto; color: var(--text-secondary); font-size: 0.9rem;">
<li>Check that GitHub usernames are correct</li>
<li>If rate limited, try again in an hour or provide a GitHub token</li>
<li>Check the browser console for more details</li>
</ul>
</div>
`;
}
});
}
// Initialize team dashboard when page loads
document.addEventListener('DOMContentLoaded', () => {
setupTeamDashboard();
});
// GitHub API Integration
// Cache Configuration
const CACHE_MAX_AGE = 15 * 60 * 1000; // 15 minutes in milliseconds
// Cache Helper Functions
function getCacheKey(username) {
return `github_events_${username}`;
}
function getTokenHash(token) {
// Simple hash for cache invalidation when token changes
if (!token) return 'no_token';
return btoa(token.substring(0, 10)); // Hash first 10 chars
}
function getFromCache(username, tokenHash) {
try {
const cacheKey = getCacheKey(username);
const cached = localStorage.getItem(cacheKey);
if (!cached) return null;
const data = JSON.parse(cached);
const now = Date.now();
const age = now - data.timestamp;
// Invalidate if cache is too old or token changed
if (age > CACHE_MAX_AGE || data.tokenHash !== tokenHash) {
localStorage.removeItem(cacheKey);
return null;
}
return data.events;
} catch (error) {
console.warn('Cache read error:', error);
return null;
}
}
function saveToCache(username, events, tokenHash) {
try {
const cacheKey = getCacheKey(username);
const data = {
events: events,
timestamp: Date.now(),
tokenHash: tokenHash
};
localStorage.setItem(cacheKey, JSON.stringify(data));
updateCacheStatus();
} catch (error) {
console.warn('Cache write error:', error);
}
}
function getCacheInfo() {
const cacheKeys = Object.keys(localStorage).filter(key => key.startsWith('github_events_'));
const cacheItems = cacheKeys.map(key => {
try {
const data = JSON.parse(localStorage.getItem(key));
return {
username: key.replace('github_events_', ''),
timestamp: data.timestamp,
age: Date.now() - data.timestamp
};
} catch {
return null;
}
}).filter(item => item !== null);
return cacheItems;
}
function updateCacheStatus() {
const cacheStatusEl = document.getElementById('cache-status');
const cacheTextEl = document.getElementById('cache-status-text');
if (!cacheStatusEl || !cacheTextEl) return;
const cacheItems = getCacheInfo();
if (cacheItems.length === 0) {
cacheStatusEl.classList.add('empty');
cacheTextEl.textContent = 'No cached data';
} else {
cacheStatusEl.classList.remove('empty');
// Find most recent cache update
const mostRecent = Math.max(...cacheItems.map(item => item.timestamp));
const ageMinutes = Math.floor((Date.now() - mostRecent) / 60000);
const ageText = ageMinutes === 0 ? 'just now' :
ageMinutes === 1 ? '1 minute ago' :
ageMinutes < 60 ? `${ageMinutes} minutes ago` :
`${Math.floor(ageMinutes / 60)} hours ago`;
cacheTextEl.textContent = `${cacheItems.length} user${cacheItems.length > 1 ? 's' : ''} cached (updated ${ageText})`;
}
}
function clearAllCache() {
const cacheKeys = Object.keys(localStorage).filter(key => key.startsWith('github_events_'));
cacheKeys.forEach(key => localStorage.removeItem(key));
updateCacheStatus();
console.log('Cache cleared');
}
async function fetchGitHubEvents(username, token = null) {
const tokenHash = getTokenHash(token);
// Try to get from cache first
const cachedEvents = getFromCache(username, tokenHash);
if (cachedEvents) {
console.log(`Using cached events for ${username}`);
return cachedEvents;
}
// Cache miss - fetch from API
console.log(`Fetching fresh events for ${username}`);
const headers = {
'Accept': 'application/vnd.github.v3+json'
};
if (token) {
headers['Authorization'] = `token ${token}`;
}
const response = await fetch(`https://api.github.com/users/${username}/events`, {
headers: headers
});
if (!response.ok) {
if (response.status === 404) {
throw new Error(`User "${username}" not found`);
} else if (response.status === 403) {
throw new Error('GitHub API rate limit exceeded. Please try again later or provide a GitHub token.');
}
throw new Error(`GitHub API error: ${response.status}`);
}
const events = await response.json();
// Save to cache
saveToCache(username, events, tokenHash);
return events;
}
async function generateTeamReport(usernames, days, startDate, endDate, token = null) {
// Calculate date range
const now = new Date();
const start = startDate ? new Date(startDate) : new Date(now.getTime() - days * 24 * 60 * 60 * 1000);
const end = endDate ? new Date(endDate) : now;
// Fetch events for all users
const allEvents = [];
const errors = [];
for (let i = 0; i < usernames.length; i++) {
const username = usernames[i];
// Update progress indicator
const resultContent = document.getElementById('team-content');
resultContent.innerHTML = `
<div style="text-align: center; padding: 2rem;">
<div class="spinner"></div>
<p>Generating team report...</p>
<p style="color: var(--text-secondary); margin-top: 1rem;">
Fetching activity for <strong>${username}</strong> (${i + 1}/${usernames.length})
</p>
</div>
`;
try {
const events = await fetchGitHubEvents(username, token);
allEvents.push({ username, events });
} catch (error) {
errors.push({ username, error: error.message });
}
}
if (allEvents.length === 0) {
throw new Error('Failed to fetch activity for all users:\n' + errors.map(e => `- ${e.username}: ${e.error}`).join('\n'));
}
// Process events
const commits = [];
const prs = [];
for (const { username, events } of allEvents) {
for (const event of events) {
const eventDate = new Date(event.created_at);
if (eventDate < start || eventDate > end) {
continue;
}
if (event.type === 'PushEvent') {
for (const commit of event.payload.commits || []) {
commits.push({
username,
repo: event.repo.name,
message: commit.message,
sha: commit.sha.substring(0, 7),
date: eventDate
});
}
} else if (event.type === 'PullRequestEvent') {
const pr = event.payload.pull_request;
prs.push({
username,
repo: event.repo.name,
number: pr.number,
title: pr.title,
state: pr.state,
action: event.payload.action,
date: eventDate
});
}
}
}
// Generate markdown report
let report = `# Team Activity Report\n\n`;
report += `**Period:** ${start.toLocaleDateString()} - ${end.toLocaleDateString()}\n`;
report += `**Team Members:** ${usernames.join(', ')}\n\n`;
if (errors.length > 0) {
report += `## ⚠️ Warnings\n\n`;
for (const error of errors) {
report += `- ${error.username}: ${error.error}\n`;
}
report += `\n`;
}
// Commits section
report += `## 📝 Commits (${commits.length})\n\n`;
if (commits.length > 0) {
const commitsByRepo = {};
for (const commit of commits) {
if (!commitsByRepo[commit.repo]) {
commitsByRepo[commit.repo] = [];
}
commitsByRepo[commit.repo].push(commit);
}
for (const [repo, repoCommits] of Object.entries(commitsByRepo)) {
report += `### ${repo} (${repoCommits.length} commits)\n\n`;
for (const commit of repoCommits.slice(0, 10)) {
const message = commit.message.split('\n')[0];
report += `- **${commit.username}** \`${commit.sha}\` ${message}\n`;
}
if (repoCommits.length > 10) {
report += `- ... and ${repoCommits.length - 10} more commits\n`;
}
report += `\n`;
}
} else {
report += `No commits found in this period.\n\n`;
}
// PRs section
report += `## 🔀 Pull Requests (${prs.length})\n\n`;
if (prs.length > 0) {
const prsByRepo = {};
for (const pr of prs) {
if (!prsByRepo[pr.repo]) {
prsByRepo[pr.repo] = [];
}
prsByRepo[pr.repo].push(pr);
}
for (const [repo, repoPrs] of Object.entries(prsByRepo)) {
report += `### ${repo}\n\n`;
for (const pr of repoPrs) {
const stateIcon = pr.state === 'open' ? '🔄' : pr.state === 'closed' ? '✅' : '❌';
report += `- ${stateIcon} **${pr.username}** #${pr.number}: ${pr.title}\n`;
}
report += `\n`;
}
} else {
report += `No pull requests found in this period.\n\n`;
}
return report;
}
// Rate Limit Management
async function fetchRateLimit(token = null) {
const headers = {
'Accept': 'application/vnd.github.v3+json'
};
if (token) {
headers['Authorization'] = `token ${token}`;
}
try {
const response = await fetch('https://api.github.com/rate_limit', { headers });
const data = await response.json();
return data.rate;
} catch (error) {
console.error('Error fetching rate limit:', error);
return null;
}
}
function formatRateLimitDisplay(rateLimit) {
if (!rateLimit) {
return 'Unable to fetch rate limit info';
}
const { limit, remaining, reset } = rateLimit;
const resetDate = new Date(reset * 1000);
const now = new Date();
const minutesUntilReset = Math.ceil((resetDate - now) / 1000 / 60);
let timeText;
if (minutesUntilReset < 60) {
timeText = `${minutesUntilReset} minute${minutesUntilReset !== 1 ? 's' : ''}`;
} else {
const hours = Math.floor(minutesUntilReset / 60);
timeText = `${hours} hour${hours !== 1 ? 's' : ''}`;
}
const percentage = (remaining / limit * 100).toFixed(0);
const authenticated = limit > 60 ? '🔐 Authenticated' : '🔓 Unauthenticated';
return `
<span class="rate-limit-remaining">${remaining}/${limit}</span> requests remaining
<span class="rate-limit-reset">(resets in ${timeText})</span>
<span class="rate-limit-auth">${authenticated}</span>
`;
}
function getRateLimitClass(rateLimit) {
if (!rateLimit) return '';
const percentage = (rateLimit.remaining / rateLimit.limit * 100);
if (percentage < 10) return 'danger';
if (percentage < 30) return 'warning';
return '';
}
async function updateRateLimitDisplay(token = null) {
const display = document.getElementById('rate-limit-display');
const textElement = display.querySelector('.rate-limit-text');
if (!display || !textElement) return;
// Show loading state
textElement.innerHTML = 'Checking rate limit...';
// Fetch rate limit
const rateLimit = await fetchRateLimit(token);
// Update display
if (rateLimit) {
textElement.innerHTML = formatRateLimitDisplay(rateLimit);
// Update display class based on remaining requests
display.className = 'rate-limit-display ' + getRateLimitClass(rateLimit);
} else {
textElement.innerHTML = 'Unable to check rate limit';
display.className = 'rate-limit-display';
}
}
// Initialize rate limit display when team dashboard is shown
function initializeRateLimitDisplay() {
const refreshButton = document.getElementById('refresh-rate-limit');
const tokenInput = document.getElementById('github-token');
if (refreshButton) {
refreshButton.addEventListener('click', () => {
const token = tokenInput?.value?.trim() || null;
updateRateLimitDisplay(token);
});
}
// Update rate limit when token is entered/changed
if (tokenInput) {
tokenInput.addEventListener('change', () => {
const token = tokenInput.value?.trim() || null;
updateRateLimitDisplay(token);
});
}
// Initial fetch
updateRateLimitDisplay();
}
// Initialize cache status display
function initializeCacheStatus() {
const clearButton = document.getElementById('clear-cache');
if (clearButton) {
clearButton.addEventListener('click', () => {
if (confirm('Clear all cached GitHub data? This will require fresh API calls for future reports.')) {
clearAllCache();
}
});
}
// Initial update
updateCacheStatus();
}
// Call initialization functions when DOM is ready
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', () => {
initializeRateLimitDisplay();
initializeCacheStatus();
});
} else {
initializeRateLimitDisplay();
initializeCacheStatus();
}