-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathRepo Explorer.html
More file actions
1124 lines (1015 loc) · 55.7 KB
/
Repo Explorer.html
File metadata and controls
1124 lines (1015 loc) · 55.7 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>GitHub Repo Explorer</title>
<style>
:root {
--primary-color: #0366d6;
--border-color: #e1e4e8;
--background-light: #f6f8fa;
--text-color: #24292e;
--text-muted: #586069;
--red: #d73a49;
--green: #28a745;
}
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
line-height: 1.6;
color: var(--text-color);
max-width: 95%;
margin: 0 auto;
padding: 20px;
}
h1, h2 { text-align: center; }
input[type="text"], input[type="password"] {
padding: 8px 12px;
border: 1px solid var(--border-color);
border-radius: 6px;
font-size: 14px;
width: 100%;
box-sizing: border-box;
}
button {
padding: 8px 14px;
border: 1px solid rgba(27, 31, 35, 0.15);
background-color: #f6f8fa;
color: var(--text-color);
border-radius: 6px;
font-size: 14px;
font-weight: 500;
cursor: pointer;
transition: background-color 0.2s;
}
button:hover { background-color: #f3f4f6; }
button:disabled { background-color: #f6f8fa; cursor: not-allowed; opacity: 0.6; }
button.primary { background-color: var(--green); color: white; border-color: var(--green); font-weight: 600; }
button.primary:hover { background-color: #269f42; }
.tabs { display: flex; border-bottom: 1px solid var(--border-color); margin-bottom: 20px; }
.tab-button { background: none; border: none; border-bottom: 3px solid transparent; padding: 10px 15px; font-size: 16px; border-radius: 0; }
.tab-button.active { border-bottom-color: var(--primary-color); font-weight: bold; }
.tab-content { display: none; }
.tab-content.active { display: block; }
.section { background-color: var(--background-light); border: 1px solid var(--border-color); border-radius: 6px; padding: 20px; margin-bottom: 20px; }
#fetcher .section { max-width: 800px; margin-left: auto; margin-right: auto; }
.section-title { margin-top: 0; border-bottom: 1px solid var(--border-color); padding-bottom: 10px; }
.controls-grid { display: flex; flex-wrap: wrap; gap: 10px; align-items: center; }
#status, #full-fetch-status { margin-top: 15px; font-weight: bold; }
.error { color: var(--red); }
.success { color: var(--green); }
/* Viewer Layout */
.viewer-layout { display: flex; gap: 20px; align-items: flex-start; }
.entity-list-container { flex: 0 0 250px; }
.viewer-main-content {
flex-grow: 1;
min-width: 0; /* Important: allows the flex item to shrink below its content size */
}
#entityList .entity-item { display: block; width: 100%; padding: 10px; border: 1px solid transparent; border-radius: 6px; text-align: left; background: none; margin-bottom: 5px; }
#entityList .entity-item.active { background-color: var(--primary-color); color: white; font-weight: bold; }
#entityList .entity-item:not(.active):hover { background-color: #f3f4f6; }
/* Table Styles - FIXED FOR PROPER RESIZING */
.table-container {
overflow-x: auto;
border: 1px solid var(--border-color);
border-radius: 6px;
position: relative;
}
table {
border-collapse: collapse;
table-layout: fixed; /* This is crucial for consistent column widths */
width: auto; /* Allow table to grow beyond container */
min-width: 100%; /* But at least fill the container */
}
th, td {
padding: 12px 15px;
text-align: left;
border-bottom: 1px solid var(--border-color);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
box-sizing: border-box; /* Include padding in width calculations */
}
#repoTableBody td:first-child {
white-space: normal;
word-break: break-all; /* Allow long names to wrap */
min-width: 18rem;
}
thead tr:last-child th { border-bottom: none; }
tr:last-child td { border-bottom: none; }
th {
background-color: var(--background-light);
user-select: none;
position: relative;
min-width: 50px; /* Minimum column width */
}
th.sortable-header { cursor: pointer; }
th.sortable-header:hover { background-color: #eef1f4; }
th .sort-indicator {
display: inline-block;
width: 1em;
color: var(--text-muted);
margin-right: 6px;
}
tr:hover { background-color: #f6f8fa; }
td a { color: var(--primary-color); text-decoration: none; }
td a:hover { text-decoration: underline; }
/* Resizable Columns */
.resize-handle {
position: absolute;
top: 0;
right: -3px;
width: 6px;
height: 100%;
cursor: col-resize;
z-index: 10;
background: transparent; /* Make it easier to grab */
}
.resize-handle:hover {
background: rgba(0, 0, 0, 0.1);
}
/* Filter Styles */
.filter-row th { padding: 8px; }
.language-filter-cell { position: relative; overflow: visible; }
.language-filter { position: relative; }
.language-filter-button { width: 100%; text-align: left; background-color: white; padding: 8px 12px; font-size: 14px; font-weight: normal; }
.language-filter-dropdown {
display: none;
position: fixed;
background-color: white;
border: 1px solid var(--border-color);
border-radius: 6px;
max-height: 250px;
overflow-y: auto;
z-index: 1000;
box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}
.language-filter-dropdown div { padding: 8px 12px; }
.language-filter-dropdown label { display: block; width: 100%; font-weight: normal;}
.api-key-container { display: flex; align-items: center; gap: 5px; flex-grow: 1; }
.api-key-container a { white-space: nowrap; }
/* Tooltip Styles */
.tooltip {
position: relative;
display: inline-block;
margin-left: 4px;
}
.tooltip .tooltip-icon {
display: inline-block;
border: 1px solid var(--text-muted);
border-radius: 50%;
width: 16px;
height: 16px;
text-align: center;
line-height: 14px; /* Adjust for better vertical alignment */
font-size: 12px;
font-style: italic;
font-family: 'Times New Roman', Times, serif;
color: var(--text-muted);
cursor: help;
user-select: none; /* Prevent text selection */
}
.tooltip .tooltip-text {
visibility: hidden;
width: 250px;
background-color: #333;
color: #fff;
text-align: left; /* Better for a sentence */
border-radius: 6px;
padding: 8px 12px;
position: absolute;
z-index: 1001; /* Ensure it's on top of other elements */
bottom: 150%; /* Position above the icon */
left: 50%;
transform: translateX(-50%); /* Center it */
opacity: 0;
transition: opacity 0.3s;
font-size: 12px;
font-weight: normal;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
font-style: normal;
box-shadow: 0 2px 8px rgba(0,0,0,0.2);
}
/* Arrow for the tooltip */
.tooltip .tooltip-text::after {
content: "";
position: absolute;
top: 100%; /* At the bottom of the tooltip */
left: 50%;
margin-left: -5px;
border-width: 5px;
border-style: solid;
border-color: #333 transparent transparent transparent;
}
.tooltip:hover .tooltip-text {
visibility: visible;
opacity: 1;
}
/* Release info styles */
.has-exe { color: var(--green); font-weight: bold; }
.no-exe { color: var(--text-muted); }
.loading-releases { color: var(--text-muted); font-style: italic; }
.token-message a { /* Or a more specific selector for your link */
color: #66b2ff; /* A lighter blue, or choose another color */
text-decoration: underline; /* Ensures it's always visibly a link */
white-space: nowrap;
}
.token-message a:hover {
color: #8cc9ff; /* Slightly lighter on hover */
}
@media (prefers-color-scheme: dark) {
:root {
--primary-color: #2f81f7;
--border-color: #30363d;
--background-light: #161b22;
--text-color: #c9d1d9;
--text-muted: #8b949e;
--green: #238636;
}
body {
background-color: #0d1117;
}
input[type="text"], input[type="password"] {
background-color: #010409;
border-color: var(--border-color);
color: var(--text-color);
}
button {
background-color: #21262d;
color: var(--text-color);
border-color: rgba(240, 246, 252, 0.1);
}
button:hover {
background-color: #30363d;
border-color: #8b949e;
}
button:disabled {
background-color: #21262d;
opacity: 0.5;
}
button.primary {
background-color: var(--green);
color: white;
border-color: var(--green);
}
button.primary:hover {
background-color: #2ea043;
}
th.sortable-header:hover { background-color: #1f242c; }
#entityList .entity-item:not(.active):hover { background-color: #161b22; }
tr:hover { background-color: #161b22; }
.resize-handle:hover { background: rgba(255, 255, 255, 0.1); }
.language-filter-button {
background-color: #0d1117;
}
.language-filter-dropdown {
background-color: #161b22;
border-color: var(--border-color);
}
.tooltip .tooltip-text {
background-color: #484f58;
color: var(--text-color);
}
.tooltip .tooltip-text::after {
border-top-color: #484f58;
}
}
</style>
</head>
<body>
<h1>GitHub Repo Explorer</h1>
<div class="tabs">
<button class="tab-button active" onclick="App.changeTab('viewer')">Cached Repositories</button>
<button class="tab-button" onclick="App.changeTab('fetcher')">Full Fetch Tool</button>
</div>
<div id="viewer" class="tab-content active">
<div class="viewer-layout">
<div class="entity-list-container">
<div class="section" style="padding: 15px;">
<div class="controls-grid" style="gap: 5px;">
<button onclick="App.updateAll()" title="Check all cached users for updated repositories.">Update All</button>
<button onclick="document.getElementById('importInput').click()" title="Import a cache file.">Import Cache</button>
<input type="file" id="importInput" accept=".json" style="display: none;" onchange="App.importData(event)">
</div>
</div>
<div class="section">
<h2 class="section-title">Cached Users</h2>
<div id="entityList"></div>
</div>
</div>
<div class="viewer-main-content">
<div id="results-container" style="display:none;">
<div class="section">
<div class="controls-grid">
<span>Actions for <strong id="currentEntityName"></strong>:</span>
<button id="updateButton" onclick="App.update()" title="Fetch recent changes and new repositories.">Update</button>
<button onclick="App.fetchReleases()" title="Fetch release information for all repositories.">Fetch Releases</button>
<button onclick="App.exportData()" title="Export cache to a JSON file.">Export</button>
<button id="deleteButton" onclick="App.deleteData()" title="Delete cache for selected user.">Delete</button>
</div>
<div id="status"></div>
</div>
<div class="table-container">
<table id="repoTable">
<thead>
<tr>
<th class="sortable-header" onclick="App.setSort('name')" style="width: 250px;"><span
class="sort-indicator"></span>Name</th>
<th class="sortable-header" onclick="App.setSort('stargazers_count')" style="width: 100px;"><span
class="sort-indicator"></span>Stars</th>
<th class="sortable-header" onclick="App.setSort('language')" style="width: 150px;"><span
class="sort-indicator"></span>Language</th>
<th class="sortable-header" onclick="App.setSort('created_at')" style="width: 120px;"><span
class="sort-indicator"></span>Created</th>
<th class="sortable-header" onclick="App.setSort('updated_at')" style="width: 120px;"><span
class="sort-indicator"></span>Updated</th>
<th class="sortable-header" onclick="App.setSort('pushed_at')" style="width: 120px;"><span
class="sort-indicator"></span>Pushed</th>
<th class="sortable-header" onclick="App.setSort('has_releases')" style="width: 100px;"><span
class="sort-indicator"></span>Releases</th>
<th class="sortable-header" onclick="App.setSort('description')" style="width: 400px;"><span
class="sort-indicator"></span>Description</th>
</tr>
<tr class="filter-row">
<th><input type="text" id="nameFilter" onkeyup="App.applyFilters()" placeholder="Filter..."></th>
<th></th>
<th class="language-filter-cell">
<div class="language-filter">
<button id="languageFilterButton" class="language-filter-button"
onclick="App.toggleLanguageFilter()">All Languages</button>
</div>
</th>
<th></th>
<th></th>
<th></th>
<th>
<select id="releaseFilter" onchange="App.applyFilters()"
style="width: 100%; padding: 8px; background-color: white; border: 1px solid var(--border-color); border-radius: 6px; font-size: 14px;">
<option value="">All</option>
<option value="has_any">Has Releases</option>
<option value="has_exe">Has .exe</option>
<option value="no_releases">No Releases</option>
</select>
</th>
<th><input type="text" id="descriptionFilter" onkeyup="App.applyFilters()" placeholder="Filter..."></th>
</tr>
</thead>
<tbody id="repoTableBody"></tbody>
</table>
</div>
</div>
<div id="viewer-prompt" class="section" style="text-align: center;">
<p>Select a cached user from the list on the left to view their repositories.</p>
<p>If the list is empty, use the 'Full Fetch Tool' tab to get started.</p>
</div>
</div>
</div>
</div>
<div id="fetcher" class="tab-content">
<div class="section">
<p>Fetch all public repositories for a GitHub user or organization. This data will be cached in your browser.</p>
<div class="controls-grid">
<input type="text" id="repoUrl" placeholder="Enter GitHub User/Org Name (e.g., 'microsoft')">
<div class="api-key-container">
<input type="password" id="apiKey" placeholder="Optional: GitHub API Key (PAT)">
<a href="https://github.com/settings/personal-access-tokens/new" target="_blank" rel="noopener noreferrer">Get token</a>
<div class="tooltip">
<span class="tooltip-icon">i</span>
<span class="tooltip-text">A Personal Access Token (PAT) is needed to get release information. It increases the number of requests you can make to GitHub's API.
<br><br>A default fine grained "public repository" token is sufficient (Read only access to public repositories) .
</span>
</div>
</div>
<button id="fetchButton" class="primary" onclick="App.fullFetch()">Fetch All Repositories</button>
</div>
<div id="full-fetch-status">The results of the full fetch will appear here.</div>
</div>
</div>
<div id="languageFilterDropdown" class="language-filter-dropdown"></div>
<script>
const DB = {
_db: null,
DB_NAME: 'GitHubRepoExplorerDB',
DB_VERSION: 1,
STORES: {
ENTITIES: 'entities',
CONFIG: 'config'
},
async init() {
if (this._db) return;
return new Promise((resolve, reject) => {
const request = indexedDB.open(this.DB_NAME, this.DB_VERSION);
request.onerror = (event) => {
console.error("IndexedDB error:", request.error);
reject("IndexedDB error: " + request.error);
};
request.onupgradeneeded = (event) => {
const db = event.target.result;
if (!db.objectStoreNames.contains(this.STORES.ENTITIES)) {
db.createObjectStore(this.STORES.ENTITIES, { keyPath: 'entity' });
}
if (!db.objectStoreNames.contains(this.STORES.CONFIG)) {
db.createObjectStore(this.STORES.CONFIG, { keyPath: 'key' });
}
};
request.onsuccess = (event) => {
this._db = event.target.result;
resolve();
};
});
},
async _getStore(storeName, mode = 'readonly') {
if (!this._db) await this.init();
return this._db.transaction(storeName, mode).objectStore(storeName);
},
async get(storeName, key) {
const store = await this._getStore(storeName);
return new Promise((resolve, reject) => {
const request = store.get(key);
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
},
async set(storeName, value) {
const store = await this._getStore(storeName, 'readwrite');
return new Promise((resolve, reject) => {
const request = store.put(value);
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
},
async delete(storeName, key) {
const store = await this._getStore(storeName, 'readwrite');
return new Promise((resolve, reject) => {
const request = store.delete(key);
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
},
async getAllKeys(storeName) {
const store = await this._getStore(storeName);
return new Promise((resolve, reject) => {
const request = store.getAllKeys();
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
}
};
const App = {
// --- STATE ---
state: {
currentEntity: null, allRepos: [], filteredRepos: [], sortBy: 'stargazers_count', sortDir: 'desc',
languages: { all: new Set(), selected: new Set() }, apiKey: '',
isResizing: false, releaseInfo: {},
},
// --- CONSTANTS ---
CACHE_KEYS: ['name', 'stargazers_count', 'language', 'created_at', 'updated_at', 'pushed_at', 'description', 'html_url', 'has_exe', 'has_releases'],
// --- INITIALIZATION ---
async init() {
await DB.init();
const apiKeyConfig = await DB.get(DB.STORES.CONFIG, 'githubApiKey');
this.state.apiKey = apiKeyConfig ? apiKeyConfig.value : '';
document.getElementById('apiKey').value = this.state.apiKey;
await this.populateEntityList();
await this.autoSelectEntity();
this.initResizableColumns();
document.body.addEventListener('click', (e) => {
const dropdown = document.getElementById('languageFilterDropdown');
const button = document.getElementById('languageFilterButton');
if (dropdown && button && !dropdown.contains(e.target) && !button.contains(e.target)) {
dropdown.style.display = 'none';
}
}, true);
},
// --- UI & TABS ---
changeTab(tabName) {
document.querySelectorAll('.tab-content').forEach(tc => tc.classList.remove('active'));
document.querySelectorAll('.tab-button').forEach(tb => tb.classList.remove('active'));
document.getElementById(tabName).classList.add('active');
document.querySelector(`.tab-button[onclick="App.changeTab('${tabName}')"]`).classList.add('active');
},
setStatus(message, type = 'info', container = 'status') {
const el = document.getElementById(container);
el.textContent = message;
el.className = type;
},
// --- CACHE & DATA MANAGEMENT ---
async getCache(entity) {
return await DB.get(DB.STORES.ENTITIES, entity);
},
async setCache(entity, data) {
try {
await DB.set(DB.STORES.ENTITIES, data);
} catch (e) {
this.setStatus(`Error saving cache: ${e.message}`, 'error');
}
},
async getAllCachedEntities() {
return await DB.getAllKeys(DB.STORES.ENTITIES);
},
async populateEntityList() {
const listEl = document.getElementById('entityList');
listEl.innerHTML = '';
const entities = await this.getAllCachedEntities();
entities.forEach(entityName => {
const button = document.createElement('button');
button.className = 'entity-item';
button.textContent = entityName;
button.dataset.entity = entityName;
button.onclick = () => this.selectEntity(entityName);
listEl.appendChild(button);
});
document.getElementById('viewer-prompt').style.display = entities.length > 0 ? 'none' : 'block';
},
async autoSelectEntity() {
const lastSelected = sessionStorage.getItem('selectedEntity');
const allEntities = await this.getAllCachedEntities();
if (lastSelected && allEntities.includes(lastSelected)) {
await this.selectEntity(lastSelected);
return;
}
const entityItems = await Promise.all(
allEntities.map(async name => ({ name, cache: await this.getCache(name) }))
);
const sortedEntities = entityItems
.filter(item => item.cache && item.cache.fetchedAt)
.sort((a, b) => new Date(b.cache.fetchedAt) - new Date(a.cache.fetchedAt));
if (sortedEntities.length > 0) {
await this.selectEntity(sortedEntities[0].name);
}
},
async selectEntity(entity) {
if (entity) {
sessionStorage.setItem('selectedEntity', entity);
} else {
sessionStorage.removeItem('selectedEntity');
}
this.state.currentEntity = entity;
this.state.releaseInfo = {};
document.querySelectorAll('#entityList .entity-item').forEach(item => {
item.classList.toggle('active', item.dataset.entity === entity);
});
const resultsContainer = document.getElementById('results-container');
const prompt = document.getElementById('viewer-prompt');
if (!entity) { resultsContainer.style.display = 'none'; prompt.style.display = 'block'; return; }
prompt.style.display = 'none';
const cachedData = await this.getCache(entity);
if (cachedData && cachedData.repos) {
this.state.allRepos = cachedData.repos;
document.getElementById('currentEntityName').textContent = entity;
this.setStatus(`Displaying ${cachedData.repos.length} cached repos. Last updated: ${new Date(cachedData.fetchedAt).toLocaleString()}`, 'success');
document.getElementById('nameFilter').value = '';
document.getElementById('descriptionFilter').value = '';
this.state.languages.selected.clear();
this.buildLanguageFilter();
this.applyFilters();
resultsContainer.style.display = 'block';
} else {
resultsContainer.style.display = 'none';
this.setStatus(`No cache found for "${entity}". Use the Full Fetch tool.`, 'error');
}
},
async deleteData() {
const entity = this.state.currentEntity;
if (!entity || !confirm(`Are you sure you want to delete all cached data for "${entity}"?`)) return;
await DB.delete(DB.STORES.ENTITIES, entity);
await this.populateEntityList();
await this.selectEntity(null);
document.getElementById('results-container').style.display = 'none';
document.getElementById('viewer-prompt').style.display = 'block';
},
async exportData() {
const entity = this.state.currentEntity;
if (!entity) return;
const data = await this.getCache(entity);
if (!data) return;
const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = `${entity}_repo_cache.json`;
a.click();
URL.revokeObjectURL(a.href);
},
importData(event) {
const file = event.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = async (e) => {
try {
const data = JSON.parse(e.target.result);
if (!data.entity || !data.repos || !data.fetchedAt) throw new Error("Invalid cache file format.");
await this.setCache(data.entity, data);
await this.populateEntityList();
await this.selectEntity(data.entity);
} catch (err) { this.setStatus(`Import failed: ${err.message}`, 'error'); }
finally { event.target.value = ''; }
};
reader.readAsText(file);
},
// --- GITHUB API FETCHING ---
async _fetch(url, options = {}) {
const newApiKey = document.getElementById('apiKey').value.trim();
if (newApiKey !== this.state.apiKey) {
this.state.apiKey = newApiKey;
await DB.set(DB.STORES.CONFIG, { key: 'githubApiKey', value: this.state.apiKey });
}
if (this.state.apiKey) {
options.headers = { ...options.headers, 'Authorization': `token ${this.state.apiKey}` };
}
const response = await fetch(url, options);
if (response.status === 403) {
const resetDate = new Date(response.headers.get('X-RateLimit-Reset') * 1000);
throw new Error(`API rate limit exceeded. Resets at ${resetDate.toLocaleTimeString()}.`);
}
if (!response.ok) {
const errorData = await response.json();
throw new Error(`API Error: ${response.status} - ${errorData.message}`);
}
return response;
},
async fullFetch() {
const userInput = document.getElementById('repoUrl').value.trim();
const fetchButton = document.getElementById('fetchButton');
fetchButton.disabled = true;
this.setStatus('Starting full fetch...', 'info', 'full-fetch-status');
let entityName, entityType;
try {
entityName = userInput.includes('github.com') ? new URL(userInput).pathname.split('/')[1] : userInput.replace(/[^a-zA-Z0-9-]/g, '');
if (!entityName) throw new Error("Invalid user/org name.");
const userCheck = await this._fetch(`https://api.github.com/users/${entityName}`);
entityType = (await userCheck.json()).type === 'Organization' ? 'orgs' : 'users';
const initialUrl = `https://api.github.com/${entityType}/${entityName}/repos?per_page=100&page=1&sort=full_name`;
this.setStatus('Fetching page 1 to determine total pages...', 'info', 'full-fetch-status');
const initialResponse = await this._fetch(initialUrl);
let allRepos = await initialResponse.json();
const linkHeader = initialResponse.headers.get('Link');
let lastPage = 1;
if (linkHeader) {
const lastLink = linkHeader.split(',').find(s => s.includes('rel="last"'));
if (lastLink) lastPage = parseInt(new URL(lastLink.match(/<(.+)>/)[1]).searchParams.get('page'));
}
if (lastPage > 1) {
const pagePromises = [];
for (let i = 2; i <= lastPage; i++) {
const pageUrl = `https://api.github.com/${entityType}/${entityName}/repos?per_page=100&page=${i}&sort=full_name`;
pagePromises.push(this._fetch(pageUrl).then(res => res.json()));
}
this.setStatus(`Fetching pages 2 to ${lastPage} in parallel...`, 'info', 'full-fetch-status');
const settledResponses = await Promise.allSettled(pagePromises);
settledResponses.forEach(res => {
if (res.status === 'fulfilled' && res.value) allRepos = allRepos.concat(res.value);
});
}
const simplifiedRepos = allRepos.map(repo => this.CACHE_KEYS.reduce((obj, key) => ({ ...obj, [key]: repo[key] }), {}));
await this.setCache(entityName, { entity: entityName, fetchedAt: new Date().toISOString(), repos: simplifiedRepos });
this.setStatus(`Fetched ${simplifiedRepos.length} repos. Now fetching release information...`, 'success', 'full-fetch-status');
await this.fetchReleasesForEntity(entityName, simplifiedRepos.length, 'full-fetch-status');
this.setStatus(`Success! Fetched ${simplifiedRepos.length} repos with release information for "${entityName}".`, 'success', 'full-fetch-status');
await this.populateEntityList();
await this.selectEntity(entityName);
this.changeTab('viewer');
} catch (error) { this.setStatus(`Error: ${error.message}`, 'error', 'full-fetch-status'); }
finally { fetchButton.disabled = false; }
},
async update(entityToUpdate = null) {
const entity = entityToUpdate || this.state.currentEntity;
if (!entity) return;
const button = document.getElementById('updateButton');
if (button && !entityToUpdate) button.disabled = true;
this.setStatus(`Checking for updates for "${entity}"...`, 'info');
try {
const cachedData = await this.getCache(entity);
if (!cachedData) throw new Error("No cache found to update.");
const latestCachedUpdate = cachedData.repos.reduce((latest, repo) => repo.updated_at > latest ? repo.updated_at : latest, '');
const userCheck = await this._fetch(`https://api.github.com/users/${entity}`);
const entityType = (await userCheck.json()).type === 'Organization' ? 'orgs' : 'users';
let recentRepos = [], page = 1, keepFetching = true;
while (keepFetching) {
this.setStatus(`Updating "${entity}": Fetching page ${page}...`, 'info');
const res = await this._fetch(`https://api.github.com/${entityType}/${entity}/repos?per_page=100&page=${page}&sort=updated`);
const pageRepos = await res.json();
if (pageRepos.length === 0) { keepFetching = false; continue; }
const lastRepoOnPage = pageRepos[pageRepos.length - 1];
if (new Date(lastRepoOnPage.updated_at) < new Date(latestCachedUpdate)) keepFetching = false;
recentRepos.push(...pageRepos.filter(r => new Date(r.updated_at) > new Date(latestCachedUpdate)));
page++;
}
if (recentRepos.length > 0) {
const repoMap = new Map(cachedData.repos.map(repo => [repo.name, repo]));
let newCount = 0, updatedCount = 0;
recentRepos.forEach(repo => {
const existingRepo = repoMap.get(repo.name);
const hasExe = existingRepo ? existingRepo.has_exe : undefined;
const hasReleases = existingRepo ? existingRepo.has_releases : undefined;
repoMap.has(repo.name) ? updatedCount++ : newCount++;
repoMap.set(repo.name, {
...this.CACHE_KEYS.reduce((obj, key) => ({ ...obj, [key]: repo[key] }), {}),
has_exe: hasExe, // Preserve existing release info
has_releases: hasReleases
});
});
cachedData.repos = Array.from(repoMap.values());
cachedData.fetchedAt = new Date().toISOString();
await this.setCache(entity, cachedData);
this.setStatus(`Update for "${entity}" complete! Found ${newCount} new and ${updatedCount} updated repos.`, 'success');
} else {
this.setStatus(`Cache for "${entity}" is already up to date.`, 'success');
}
// Check if we need to fetch release info
const shouldFetchReleases = recentRepos.length > 0 || // Any new/updated repos
!cachedData.releasesCheckedAt || // Never checked releases
cachedData.repos.some(repo => repo.has_exe === undefined || repo.has_exe === null); // Missing release data
if (shouldFetchReleases) {
this.setStatus(`Fetching release information...`, 'info');
await this.fetchReleasesForEntity(entity);
}
// Always refresh the display if this is the current entity
if (entity === this.state.currentEntity) {
await this.selectEntity(entity);
}
} catch (error) {
this.setStatus(`Update for "${entity}" failed: ${error.message}`, 'error');
} finally {
if (button && !entityToUpdate) button.disabled = false;
}
},
async fetchReleasesForEntity(entityName, expectedRepoCount = null, fetchStatusName = null) {
if (!entityName) {
console.error("No entity name provided for fetching releases.");
return;
}
const cachedData = await this.getCache(entityName);
if (!cachedData || !cachedData.repos)
return;
try {
// Check if entity is user or org
const userCheck = await this._fetch(`https://api.github.com/users/${entityName}`);
const entityType = (await userCheck.json()).type === 'Organization' ? 'organization' : 'user';
// Show initial status if this is the current entity
if (entityName === this.state.currentEntity) {
this.setStatus(`Fetching release information for ${cachedData.repos.length} repositories...`, 'info');
if (!expectedRepoCount && cachedData.repos) {
expectedRepoCount = cachedData.repos.length;
}
}
const query = `
query GetRepositoriesWithReleases($username: String!, $cursor: String) {
${entityType}(login: $username) {
repositories(first: 100, after: $cursor) {
pageInfo {
endCursor
hasNextPage
}
nodes {
name
latestRelease {
releaseAssets(first: 25) {
nodes {
name
contentType
}
}
}
}
}
}
}
`;
let hasNextPage = true;
let cursor = null;
const releaseInfo = {};
let processedCount = 0;
while (hasNextPage) {
const variables = { username: entityName };
if (cursor) variables.cursor = cursor;
const response = await this._fetch('https://api.github.com/graphql', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ query, variables })
});
const data = await response.json();
if (data.errors) {
throw new Error(data.errors.map(e => e.message).join('; '));
}
if (!data.data || !data.data[entityType] || !data.data[entityType].repositories) {
throw new Error(`Unexpected GraphQL response structure for entity type ${entityType}.`);
}
const repositories = data.data[entityType].repositories;
repositories.nodes.forEach(repo => {
if (repo.latestRelease && repo.latestRelease.releaseAssets) {
const hasExe = repo.latestRelease.releaseAssets.nodes.some(asset =>
asset.name.toLowerCase().endsWith('.exe') ||
asset.contentType === 'application/x-msdownload' ||
asset.contentType === 'application/x-msdos-program'
);
releaseInfo[repo.name] = { has_exe: hasExe, has_releases: true };
} else {
releaseInfo[repo.name] = { has_exe: false, has_releases: false };
}
});
processedCount += repositories.nodes.length;
let denominatorString = expectedRepoCount ? `/${expectedRepoCount}` : '';
if (fetchStatusName) {
this.setStatus(`Fetching release information for ${entityName}... (${processedCount}${denominatorString} repos processed)`, 'info', fetchStatusName);
} else if (entityName === this.state.currentEntity) {
this.setStatus(`Fetching release information... (${processedCount}${denominatorString} repos processed)`, 'info');
}
hasNextPage = repositories.pageInfo.hasNextPage;
cursor = repositories.pageInfo.endCursor;
}
// Update cached data with release info
cachedData.repos = cachedData.repos.map(repo => ({
...repo,
has_exe: releaseInfo[repo.name] !== undefined ? releaseInfo[repo.name].has_exe : repo.has_exe,
has_releases: releaseInfo[repo.name] !== undefined ? releaseInfo[repo.name].has_releases : repo.has_releases
}));
cachedData.releasesCheckedAt = new Date().toISOString();
await this.setCache(entityName, cachedData);
// If this is the current entity, refresh the display and show completion
if (entityName === this.state.currentEntity) {
this.state.allRepos = cachedData.repos;
this.applyFilters();
this.setStatus(`Release information fetched for all ${processedCount} repositories.`, 'success');
}
} catch (error) {
console.error(`Failed to fetch releases for ${entityName}:`, error);
if (entityName === this.state.currentEntity) {
this.setStatus(`Failed to fetch release info: ${error.message}`, 'error');
}
}
},
async fetchReleases() {
await this.fetchReleasesForEntity(this.state.currentEntity);
},
async updateAll() {
const allEntities = await this.getAllCachedEntities();
for (const entity of allEntities) { await this.update(entity); }
this.setStatus('Finished updating all cached users.', 'success');
},
// --- TABLE RENDERING, SORTING, FILTERING ---
renderTable() {
const tbody = document.getElementById('repoTableBody');
tbody.innerHTML = '';
document.querySelectorAll('th .sort-indicator').forEach(el => el.textContent = '');
const activeTh = document.querySelector(`th[onclick="App.setSort('${this.state.sortBy}')"]`);
if (activeTh) activeTh.querySelector('.sort-indicator').textContent = this.state.sortDir === 'asc' ? '▲' : '▼';
if (this.state.filteredRepos.length === 0) { tbody.innerHTML = '<tr><td colspan="8" style="text-align:center;">No repositories match filters.</td></tr>'; return; }
const fragment = document.createDocumentFragment();
for (const repo of this.state.filteredRepos) {
const tr = document.createElement('tr');
let releaseCell = '<td class="no-exe">—</td>';
if (repo.has_releases === true && repo.has_exe === true) {
releaseCell = '<td class="has-exe" title="Has releases with .exe">Yes (.exe)</td>';
} else if (repo.has_releases === true) {
releaseCell = '<td class="has-exe" title="Has releases but no .exe">Yes</td>';
} else if (repo.has_releases === false) {
releaseCell = '<td class="no-exe">No</td>';
}
tr.innerHTML = `
<td><a href="${repo.html_url}" target="_blank" rel="noopener noreferrer" title="${repo.name}">${repo.name}</a></td>
<td>${repo.stargazers_count.toLocaleString()}</td>
<td>${repo.language || 'N/A'}</td>
<td>${new Date(repo.created_at).toLocaleDateString()}</td>
<td>${new Date(repo.updated_at).toLocaleDateString()}</td>
<td>${new Date(repo.pushed_at).toLocaleDateString()}</td>
${releaseCell}
<td title="${repo.description || ''}">${repo.description || ''}</td>`;
fragment.appendChild(tr);
}
tbody.appendChild(fragment);
},
setSort(column) {
if (this.state.isResizing) return;
this.state.sortDir = (this.state.sortBy === column && this.state.sortDir === 'desc') ? 'asc' : 'desc';
this.state.sortBy = column;
this.applyFilters();
},
_sortData(data) {
const { sortBy, sortDir } = this.state;
const dir = sortDir === 'asc' ? 1 : -1;
return [...data].sort((a, b) => {
let valA = a[sortBy], valB = b[sortBy];
// Special handling for has_exe column
if (sortBy === 'has_releases') {
// Convert to numeric for better sorting: Yes with .exe (2), Yes (1), No (0), undefined (-1)
const getVal = (repo) => {
if (repo.has_releases === true && repo.has_exe === true)
return 2;
if (repo.has_releases === true)
return 1;
if (repo.has_releases === false)
return 0;
return -1;
};
valA = getVal(a);
valB = getVal(b);
} else if (typeof valA === 'string' && sortBy.endsWith('_at')) {