-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshared.mjs
More file actions
1161 lines (983 loc) · 40.2 KB
/
shared.mjs
File metadata and controls
1161 lines (983 loc) · 40.2 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 API configuration
const GITHUB_API_BASE = 'https://api.github.com';
// Cache configuration (1 hour default)
const CACHE_DURATION_MS = 60 * 60 * 1000;
const CACHE_KEY_PREFIX = 'github_cache_';
// State
let githubToken = '';
/**
* Get repositories from query string
*/
export function getRepositoriesFromQueryString() {
const params = new URLSearchParams(window.location.search);
const reposParam = params.get('repos');
if (reposParam) {
return reposParam.split(/[,|]/).map(r => r.trim()).filter(r => r);
}
return null;
}
/**
* Set the GitHub token
*/
export function setGitHubToken(token) {
githubToken = token;
}
/**
* Generate a consistent color for a repository name
*/
export function getRepoColor(repoName) {
// Better hash function with more distribution
// Use golden ratio to spread values across the spectrum
let hash = 0;
for (let i = 0; i < repoName.length; i++) {
const char = repoName.charCodeAt(i);
hash = ((hash << 5) - hash) + char;
hash = hash & hash; // Convert to 32bit integer
}
// Use golden ratio (0.618033988749895) for better distribution
const goldenRatio = 0.618033988749895;
const hue = (Math.abs(hash) * goldenRatio * 360) % 360;
// Use high saturation and moderate lightness for vibrant colors
// Return as HSL with moderate opacity for background
return `hsla(${Math.round(hue)}, 80%, 60%, 0.25)`;
}
/**
* Get the GitHub token
*/
export function getGitHubToken() {
return githubToken;
}
/**
* Fetch data from GitHub API
*/
export async function fetchGitHub(url) {
const headers = {
'Accept': 'application/vnd.github.v3+json'
};
if (githubToken) {
headers['Authorization'] = `token ${githubToken}`;
}
const response = await fetch(url, { headers });
if (!response.ok) {
const error = await response.json().catch(() => ({ message: response.statusText }));
// Show token section if rate limited or needs authentication
if (response.status === 401 || response.status === 403) {
const tokenSection = document.getElementById('tokenSection');
const reposSection = document.getElementById('reposSection');
if (tokenSection && reposSection) {
tokenSection.style.display = 'block';
reposSection.classList.remove('collapsed');
}
}
throw new Error(error.message || `HTTP ${response.status}`);
}
return response.json();
}
/**
* Classify an item (issue or PR) as bug, feature, task, or other
*/
export function classifyItem(item, repo = null) {
const labels = item.labels.map(label =>
typeof label === 'string' ? label : label.name
).map(name => name.toLowerCase());
let type = 'other';
// Check for bug indicators
if (labels.some(label =>
label === 'bug' ||
label === 'bugs' ||
label.startsWith('bug:') ||
label.startsWith('bug ') ||
label.includes('defect') ||
label.includes('error') ||
label === 'fix' ||
label.startsWith('fix:') ||
label.startsWith('fix ')
)) {
type = 'bug';
}
// Check for feature indicators
else if (labels.some(label =>
label === 'feature' ||
label === 'features' ||
label.startsWith('feature:') ||
label.startsWith('feature ') ||
label === 'enhancement' ||
label === 'enhancements' ||
label.startsWith('enhancement:') ||
label.startsWith('enhancement ') ||
label === 'improvement' ||
label.startsWith('improvement:') ||
label.startsWith('improvement ') ||
label === 'feat' ||
label.startsWith('feat:') ||
label.startsWith('feat ')
)) {
type = 'feature';
}
// Also check if the item has a type field (GitHub issue types)
if (item.type && typeof item.type === 'object' && item.type.name) {
const typeName = item.type.name.toLowerCase();
if (typeName === 'bug') {
type = 'bug';
} else if (typeName === 'feature') {
type = 'feature';
} else if (typeName === 'task') {
type = 'task';
}
}
const result = {
...item,
type
};
if (repo) {
result.repoName = repo;
}
return result;
}
/**
* Get cached data for a repository
*/
function getCachedData(repo, openOnly) {
const cacheKey = `${CACHE_KEY_PREFIX}${repo}_${openOnly ? 'open' : 'all'}`;
try {
const cached = localStorage.getItem(cacheKey);
if (!cached) return null;
const { data, timestamp } = JSON.parse(cached);
const age = Date.now() - timestamp;
// Return cached data if still fresh
if (age < CACHE_DURATION_MS) {
console.log(`Using cached data for ${repo} (${Math.round(age / 1000)}s old)`);
// Add cache metadata to the result
return { ...data, _cacheTimestamp: timestamp, _fromCache: true };
}
// Cache expired
localStorage.removeItem(cacheKey);
return null;
} catch (error) {
console.error('Cache read error:', error);
return null;
}
}
/**
* Store data in cache
*/
function setCachedData(repo, openOnly, data) {
const cacheKey = `${CACHE_KEY_PREFIX}${repo}_${openOnly ? 'open' : 'all'}`;
try {
const cacheEntry = {
data,
timestamp: Date.now()
};
localStorage.setItem(cacheKey, JSON.stringify(cacheEntry));
} catch (error) {
console.error('Cache write error:', error);
}
}
/**
* Clear all cached repository data
*/
export function clearCache(repos = null) {
try {
const keys = Object.keys(localStorage);
let cacheKeys;
if (repos && repos.length > 0) {
// Clear cache only for specific repositories
cacheKeys = keys.filter(key => {
if (!key.startsWith(CACHE_KEY_PREFIX)) return false;
return repos.some(repo => key.includes(`${CACHE_KEY_PREFIX}${repo}_`));
});
} else {
// Clear all cache
cacheKeys = keys.filter(key => key.startsWith(CACHE_KEY_PREFIX));
}
cacheKeys.forEach(key => localStorage.removeItem(key));
console.log(`Cleared ${cacheKeys.length} cached repositories`);
return cacheKeys.length;
} catch (error) {
console.error('Cache clear error:', error);
return 0;
}
}
/**
* Fetch all issues and PRs for a repository
*/
export async function fetchRepositoryData(repo, openOnly = false) {
const [owner, repoName] = repo.split('/');
// Check cache first
const cached = getCachedData(repo, openOnly);
if (cached) {
console.log(`Using cache for ${repo}`);
return cached;
}
console.log(`Fetching fresh data for ${repo}`);
try {
const state = openOnly ? 'open' : 'all';
const issuesAndPRsUrl = `${GITHUB_API_BASE}/repos/${owner}/${repoName}/issues?state=${state}&per_page=100`;
const issuesAndPRs = await fetchGitHub(issuesAndPRsUrl);
// Separate issues from pull requests
const issues = issuesAndPRs.filter(item => !item.pull_request);
const pullRequests = issuesAndPRs.filter(item => item.pull_request);
const result = {
repo,
owner,
repoName,
issues: issues.map(item => classifyItem(item, repo)),
pullRequests: pullRequests.map(item => classifyItem(item, repo)),
success: true
};
// Cache the successful result
setCachedData(repo, openOnly, result);
return result;
} catch (error) {
console.error(`Error fetching ${repo}:`, error);
return {
repo,
owner,
repoName,
issues: [],
pullRequests: [],
success: false,
error: error.message
};
}
}
/**
* Calculate contrast color (black or white) based on background color
*/
export function getContrastColor(hexColor) {
const hex = hexColor.replace('#', '');
const r = parseInt(hex.substr(0, 2), 16);
const g = parseInt(hex.substr(2, 2), 16);
const b = parseInt(hex.substr(4, 2), 16);
const luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255;
return luminance > 0.5 ? '#000000' : '#ffffff';
}
/**
* Show error message
*/
export function showError(message) {
const errorContainer = document.getElementById('error-container');
if (!errorContainer) return;
const errorDiv = document.createElement('div');
errorDiv.className = 'error';
errorDiv.innerHTML = `
<div class="error-content">
<div class="error-message">${message}</div>
<button onclick="this.parentElement.parentElement.remove()" class="error-close-btn">×</button>
</div>
`;
errorContainer.innerHTML = '';
errorContainer.appendChild(errorDiv);
}
/**
* Escape HTML to prevent XSS
*/
export function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
/**
* Format reactions for display
*/
export function formatReactions(reactions) {
if (!reactions) return '';
const reactionMap = [
{ key: '+1', emoji: '👍', label: 'thumbs up' },
{ key: '-1', emoji: '👎', label: 'thumbs down' },
{ key: 'laugh', emoji: '😄', label: 'laugh' },
{ key: 'hooray', emoji: '🎉', label: 'hooray' },
{ key: 'confused', emoji: '😕', label: 'confused' },
{ key: 'heart', emoji: '❤️', label: 'heart' },
{ key: 'rocket', emoji: '🚀', label: 'rocket' },
{ key: 'eyes', emoji: '👀', label: 'eyes' }
];
const reactionElements = reactionMap
.filter(r => reactions[r.key] && reactions[r.key] > 0)
.map(r => `<span class="interaction-metric" title="${r.label}">${r.emoji} ${reactions[r.key]}</span>`);
if (reactionElements.length === 0) return '';
return `<span class="reactions">${reactionElements.join('')}</span>`;
}
/**
* Get total reactions count for an item
*/
export function getTotalReactions(reactions) {
if (!reactions) return 0;
const keys = ['+1', '-1', 'laugh', 'hooray', 'confused', 'heart', 'rocket', 'eyes'];
return keys.reduce((total, key) => total + (reactions[key] || 0), 0);
}
/**
* Update view switcher links to preserve current repos parameter
*/
function updateViewSwitcherLinks() {
const params = new URLSearchParams(window.location.search);
const repos = params.get('repos');
if (repos) {
const viewSwitcher = document.querySelector('.view-switcher');
if (viewSwitcher) {
const byRepoLink = viewSwitcher.querySelector('a[href="index.html"]');
const byTypeLink = viewSwitcher.querySelector('a[href="by-type.html"]');
if (byRepoLink) {
byRepoLink.href = `index.html?repos=${encodeURIComponent(repos)}`;
}
if (byTypeLink) {
byTypeLink.href = `by-type.html?repos=${encodeURIComponent(repos)}`;
}
}
}
}
/**
* Delete a specific repository from cache
*/
function deleteRepoFromCache(repo) {
const cacheKeysToDelete = [];
// Find all cache keys for this repo
Object.keys(localStorage).forEach(key => {
if (key.startsWith(`${CACHE_KEY_PREFIX}${repo}_`)) {
cacheKeysToDelete.push(key);
}
});
if (cacheKeysToDelete.length === 0) {
showError(`No cache found for ${repo}`);
return;
}
// Delete the cache entries
cacheKeysToDelete.forEach(key => localStorage.removeItem(key));
// Also remove from the repos textarea
const reposInput = document.getElementById('repos');
if (reposInput) {
const currentRepos = reposInput.value.split('\n')
.map(line => line.trim())
.filter(line => line && line.includes('/'));
const filteredRepos = currentRepos.filter(r => r !== repo);
reposInput.value = filteredRepos.join('\n');
// Trigger input event to show change notice
reposInput.dispatchEvent(new Event('input', { bubbles: true }));
}
// Show confirmation message briefly
const cacheStatus = document.getElementById('cacheStatus');
if (cacheStatus) {
cacheStatus.innerHTML = `🗑️ Deleted cache for ${repo}`;
}
// Update cache status display immediately to remove the item
setTimeout(() => {
updateCacheStatus();
}, 500);
}
/**
* Add a repository to the repos list if it's not already there
*/
function addRepoToList(repo) {
const reposInput = document.getElementById('repos');
if (!reposInput) return;
const currentRepos = reposInput.value.split('\n')
.map(line => line.trim())
.filter(line => line && line.includes('/'));
// Toggle: remove if exists, add if not
const repoIndex = currentRepos.indexOf(repo);
let message;
if (repoIndex !== -1) {
// Remove the repo
currentRepos.splice(repoIndex, 1);
message = `➖ Removed ${repo} from list`;
} else {
// Add the repo
currentRepos.push(repo);
message = `✅ Added ${repo} to list`;
}
reposInput.value = currentRepos.join('\n');
// Trigger input event to show change notice
reposInput.dispatchEvent(new Event('input', { bubbles: true }));
// Expand the config section if collapsed
const reposSection = document.getElementById('reposSection');
if (reposSection && reposSection.classList.contains('collapsed')) {
reposSection.classList.remove('collapsed');
}
// Show toggle message
const cacheStatus = document.getElementById('cacheStatus');
if (cacheStatus) {
const originalText = cacheStatus.innerHTML;
cacheStatus.innerHTML = message;
setTimeout(() => {
cacheStatus.innerHTML = originalText;
}, 2000);
}
}
/**
* Setup common UI handlers (repos toggle, token permissions toggle)
*/
export function setupCommonUI() {
// Update view switcher links with current repos
updateViewSwitcherLinks();
// Toggle repos configuration section
const reposToggle = document.getElementById('reposToggle');
const reposSection = document.getElementById('reposSection');
const reposInput = document.getElementById('repos');
// Auto-expand config if only default repo is present
if (reposSection && reposInput) {
const currentRepos = reposInput.value.trim();
const defaultRepo = 'hodpub/github-issues-tracker';
// Check if repos is just the default (no URL params)
const queryRepos = getRepositoriesFromQueryString();
if (!queryRepos && currentRepos === defaultRepo) {
reposSection.classList.remove('collapsed');
}
}
if (reposToggle && reposSection) {
reposToggle.addEventListener('click', () => {
reposSection.classList.toggle('collapsed');
});
}
// Toggle token permissions
const permissionsToggle = document.getElementById('permissionsToggle');
const permissionsContent = document.getElementById('permissionsContent');
const permissionIcon = permissionsToggle?.querySelector('.permission-icon');
if (permissionsToggle && permissionsContent) {
permissionsToggle.addEventListener('click', () => {
permissionsContent.classList.toggle('hidden');
permissionIcon?.classList.toggle('collapsed');
});
}
// Clear cache button
const clearCacheBtn = document.getElementById('clearCacheBtn');
const cacheStatus = document.getElementById('cacheStatus');
if (clearCacheBtn && cacheStatus) {
clearCacheBtn.addEventListener('click', () => {
const count = clearCache();
cacheStatus.textContent = `✓ Cleared ${count} cached repositories`;
setTimeout(() => {
cacheStatus.textContent = '';
}, 3000);
});
}
// Update cache status on page load
updateCacheStatus();
}
/**
* Update cache status display
*/
export function updateCacheStatus() {
const cacheStatus = document.getElementById('cacheStatus');
const cacheDetails = document.getElementById('cacheDetails');
if (!cacheStatus) return;
try {
const keys = Object.keys(localStorage);
const cacheKeys = keys.filter(key => key.startsWith(CACHE_KEY_PREFIX));
if (cacheKeys.length > 0) {
// Extract repository cache info
const cacheInfo = cacheKeys.map(key => {
try {
const match = key.match(/github_cache_(.+)_(open|all)$/);
if (!match) return null;
const repo = match[1];
const type = match[2];
const cached = localStorage.getItem(key);
if (!cached) return null;
const { timestamp } = JSON.parse(cached);
const ageMs = Date.now() - timestamp;
const ageMinutes = Math.floor(ageMs / 60000);
const ageSeconds = Math.floor((ageMs % 60000) / 1000);
const remainingMs = CACHE_DURATION_MS - ageMs;
const remainingMinutes = Math.max(0, Math.ceil(remainingMs / 60000));
let timeAgo;
if (ageMinutes > 0) {
timeAgo = `${ageMinutes}m ${ageSeconds}s ago`;
} else {
timeAgo = `${ageSeconds}s ago`;
}
return {
repo,
type,
timeAgo,
remainingMinutes,
expired: remainingMs <= 0
};
} catch (e) {
return null;
}
}).filter(info => info && !info.expired).sort((a, b) => a.repo.localeCompare(b.repo));
const uniqueRepos = [...new Set(cacheInfo.map(info => info.repo))].length;
cacheStatus.innerHTML = `📦 ${uniqueRepos} repo${uniqueRepos !== 1 ? 's' : ''} cached (click to expand)`;
// Setup click handler for toggling
cacheStatus.onclick = () => {
if (cacheDetails && cacheInfo.length > 0) {
const isVisible = cacheDetails.style.display !== 'none';
cacheDetails.style.display = isVisible ? 'none' : 'block';
cacheStatus.innerHTML = isVisible ?
`📦 ${uniqueRepos} repo${uniqueRepos !== 1 ? 's' : ''} cached (click to expand)` :
`📦 ${uniqueRepos} repo${uniqueRepos !== 1 ? 's' : ''} cached (click to collapse)`;
}
};
// Populate details panel
if (cacheDetails) {
cacheDetails.innerHTML = `
<div class="cache-tip">
💡 <strong>Tip:</strong> Left-click to toggle repo in list • Right-click to delete from cache
</div>
` + cacheInfo.map(info => `
<div class="cache-detail-item">
<span class="cache-repo-name"
data-repo="${escapeHtml(info.repo)}"
title="Left-click to toggle in list • Right-click to delete from cache">
${escapeHtml(info.repo)}
</span>
<span class="cache-detail-time">
${info.timeAgo} •
expires in ${info.remainingMinutes}m
</span>
</div>
`).join('');
// Add click handlers for repo names
cacheDetails.querySelectorAll('.cache-repo-name').forEach(el => {
el.addEventListener('click', (e) => {
e.stopPropagation();
const repo = el.dataset.repo;
addRepoToList(repo);
});
// Add right-click handler to delete from cache
el.addEventListener('contextmenu', (e) => {
e.preventDefault();
e.stopPropagation();
const repo = el.dataset.repo;
deleteRepoFromCache(repo);
});
});
}
} else {
cacheStatus.textContent = 'No cached data';
cacheStatus.onclick = null;
if (cacheDetails) {
cacheDetails.style.display = 'none';
cacheDetails.innerHTML = '';
}
}
} catch (error) {
cacheStatus.textContent = 'No cached data';
cacheStatus.onclick = null;
if (cacheDetails) {
cacheDetails.style.display = 'none';
cacheDetails.innerHTML = '';
}
}
}
/**
* Get cache age text for a repository
*/
export function getCacheAgeText(repoData) {
if (!repoData._cacheTimestamp) return '';
const ageMs = Date.now() - repoData._cacheTimestamp;
const ageMinutes = Math.floor(ageMs / 60000);
const ageSeconds = Math.floor((ageMs % 60000) / 1000);
const remainingMs = CACHE_DURATION_MS - ageMs;
const remainingMinutes = Math.max(0, Math.ceil(remainingMs / 60000));
// If cache is expired, don't show it
if (remainingMs <= 0) return '';
let timeAgo;
if (ageMinutes > 0) {
timeAgo = `${ageMinutes}m ago`;
} else {
timeAgo = `${ageSeconds}s ago`;
}
return `📦 Cached ${timeAgo} (expires in ${remainingMinutes}m)`;
}
/**
* Handle force refresh - clears cache if checkbox is checked
*/
export function handleForceRefresh(repos) {
const forceRefresh = document.getElementById('forceRefresh');
if (forceRefresh && forceRefresh.checked) {
const clearedCount = clearCache(repos);
console.log(`Force refresh: cleared ${clearedCount} cache entries for`, repos);
// Uncheck the box after clearing
forceRefresh.checked = false;
return true;
}
return false;
}
/**
* Get initial repositories (from query string or textarea)
*/
export function getInitialRepos() {
const reposInput = document.getElementById('repos');
if (!reposInput) return [];
const queryRepos = getRepositoriesFromQueryString();
if (queryRepos) {
reposInput.value = queryRepos.join('\n');
return queryRepos;
}
return reposInput.value.split('\n').map(line => line.trim()).filter(line => line && line.includes('/'));
}
/**
* Setup load button handler
*/
export function setupLoadButton(onLoad) {
const loadBtn = document.getElementById('loadBtn');
const tokenInput = document.getElementById('token');
const reposInput = document.getElementById('repos');
const forceRefresh = document.getElementById('forceRefresh');
let configChanged = false;
// Load saved token from localStorage
const savedToken = localStorage.getItem('githubToken');
if (savedToken) {
tokenInput.value = savedToken;
setGitHubToken(savedToken);
}
// Track changes to repos textarea
const showChangeNotice = () => {
if (!configChanged) {
configChanged = true;
loadBtn.style.background = '#da3633';
loadBtn.style.animation = 'pulse 2s infinite';
loadBtn.textContent = '⚠️ Load Issues & PRs (Config Changed)';
}
};
const hideChangeNotice = () => {
configChanged = false;
loadBtn.style.background = '';
loadBtn.style.animation = '';
loadBtn.textContent = 'Load Issues & PRs';
};
// Watch for changes in repos textarea
reposInput.addEventListener('input', showChangeNotice);
loadBtn.addEventListener('click', async () => {
const token = tokenInput.value.trim();
setGitHubToken(token);
const reposText = reposInput.value.trim();
// Save to localStorage
localStorage.setItem('githubToken', token);
localStorage.setItem('githubRepos', reposText);
// Clear change notice
hideChangeNotice();
if (!reposText) {
showError('Please enter at least one repository');
return;
}
const repos = reposText.split('\n')
.map(line => line.trim())
.filter(line => line && line.includes('/'));
if (repos.length === 0) {
showError('Please enter valid repositories in format: owner/repo');
return;
}
// Update URL with repos list (skip if only default repo)
const defaultRepo = 'hodpub/github-issues-tracker';
if (!(repos.length === 1 && repos[0] === defaultRepo)) {
const url = new URL(window.location);
url.searchParams.set('repos', repos.join(','));
window.history.pushState({}, '', url);
// Update view switcher links with new repos (small delay to ensure URL is updated)
setTimeout(() => updateViewSwitcherLinks(), 10);
}
// Handle force refresh
handleForceRefresh(repos);
await onLoad(repos);
// Update cache status after loading (with small delay to ensure cache writes complete)
setTimeout(() => updateCacheStatus(), 100);
});
// Setup share button
const shareBtn = document.getElementById('shareBtn');
if (shareBtn) {
shareBtn.addEventListener('click', async () => {
try {
await navigator.clipboard.writeText(window.location.href);
const originalText = shareBtn.innerHTML;
shareBtn.innerHTML = '✅ Copied!';
shareBtn.style.background = '#238636';
setTimeout(() => {
shareBtn.innerHTML = originalText;
}, 2000);
} catch (err) {
showError('Failed to copy URL to clipboard');
}
});
}
return { tokenInput, reposInput };
}
/**
* Setup auto-load functionality for initial repos from URL
* @param {Function} loadFunction - The async function to call with repos array
*/
export async function setupAutoLoad(loadFunction) {
const initialRepos = getInitialRepos();
if (initialRepos && initialRepos.length > 0) {
// Update URL with initial repos (skip if only default repo)
const defaultRepo = 'hodpub/github-issues-tracker';
if (!(initialRepos.length === 1 && initialRepos[0] === defaultRepo)) {
const url = new URL(window.location);
url.searchParams.set('repos', initialRepos.join(','));
window.history.replaceState({}, '', url);
}
// Auto-load
await loadFunction(initialRepos);
// Update cache status after loading (with small delay to ensure cache writes complete)
setTimeout(() => updateCacheStatus(), 100);
}
}
/**
* Setup ad banner
*/
export function setupAdBanner(imageUrl = 'hodpub-ad.webp') {
const adContainer = document.getElementById('hodpub-ad');
const adImg = document.getElementById('hodpub-ad-img');
if (!adContainer || !adImg) return;
// Set image source
adImg.src = imageUrl;
// Hide container if image fails to load
adImg.onerror = function() {
adContainer.style.display = 'none';
};
}
/**
* Setup help panel
*/
export function setupHelpPanel() {
const helpBtn = document.getElementById('helpBtn');
const helpPanel = document.getElementById('helpPanel');
const closeHelp = document.getElementById('closeHelp');
const helpContent = document.getElementById('helpContent');
if (!helpBtn || !helpPanel || !closeHelp || !helpContent) return;
// Help content
const helpHTML = `
<div class="help-content-wrapper">
<h2>📖 Quick Start Guide</h2>
<section>
<h3>🚀 Getting Started</h3>
<ol>
<li><strong>Enter repositories</strong> in the format <code>owner/repo</code> (one per line)</li>
<li><strong>Optional (but required for private repos):</strong> Add a GitHub token for higher rate limits (5000/hour vs 60/hour) and to access private repositories</li>
<li>Click <strong>"Load Issues & PRs"</strong> to fetch data</li>
<li>Switch between <strong>"By Repository"</strong> and <strong>"By Type"</strong> views</li>
</ol>
</section>
<section>
<h3>🎯 Key Features</h3>
<ul>
<li><strong>Click on any issue/PR card</strong> to view details inline</li>
<li><strong>PRs open directly on GitHub</strong> for code review</li>
<li><strong>Color coding:</strong> Bugs (🐛 red/green), PRs (🔀 purple when present)</li>
<li><strong>Automatic classification:</strong> Bugs, features, tasks based on labels</li>
<li><strong>1-hour caching</strong> to reduce API calls and stay within rate limits</li>
</ul>
</section>
<section>
<h3>💾 Cache Management</h3>
<ul>
<li><strong>Click "📦 cached"</strong> to expand/collapse cache details</li>
<li><strong>Left-click</strong> a cached repo name to toggle it in your list</li>
<li><strong>Right-click</strong> a cached repo name to delete it from cache</li>
<li><strong>"Force refresh"</strong> checkbox bypasses cache for fresh data</li>
<li><strong>"Clear Cache"</strong> button removes all cached data</li>
</ul>
</section>
<section>
<h3>🔗 Sharing & URLs</h3>
<ul>
<li><strong>URL auto-updates</strong> when you load repositories</li>
<li><strong>Share button (🔗)</strong> copies the current URL to clipboard</li>
<li><strong>Bookmark URLs</strong> to save your repository configurations</li>
<li><strong>URL format:</strong> <code>?repos=owner/repo1,owner/repo2</code></li>
</ul>
</section>
<section>
<h3>⚠️ Important Notes</h3>
<ul>
<li><strong>Red pulsing Load button</strong> means config changed - click to reload</li>
<li><strong>100% client-side</strong> - no data sent to servers, all stays local</li>
<li><strong>Token stored locally</strong> in your browser only</li>
<li><strong>Private repos</strong> require a token with <code>repo</code> scope</li>
<li><strong>Optional analytics:</strong> First visit shows consent banner - only page views tracked if you accept (no personal data or repository names)</li>
</ul>
</section>
<section>
<h3>🎨 View Modes</h3>
<ul>
<li><strong>By Repository:</strong> Each repo gets its own section showing all issues/PRs</li>
<li><strong>By Type:</strong> Issues grouped across all repos (PRs, Bugs, Features, Tasks)</li>
</ul>
</section>
<section>
<h3>👍 How to Upvote/React to Issues</h3>
<ol>
<li>Click the <strong>↗️ arrow link</strong> next to the issue title, or click <strong>"View on GitHub"</strong> button at the bottom of the detail panel</li>
<li>This will open the issue on GitHub in a new tab</li>
<li>On the GitHub issue page, find the <strong>emoji reaction buttons</strong> at the bottom of the issue description</li>
<li>Click the emoji you want to add (👍 for upvote, ❤️ for heart, etc.)</li>
<li>Your reaction will be visible to everyone and counted in the reaction totals</li>
</ol>
<img src="assets/reaction-example.png" alt="GitHub reaction buttons example" class="help-image">
<p><em>Note: You need to be logged into GitHub to add reactions. Reactions are public and associated with your GitHub account.</em></p>
</section>
<div class="help-pro-tip">
<strong>💡 Pro Tip:</strong> Use the cache panel to quickly add/remove repos you've previously viewed!
</div>
</div>
`;
// Show help panel
helpBtn.addEventListener('click', () => {
helpContent.innerHTML = helpHTML;
helpPanel.classList.add('open');
});
// Close help panel
closeHelp.addEventListener('click', () => {
helpPanel.classList.remove('open');
});
// React help button (if exists on page)
const reactHelpBtn = document.getElementById('reactHelpBtn');
if (reactHelpBtn) {
reactHelpBtn.addEventListener('click', () => {
helpContent.innerHTML = helpHTML;
helpPanel.classList.add('open');
// Scroll to the reactions section after a brief delay
setTimeout(() => {
const reactSection = helpContent.querySelector('h3');
const sections = helpContent.querySelectorAll('h3');
sections.forEach(section => {
if (section.textContent.includes('How to Upvote/React')) {
section.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
});
}, 100);
});
}
}
/**
* Format a date for display
*/
export function formatDate(dateString) {
return new Date(dateString).toLocaleDateString('en-US', {
year: 'numeric',
month: 'short',
day: 'numeric'
});
}
/**
* Format markdown text with support for mixed HTML/Markdown
*/