-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1057 lines (932 loc) · 31.1 KB
/
script.js
File metadata and controls
1057 lines (932 loc) · 31.1 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
class PullRequest {
constructor(prData) {
this.data = prData;
}
get id() {
return this.data.id;
}
get title() {
return this.data.title;
}
get url() {
return this.data.url;
}
get number() {
return this.data.number;
}
get isDraft() {
return this.data.isDraft;
}
get isNotDraft() {
return !this.isDraft;
}
get mergeable() {
return this.data.mergeable;
}
get mergeStateStatus() {
return this.data.mergeStateStatus;
}
get createdAt() {
return this.data.createdAt;
}
get updatedAt() {
return this.data.updatedAt;
}
get repository() {
return this.data.repository;
}
get author() {
return this.data.author;
}
get baseRefName() {
return this.data.baseRefName;
}
get commits() {
return this.data.commits;
}
get reviews() {
return this.data.reviews;
}
get reviewDecision() {
return this.data.reviewDecision;
}
isReadyToBeMerged() {
return this.isNotDraft && this.hasBeenApproved() && this.hasNoConflicts();
}
isBlockedByOther() {
return this.isNotDraft && this.waitingForReview() && this.hasNoConflicts();
}
hasBeenApproved() {
if (this.hasChangesRequested()) {
return false;
}
return this.reviewDecision === "APPROVED";
// const reviews = this.reviews.nodes || [];
// const hasApprovalReview = reviews.some((review) => {
// const assignees = this.data.assignees.nodes || [];
// const isAssignee = assignees.some(
// (assignee) => assignee.login === review.author.login,
// );
// return review.state === "APPROVED" && !isAssignee;
// });
// return hasApprovalReview && !this.hasChangesRequested();
}
approvedBy() {
return [];
// const reviews = this.reviews.nodes || [];
// const approvedBy = [];
// reviews.forEach((review) => {
// if (review.state === "APPROVED") {
// approvedBy.push(review.author);
// }
// });
// return approvedBy;
}
hasChangesRequested() {
if (this.reviewDecision === "CHANGES_REQUESTED") {
return true;
}
return false;
// const reviews = this.reviews.nodes || [];
// const hasChangesRequested = reviews.some(
// (review) => review.state === "CHANGES_REQUESTED",
// );
// if (hasChangesRequested) {
// return true;
// }
// return reviews.some((review) => review.state === "COMMENTED");
}
waitingForReview() {
return (
this.isNotDraft &&
!this.hasBeenApproved() &&
!this.hasChangesRequested() &&
this.reviewDecision === "REVIEW_REQUIRED"
);
}
hasNoConflicts() {
return this.mergeable === "MERGEABLE";
}
get hasMergeConflicts() {
return this.mergeable === "CONFLICTING";
}
get hasUnknownMergeStatus() {
return this.mergeable === "UNKNOWN";
}
get isBehindMainBranch() {
return this.mergeStateStatus === "BEHIND";
}
isStale() {
const updatedDate = new Date(this.updatedAt).toDateString();
const today = new Date().toDateString();
return updatedDate !== today;
}
getJiraKey() {
const jiraMatch = this.title.match(/^\[([A-Z]+-\d+)\]/);
return jiraMatch ? jiraMatch[1] : null;
}
getTitleWithoutJira() {
return this.title.replace(/^\[([A-Z]+-\d+)\]\s*/, "");
}
get isPOC() {
return this.title.startsWith("[POC]");
}
get latestCommitSha() {
const commits = this.commits.nodes;
return commits.length > 0 ? commits[0].commit.oid : null;
}
getStatusCheckRollup() {
const commits = this.commits.nodes;
return commits.length > 0 ? commits[0].commit.statusCheckRollup : null;
}
async getCommitsBehindCount() {
if (!this.baseRefName || !this.latestCommitSha) {
return 0;
}
// Cache the result to avoid multiple API calls
if (this._behindCount !== undefined) {
return this._behindCount;
}
try {
const [owner, repo] = this.repository.nameWithOwner.split("/");
// Get the current HEAD SHA of the base branch
const currentBaseHeadSha = await window.githubAPI.getBranchHeadSha(
owner,
repo,
this.baseRefName,
(rateLimitInfo) => {
if (window.main && window.main.updateRateLimitUI) {
window.main.updateRateLimitUI(rateLimitInfo);
}
},
);
// Compare current base HEAD with PR's latest commit
const comparison = await window.githubAPI.compareCommits(
this.number,
owner,
repo,
currentBaseHeadSha.object.sha,
this.latestCommitSha,
(rateLimitInfo) => {
if (window.main && window.main.updateRateLimitUI) {
window.main.updateRateLimitUI(rateLimitInfo);
}
},
);
this._behindCount = comparison.behind_by;
return this._behindCount;
} catch (error) {
console.error("Error fetching commits behind count:", error);
this._behindCount = 0;
return 0;
}
}
}
class GitHubPRDashboard {
constructor() {
this.organization = null;
document.getElementById("orgDropdown").addEventListener("change", (e) => {
const newOrg = e.target.value;
window.dispatchEvent(
new CustomEvent("organizationChanged", {
detail: { organization: newOrg },
}),
);
});
}
hide() {
document.getElementById("mainContent")?.classList.add("hidden");
}
show(org) {
console.log("Showing main content for organization:", org);
this.organization = org;
window.githubAPI.clearPromiseCache();
window.auth.hide();
window.org.hide();
document.getElementById("mainContent")?.classList.remove("hidden");
this.loadPullRequests();
this.populateOrgDropdown(org);
}
populateOrgDropdown(selectOrganization) {
const dropdown = document.getElementById("orgDropdown");
dropdown.innerHTML = "";
window.githubAPI.getUserOrganizations().then((orgs) => {
orgs.forEach((org) => {
const option = document.createElement("option");
option.value = org.login;
option.textContent = org.login;
if (org.login === selectOrganization) {
option.selected = true;
}
dropdown.appendChild(option);
});
});
}
async loadPullRequests() {
console.log("Loading pull requests for organization:", this.organization);
if (!this.organization) {
console.warn("Cannot load pull requests: missing token or organization");
return;
}
this.showLoading(true);
this.hideError();
this.hideNoDataMessage();
try {
const data = await this.fetchPullRequests();
this.displayPullRequests(data);
this.updateLastRefreshed();
this.updateNoPrsMessage();
} catch (error) {
console.error("Error loading pull requests:", error);
this.showError(`Failed to load pull requests: ${error.message}`);
} finally {
this.showLoading(false);
}
}
async fetchPullRequests() {
return await window.githubAPI.fetchPullRequests(
this.organization,
(rateLimitInfo) => this.handleRateLimitInfo(rateLimitInfo),
);
}
displayPullRequests(data) {
console.log("Displaying pull requests:", data);
const tbody = document.getElementById("prTableBody");
const pullRequests = data.search.edges.map(
(edge) => new PullRequest(edge.node),
);
if (pullRequests.length === 0) {
this.showNoDataMessage();
return;
}
// Sort PRs with custom priority logic
pullRequests.sort((a, b) => {
const aIsReadyToBeMerged = a.isReadyToBeMerged();
const bIsReadyToBeMerged = b.isReadyToBeMerged();
// PRs that are ready to be merged go to top
if (aIsReadyToBeMerged && !bIsReadyToBeMerged) return -1;
if (!aIsReadyToBeMerged && bIsReadyToBeMerged) return 1;
const aIsBlockedByOther = a.isBlockedByOther();
const bIsBlockedByOther = b.isBlockedByOther();
// PRs that are blocked by other go to bottom
if (aIsBlockedByOther && !bIsBlockedByOther) return 1;
if (!aIsBlockedByOther && bIsBlockedByOther) return -1;
// Within same category, sort by updatedAt (oldest first)
return new Date(a.updatedAt) - new Date(b.updatedAt);
});
// Split PRs into regular and POC groups
const regularPRs = pullRequests.filter((pr) => !pr.isPOC);
const pocPRs = pullRequests.filter((pr) => pr.isPOC);
// Create new content in document fragment first
const fragment = document.createDocumentFragment();
const newRows = [];
regularPRs.forEach(async (pr, index) => {
const row = this.createPRRow(pr);
fragment.appendChild(row);
newRows.push({ pr, row, index });
});
// Build POC section
const pocContainer = document.getElementById("pocPrsContainer");
const pocFragment = document.createDocumentFragment();
const pocRows = [];
pocPRs.forEach(async (pr, index) => {
const row = this.createPRRow(pr);
pocFragment.appendChild(row);
pocRows.push({ pr, row, index });
});
tbody.innerHTML = "";
tbody.appendChild(fragment);
// Load CI status asynchronously for each PR
newRows.forEach(({ pr, row, index }) => {
this.loadCIStatusForPR(pr, row, index);
});
// Handle POC PRs section
const pocTbody = document.getElementById("pocTableBody");
pocTbody.innerHTML = "";
if (pocPRs.length > 0) {
pocContainer.style.display = "block";
document.getElementById("pocCount").textContent = pocPRs.length;
pocTbody.appendChild(pocFragment);
pocRows.forEach(({ pr, row, index }) => {
this.loadCIStatusForPR(pr, row, index);
});
} else {
pocContainer.style.display = "none";
}
}
createPRRow(pr) {
const row = document.createElement("tr");
this.applyRowStyling(row, pr);
row.appendChild(this.createCheckoutCell(pr));
row.appendChild(this.createRepositoryCell(pr));
row.appendChild(this.createAuthorCell(pr));
row.appendChild(this.createTitleCell(pr));
row.appendChild(this.createStatusCell(pr));
row.appendChild(this.createUpToDateCell(pr));
row.appendChild(this.createCICell());
row.appendChild(this.createActionsCell());
return row;
}
applyRowStyling(row, pr) {
if (pr.isBlockedByOther()) {
row.classList.add("blocked-by-other-pr");
} else if (pr.isReadyToBeMerged()) {
row.classList.add("ready-to-be-merged");
} else if (pr.isStale()) {
row.classList.add("stale-pr");
}
}
createCheckoutCell(pr) {
const cell = document.createElement("td");
cell.className = "col-checkout";
const button = document.createElement("button");
button.textContent = "⬇️";
button.title = `gh pr checkout ${pr.number}`;
button.className = "checkout-button";
button.addEventListener("click", () => {
navigator.clipboard.writeText(`gh pr checkout ${pr.number}`);
});
cell.appendChild(button);
return cell;
}
createRepositoryCell(pr) {
const cell = document.createElement("td");
cell.className = "col-repository";
cell.textContent = pr.repository.name;
cell.title = pr.repository.name; // Show full name on hover
return cell;
}
createAuthorCell(pr) {
const cell = document.createElement("td");
cell.className = "col-author";
if (pr.author) {
const avatar = document.createElement("img");
avatar.src = pr.author.avatarUrl;
avatar.alt = pr.author.login;
avatar.className = "author-avatar";
avatar.title = pr.author.login;
cell.appendChild(avatar);
} else {
cell.textContent = "?";
}
return cell;
}
createTitleCell(pr) {
const cell = document.createElement("td");
cell.className = "col-title";
const jiraKey = pr.getJiraKey();
if (jiraKey) {
this.addJiraLink(cell, jiraKey);
cell.appendChild(document.createTextNode(" "));
}
this.addPRTitleLink(cell, pr.url, pr.getTitleWithoutJira());
return cell;
}
addJiraLink(cell, jiraKey) {
const jiraLink = document.createElement("a");
jiraLink.href = `https://hoverinc.atlassian.net/browse/${jiraKey}`;
jiraLink.target = "_blank";
jiraLink.textContent = `[${jiraKey}]`;
jiraLink.className = "jira-link";
cell.appendChild(jiraLink);
}
addPRTitleLink(cell, url, title) {
const titleLink = document.createElement("a");
titleLink.href = url;
titleLink.target = "_blank";
titleLink.textContent = title;
titleLink.className = "pr-link";
cell.appendChild(titleLink);
}
addDraftBadge(cell) {
const draftBadge = document.createElement("span");
draftBadge.className = "draft-badge";
draftBadge.textContent = "DRAFT";
cell.appendChild(draftBadge);
}
createUpToDateCell(pr) {
const cell = document.createElement("td");
cell.className = "col-uptodate";
if (pr.hasMergeConflicts) {
cell.innerHTML = '<span class="status-badge error">❌ Conflicts</span>';
} else if (pr.hasUnknownMergeStatus) {
cell.innerHTML = '<span class="status-badge neutral">🔄 Loading</span>';
} else {
// Check if PR is behind using the API (more reliable than mergeStateStatus)
pr.getCommitsBehindCount()
.then((count) => {
if (count > 0) {
cell.innerHTML = `<span class="status-badge warning">⚠️ Behind (${count} commit${count === 1 ? "" : "s"})</span>`;
} else {
// PR is up to date - show nothing (empty cell)
cell.innerHTML = "";
}
})
.catch((error) => {
console.error("Error checking behind status:", error);
// On error, fall back to the old unreliable method
if (pr.isBehindMainBranch) {
cell.innerHTML =
'<span class="status-badge warning">⚠️ Behind</span>';
}
});
}
return cell;
}
createStatusCell(pr) {
const cell = document.createElement("td");
cell.className = "col-status";
if (pr.isDraft) {
this.addDraftBadge(cell);
return cell;
}
if (pr.hasBeenApproved()) {
cell.innerHTML =
'<span class="status-badge success">✅ Approved by ' +
pr
.approvedBy()
.map((a) => {
return `<img src="${a.avatarUrl}" alt="${a.login}" class="author-avatar">`;
})
.join(", ") +
"</span>";
} else if (pr.hasChangesRequested()) {
cell.innerHTML =
'<span class="status-badge warning">🔄 Changes Requested</span>';
} else if (pr.waitingForReview()) {
console.log("waitingForReview", pr);
cell.innerHTML =
'<span class="status-badge neutral">⏳ Waiting for Review</span>';
}
return cell;
}
createCICell() {
const cell = document.createElement("td");
cell.className = "col-ci";
cell.innerHTML = '<span class="status-badge neutral">🔄 Loading...</span>';
return cell;
}
createActionsCell() {
const cell = document.createElement("td");
cell.className = "col-actions";
return cell;
}
async loadCIStatusForPR(pr, row, index) {
try {
const sha = pr.latestCommitSha;
if (!sha) {
this.updateCICell(
row,
{
text: "sha latest commit not found",
class: "neutral",
failedChecks: [],
},
pr,
);
return;
}
const statusRollup = pr.getStatusCheckRollup();
// Get basic status from GraphQL first
let ciStatus = {
text: "No CI",
class: "neutral",
failedChecks: [],
};
if (statusRollup) {
switch (statusRollup.state) {
case "SUCCESS":
ciStatus = {
text: "✅ Passed",
class: "success",
failedChecks: [],
};
break;
case "FAILURE":
case "ERROR":
// Only use REST API when there are actual failures
const [owner, repo] = pr.repository.nameWithOwner.split("/");
const failedChecks = await this.fetchFailedChecks(owner, repo, sha);
ciStatus = {
text: statusRollup.state === "FAILURE" ? "❌ Failed" : "💥 Error",
class: "error",
failedChecks: failedChecks,
};
break;
case "PENDING":
ciStatus = {
text: "🟡 Running",
class: "warning",
failedChecks: [],
};
break;
}
}
this.updateCICell(row, ciStatus, pr);
} catch (error) {
console.warn(`Failed to load CI status for PR ${pr.number}:`, error);
this.updateCICell(
row,
{
text: "Error",
class: "error",
failedChecks: [],
},
pr,
);
}
}
async fetchFailedChecks(owner, repo, sha) {
return await window.githubAPI.fetchFailedChecks(
owner,
repo,
sha,
(rateLimitInfo) => this.handleRateLimitInfo(rateLimitInfo),
);
}
updateCICell(row, ciStatus, pr = null) {
const ciCell = row.querySelector(".col-ci");
const actionsCell = row.querySelector(".col-actions");
if (ciStatus.class === "error" && ciStatus.failedChecks.length > 0) {
const failedChecks = ciStatus.failedChecks;
const showExpandButton = failedChecks.length > 3;
const visibleChecks = showExpandButton
? failedChecks.slice(0, 2)
: failedChecks;
const hiddenChecks = showExpandButton ? failedChecks.slice(2) : [];
const expandButton = showExpandButton
? `<li class="expand-checks-item"><button class="expand-checks-button" onclick="window.main.toggleFailedChecks(this)" data-expanded="false">more... (${hiddenChecks.length})</button></li>`
: "";
ciCell.innerHTML = `
<div class="ci-status-container">
<div class="ci-status-left">
<span class="status-badge ${ciStatus.class}">${ciStatus.text}</span>
</div>
<ul class="failed-checks-list">
${visibleChecks
.map(
(check) =>
`<li><a href="${check.url}" target="_blank" class="check-link">${check.name}</a></li>`,
)
.join("")}
${expandButton}
${
hiddenChecks.length > 0
? `<div class="hidden-checks" style="display: none;">
${hiddenChecks
.map(
(check) =>
`<li><a href="${check.url}" target="_blank" class="check-link">${check.name}</a></li>`,
)
.join("")}
</div>`
: ""
}
</ul>
</div>
`;
} else {
ciCell.innerHTML = `<span class="status-badge ${ciStatus.class}">${ciStatus.text}</span>`;
}
// Update Actions column based on PR state
this.updateActionsCell(actionsCell, pr, ciStatus);
}
updateActionsCell(actionsCell, pr, ciStatus) {
const actions = [];
// Add convert draft button for draft PRs
if (pr && pr.isDraft) {
actions.push(
`<button class="convert-draft-button" onclick="window.main.handleConvertDraftToOpen('${pr.id}', this)" title="Convert to ready for review">📝 Draft => Open</button>`,
);
}
// Add re-run button for failed CI
if (pr && ciStatus.class === "error" && ciStatus.failedChecks.length > 0) {
actions.push(
`<button class="rerun-button" onclick="window.main.handleRerunFailedJobs('${pr.repository.nameWithOwner}', '${pr.latestCommitSha}', this)" title="Re-run failed jobs">🔄 Re-run</button>`,
);
}
// Set initial actions
actionsCell.innerHTML = actions.join(" ");
// Check if PR is behind using the API and add sync button asynchronously
if (pr && pr.hasNoConflicts()) {
pr.getCommitsBehindCount()
.then((count) => {
if (count > 0) {
const syncButton = `<button class="sync-button" onclick="window.main.handleSyncWithBaseBranch('${pr.repository.nameWithOwner}', ${pr.number}, '${pr.baseRefName}', this)" title="Sync with base branch">🔄 Sync with ${pr.baseRefName}</button>`;
// Add sync button to existing actions
const currentActions = actionsCell.innerHTML
? [actionsCell.innerHTML]
: [];
currentActions.push(syncButton);
actionsCell.innerHTML = currentActions.join(" ");
}
})
.catch((error) => {
console.error("Error checking behind status for sync button:", error);
});
}
}
showLoading(show) {
const spinner = document.getElementById("loadingSpinner");
if (show) {
spinner.style.display = "block";
// Force reflow to ensure display change is applied before opacity transition
spinner.offsetHeight;
} else {
setTimeout(() => {
spinner.style.display = "none";
}, 200); // Match the CSS transition duration
}
}
showError(message) {
const errorDiv = document.getElementById("errorMessage");
errorDiv.textContent = message;
errorDiv.style.display = "block";
}
hideError() {
document.getElementById("errorMessage").style.display = "none";
}
showNoDataMessage() {
document.getElementById("prTableBody").innerHTML = "";
document.getElementById("noPrsMessage").style.display = "block";
}
hideNoDataMessage() {
document.getElementById("noPrsMessage").style.display = "none";
}
updateNoPrsMessage() {
const noPrsText = document.getElementById("noPrsText");
if (noPrsText && this.organization) {
noPrsText.textContent = `No assigned pull requests found in the ${this.organization} organization.`;
}
}
handleRateLimitInfo(rateLimitInfo) {
if (!rateLimitInfo) return;
const elementId =
rateLimitInfo.type === "graphql" ? "rateLimit" : "restRateLimit";
const prefix = rateLimitInfo.type === "graphql" ? "GraphQL" : "REST";
const rateLimitElement = document.getElementById(elementId);
if (rateLimitElement) {
rateLimitElement.textContent = `${prefix}: ${rateLimitInfo.remaining}/${rateLimitInfo.limit}${rateLimitInfo.resetString}`;
rateLimitElement.className = rateLimitInfo.isLow
? "rate-limit-low"
: "rate-limit-ok";
}
}
updateLastRefreshed() {
this.lastRefreshTime = new Date();
this.updateRelativeTime();
// Update relative time every minute
if (this.relativeTimeInterval) {
clearInterval(this.relativeTimeInterval);
}
this.relativeTimeInterval = setInterval(
() => this.updateRelativeTime(),
60000,
);
}
updateRelativeTime() {
if (!this.lastRefreshTime) return;
const now = new Date();
const diffMs = now - this.lastRefreshTime;
const diffMinutes = Math.floor(diffMs / 60000);
let relativeText;
if (diffMinutes < 1) {
relativeText = "just now";
} else if (diffMinutes === 1) {
relativeText = "1 minute ago";
} else if (diffMinutes < 60) {
relativeText = `${diffMinutes} minutes ago`;
} else {
const diffHours = Math.floor(diffMinutes / 60);
if (diffHours === 1) {
relativeText = "1 hour ago";
} else {
relativeText = `${diffHours} hours ago`;
}
}
document.getElementById("lastUpdated").textContent =
`Last updated: ${relativeText}`;
}
/**
* Shared button state management utilities
*/
setButtonLoading(button, loadingText) {
button.dataset.originalText = button.textContent;
button.textContent = loadingText;
button.disabled = true;
button.classList.add("loading");
}
setButtonSuccess(button, successText, resetDelay = 3000) {
button.textContent = successText;
button.classList.remove("loading");
button.classList.add("success");
this.scheduleButtonReset(button, resetDelay);
}
setButtonWarning(button, warningText, resetDelay = 5000) {
button.textContent = warningText;
button.classList.remove("loading");
button.classList.add("warning");
this.scheduleButtonReset(button, resetDelay);
}
setButtonError(button, errorText, resetDelay = 3000) {
button.textContent = errorText;
button.classList.remove("loading");
button.classList.add("error");
this.scheduleButtonReset(button, resetDelay);
}
scheduleButtonReset(button, delay) {
setTimeout(() => {
this.resetButton(button);
}, delay);
}
resetButton(button) {
const originalText = button.dataset.originalText || button.textContent;
button.textContent = originalText;
button.disabled = false;
button.classList.remove("loading", "success", "warning", "error");
delete button.dataset.originalText;
}
/**
* Generic action button handler
* @param {HTMLButtonElement} button - The button that was clicked
* @param {Object} actionConfig - Configuration object
* @param {string} actionConfig.loadingText - Text to show while loading
* @param {Function} actionConfig.action - Async function to execute
* @param {Function} actionConfig.onSuccess - Function to handle success result
* @param {Function} actionConfig.onError - Function to handle error (optional)
*/
async handleActionButton(button, actionConfig) {
this.setButtonLoading(button, actionConfig.loadingText);
try {
const result = await actionConfig.action();
actionConfig.onSuccess(result);
} catch (error) {
console.error(`Action button error:`, error);
if (actionConfig.onError) {
actionConfig.onError(error);
} else {
this.setButtonError(button, "❌ Error");
}
}
}
/**
* Handle converting a draft PR to ready for review
* @param {string} nodeId - Pull request node ID (GraphQL ID)
* @param {HTMLButtonElement} button - The button that was clicked
*/
async handleConvertDraftToOpen(nodeId, button) {
await this.handleActionButton(button, {
loadingText: "⏳ Converting...",
action: async () => {
return await window.githubAPI.markPullRequestReadyForReview(
nodeId,
(rateLimitInfo) => this.handleRateLimitInfo(rateLimitInfo),
);
},
onSuccess: (result) => {
this.setButtonSuccess(button, "✅ Ready for Review");
// Refresh the PR data to update the UI
setTimeout(() => {
this.loadPullRequests();
}, 1000);
},
onError: (error) => {
console.error("Error converting draft to open:", error);
this.setButtonError(button, "❌ Failed");
},
});
}
/**
* Handle syncing a PR branch with the base branch
* @param {string} repoNameWithOwner - Repository name with owner (e.g., "owner/repo")
* @param {number} pullNumber - Pull request number
* @param {string} baseBranch - Base branch name
* @param {HTMLButtonElement} button - The button that was clicked
*/
async handleSyncWithBaseBranch(
repoNameWithOwner,
pullNumber,
baseBranch,
button,
) {
const [owner, repo] = repoNameWithOwner.split("/");
await this.handleActionButton(button, {
loadingText: "⏳ Syncing...",
action: async () => {
return await window.githubAPI.updatePullRequestBranch(
owner,
repo,
pullNumber,
(rateLimitInfo) => this.handleRateLimitInfo(rateLimitInfo),
);
},
onSuccess: (result) => {
this.setButtonSuccess(button, "✅ Synced");
// Refresh the PR data to update the UI
setTimeout(() => {
this.loadPullRequests();
}, 1000);
},
onError: (error) => {
console.error("Error syncing with base branch:", error);
this.setButtonError(button, "❌ Failed");
},
});
}
/**
* Handle re-running failed CI jobs for a PR
* @param {string} repoNameWithOwner - Repository name with owner (e.g., "owner/repo")
* @param {string} sha - Commit SHA
* @param {HTMLButtonElement} button - The button that was clicked
*/
async handleRerunFailedJobs(repoNameWithOwner, sha, button) {
const [owner, repo] = repoNameWithOwner.split("/");
// Update button state to loading
const originalText = button.textContent;
button.textContent = "⏳ Running...";
button.disabled = true;
button.classList.add("loading");
try {
// Get workflow runs for this commit
const workflowRuns = await window.githubAPI.fetchWorkflowRuns(
owner,
repo,
sha,
(rateLimitInfo) => this.handleRateLimitInfo(rateLimitInfo),
);
// Find failed or cancelled runs
const failedRuns = workflowRuns.filter(
(run) => run.conclusion === "failure" || run.conclusion === "cancelled",
);
if (failedRuns.length === 0) {
button.textContent = "✅ No Failed Jobs";
button.classList.remove("loading");
button.classList.add("success");
setTimeout(() => {
button.textContent = originalText;
button.disabled = false;
button.classList.remove("success");
}, 3000);
return;
}
// Re-run failed jobs for each failed run
let successCount = 0;
for (const run of failedRuns) {
const success = await window.githubAPI.rerunFailedJobs(
owner,
repo,
run.id,
(rateLimitInfo) => this.handleRateLimitInfo(rateLimitInfo),
);