-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
1209 lines (1069 loc) · 37.9 KB
/
Copy pathcontent.js
File metadata and controls
1209 lines (1069 loc) · 37.9 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
(() => {
const STORAGE_KEY = "md_expert_pr_config";
const NAV_CACHE_KEY = "md_expert_pr_nav_cache";
const STYLE_ID = "md-expert-pr-style";
const PANEL_ID = "md-expert-pr-panel";
const BADGE_ID = "md-expert-pr-badge";
const NAV_BUTTONS_ID = "md-expert-pr-nav-buttons";
const NAV_CACHE_MAX_AGE_MS = 1000 * 60 * 60 * 8;
const DEFAULT_CONFIG = {
apiKey: "",
settingsOpen: false
};
const state = {
config: loadConfig(),
currentResult: null,
listCache: new Map(),
mountRetryTimer: null,
mountRetryCount: 0,
keyboardListenerAttached: false,
navMountRetryTimer: null,
navMountRetryCount: 0,
navViewportListenerAttached: false,
navRepositionFrame: null
};
function loadConfig() {
const raw = window.localStorage.getItem(STORAGE_KEY);
if (!raw) return { ...DEFAULT_CONFIG };
try {
const parsed = JSON.parse(raw);
return { ...DEFAULT_CONFIG, ...parsed };
} catch (error) {
return { ...DEFAULT_CONFIG };
}
}
function saveConfig(nextConfig) {
state.config = { ...DEFAULT_CONFIG, ...nextConfig };
window.localStorage.setItem(STORAGE_KEY, JSON.stringify(state.config));
}
function isPullDetailPage() {
return /\/pull\/(\d+)(\/|$)/.test(window.location.pathname);
}
function isPullListPage() {
return /\/pulls(\/|$)/.test(window.location.pathname);
}
function normalizePullPath(urlLike) {
try {
const url = new URL(String(urlLike || ""), window.location.origin);
const match = url.pathname.match(/^\/[^/]+\/[^/]+\/pull\/\d+/);
return match ? match[0] : null;
} catch (error) {
return null;
}
}
function getRepoPathFromPullPath(pullPath) {
const match = String(pullPath || "").match(/^\/[^/]+\/[^/]+/);
return match ? match[0] : null;
}
function readNavigationCache() {
const raw = window.localStorage.getItem(NAV_CACHE_KEY);
if (!raw) return null;
try {
const parsed = JSON.parse(raw);
if (!parsed || !Array.isArray(parsed.pullPaths)) return null;
if (typeof parsed.updatedAt !== "number") return null;
return parsed;
} catch (error) {
return null;
}
}
function writeNavigationCache(pullPaths) {
if (!Array.isArray(pullPaths) || !pullPaths.length) return;
const repoPath = getRepoPathFromPullPath(pullPaths[0]);
if (!repoPath) return;
window.localStorage.setItem(
NAV_CACHE_KEY,
JSON.stringify({
repoPath,
listPath: window.location.pathname,
listSearch: window.location.search || "",
pullPaths,
updatedAt: Date.now()
})
);
}
function cachePullListOrder() {
if (!isPullListPage()) return;
const rows = document.querySelectorAll("div.js-issue-row");
const pullPaths = [];
const seen = new Set();
rows.forEach((row) => {
const titleLink =
row.querySelector("a[data-hovercard-type='pull_request']") ||
row.querySelector("a[id^='issue_']") ||
row.querySelector("a.Link--primary[href*='/pull/']");
if (!titleLink) return;
const pullPath = normalizePullPath(titleLink.getAttribute("href") || titleLink.href);
if (!pullPath || seen.has(pullPath)) return;
seen.add(pullPath);
pullPaths.push(pullPath);
});
writeNavigationCache(pullPaths);
}
function isEditableTarget(target) {
const element = target instanceof Element ? target : null;
if (!element) return false;
if (element.closest("input, textarea, select, button, [contenteditable=''], [contenteditable='true'], [role='textbox']")) {
return true;
}
return false;
}
function getAdjacentPullPath(direction) {
const currentPullPath = normalizePullPath(window.location.href);
if (!currentPullPath) return null;
const cache = readNavigationCache();
if (!cache) return null;
if (!Array.isArray(cache.pullPaths) || cache.pullPaths.length < 2) return null;
if (Date.now() - cache.updatedAt > NAV_CACHE_MAX_AGE_MS) return null;
const repoPath = getRepoPathFromPullPath(currentPullPath);
if (!repoPath || cache.repoPath !== repoPath) return null;
const currentIndex = cache.pullPaths.indexOf(currentPullPath);
if (currentIndex === -1) return null;
const targetIndex = (currentIndex + direction + cache.pullPaths.length) % cache.pullPaths.length;
if (targetIndex === currentIndex) return null;
return cache.pullPaths[targetIndex];
}
function navigateToAdjacentPull(direction) {
const targetPath = getAdjacentPullPath(direction);
if (!targetPath) return false;
window.location.assign(targetPath);
return true;
}
function handlePullNavigationShortcut(event) {
if (!isPullDetailPage()) return;
if (event.defaultPrevented) return;
if (event.metaKey || event.ctrlKey || event.altKey) return;
if (isEditableTarget(event.target)) return;
let direction = 0;
if (event.key === "ArrowRight") direction = 1;
if (event.key === "ArrowLeft") direction = -1;
if (event.key === "]") direction = 1;
if (event.key === "[") direction = -1;
if (!direction) return;
const navigated = navigateToAdjacentPull(direction);
if (!navigated) return;
event.preventDefault();
event.stopPropagation();
}
function ensureKeyboardShortcutBinding() {
if (state.keyboardListenerAttached) return;
state.keyboardListenerAttached = true;
document.addEventListener("keydown", handlePullNavigationShortcut, true);
}
function clearNavMountRetry() {
if (!state.navMountRetryTimer) return;
window.clearTimeout(state.navMountRetryTimer);
state.navMountRetryTimer = null;
}
function scheduleNavMountRetry() {
if (state.navMountRetryTimer || state.navMountRetryCount >= 40 || !isPullDetailPage()) return;
state.navMountRetryTimer = window.setTimeout(() => {
state.navMountRetryTimer = null;
state.navMountRetryCount += 1;
ensureNavButtons();
}, 250);
}
function queueNavButtonsRefresh() {
if (state.navRepositionFrame !== null) return;
state.navRepositionFrame = window.requestAnimationFrame(() => {
state.navRepositionFrame = null;
ensureNavButtons();
});
}
function ensureNavViewportBinding() {
if (state.navViewportListenerAttached) return;
state.navViewportListenerAttached = true;
window.addEventListener("resize", queueNavButtonsRefresh);
window.addEventListener("scroll", queueNavButtonsRefresh, true);
}
function getCodeButtonMatchScore(element) {
const text = normalizeText(element.textContent);
const ariaLabel = normalizeText(element.getAttribute("aria-label"));
let score = 0;
if (text === "code") score += 4;
else if (text.startsWith("code ")) score += 2;
if (ariaLabel === "code") score += 3;
else if (ariaLabel.startsWith("code ")) score += 2;
return score;
}
function findCodeButton() {
const sidebar = findSidebar();
const roots = [sidebar, document].filter(Boolean);
const seen = new Set();
const candidates = [];
roots.forEach((root) => {
root.querySelectorAll("button, summary, a").forEach((element) => {
if (seen.has(element)) return;
seen.add(element);
if (!isVisibleElement(element)) return;
if (element.closest(`#${PANEL_ID}`) || element.closest(`#${NAV_BUTTONS_ID}`)) return;
const textScore = getCodeButtonMatchScore(element);
if (!textScore) return;
const classText = normalizeText(element.className);
const rect = element.getBoundingClientRect();
let score = textScore;
if (sidebar && sidebar.contains(element)) score += 8;
if (classText.includes("btn") || classText.includes("button")) score += 2;
if (element.closest("details")) score += 1;
if (rect.width >= 80 && rect.width <= 240) score += 2;
if (rect.height >= 28 && rect.height <= 44) score += 1;
candidates.push({ element, score });
});
});
if (!candidates.length) return null;
candidates.sort((a, b) => b.score - a.score);
return candidates[0].element;
}
function updateNavButtonsState(wrapper) {
if (!wrapper) return;
const prevButton = wrapper.querySelector("[data-nav='prev']");
const nextButton = wrapper.querySelector("[data-nav='next']");
if (!prevButton || !nextButton) return;
const canGoPrev = Boolean(getAdjacentPullPath(-1));
const canGoNext = Boolean(getAdjacentPullPath(1));
prevButton.disabled = !canGoPrev;
nextButton.disabled = !canGoNext;
const disabledTitle = "Visit the repo PR list to enable";
prevButton.title = canGoPrev ? "Previous PR (ArrowLeft)" : disabledTitle;
nextButton.title = canGoNext ? "Next PR (ArrowRight)" : disabledTitle;
}
function ensureNavButtons() {
const existing = document.getElementById(NAV_BUTTONS_ID);
if (!isPullDetailPage()) {
if (existing) existing.remove();
clearNavMountRetry();
state.navMountRetryCount = 0;
return;
}
const codeButton = findCodeButton();
if (!codeButton) {
if (existing) existing.remove();
scheduleNavMountRetry();
return;
}
const codeRect = codeButton.getBoundingClientRect();
if (!codeRect.width || !codeRect.height) {
scheduleNavMountRetry();
return;
}
let wrapper = existing;
if (!wrapper) {
wrapper = document.createElement("div");
wrapper.id = NAV_BUTTONS_ID;
wrapper.innerHTML = `
<button class="md-pr-nav-btn" type="button" data-nav="prev" aria-label="Previous pull request">←</button>
<button class="md-pr-nav-btn" type="button" data-nav="next" aria-label="Next pull request">→</button>
`;
wrapper.querySelector("[data-nav='prev']")?.addEventListener("click", (event) => {
event.preventDefault();
navigateToAdjacentPull(-1);
});
wrapper.querySelector("[data-nav='next']")?.addEventListener("click", (event) => {
event.preventDefault();
navigateToAdjacentPull(1);
});
}
if (wrapper.parentElement !== document.body) {
document.body.appendChild(wrapper);
}
wrapper.style.left = `${Math.round(window.scrollX + codeRect.left)}px`;
wrapper.style.top = `${Math.round(window.scrollY + codeRect.bottom + 6)}px`;
wrapper.style.width = `${Math.round(codeRect.width)}px`;
wrapper.style.setProperty("--md-pr-nav-btn-height", `${Math.round(codeRect.height)}px`);
const borderRadius = window.getComputedStyle(codeButton).borderRadius;
if (borderRadius) {
wrapper.style.setProperty("--md-pr-nav-btn-radius", borderRadius);
}
updateNavButtonsState(wrapper);
clearNavMountRetry();
state.navMountRetryCount = 0;
}
function canUseBackground() {
return typeof chrome !== "undefined" && chrome.runtime && chrome.runtime.sendMessage;
}
function fetchViaBackground(url, apiKey) {
if (!canUseBackground()) return Promise.resolve(null);
return new Promise((resolve) => {
chrome.runtime.sendMessage(
{ type: "md-expert-pr-check", url, apiKey },
(response) => {
if (chrome.runtime.lastError) {
resolve(null);
return;
}
resolve(response);
}
);
});
}
function ensureStyles() {
if (document.getElementById(STYLE_ID)) return;
const style = document.createElement("style");
style.id = STYLE_ID;
style.textContent = `
#${PANEL_ID} {
color: var(--fgColor-default, #24292f);
}
#${PANEL_ID}.discussion-sidebar-item {
margin-top: 0;
}
#${PANEL_ID}.md-pr-fallback {
margin: 16px 0;
}
#${PANEL_ID} .md-pr-panel {
font-size: 12px;
line-height: 1.5;
}
#${PANEL_ID} .md-pr-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 6px;
}
#${PANEL_ID} .md-pr-heading {
margin: 0;
}
#${PANEL_ID} .md-pr-gear {
border: none;
background: transparent;
color: var(--fgColor-muted, #57606a);
width: 20px;
height: 20px;
padding: 0;
display: inline-flex;
align-items: center;
justify-content: center;
cursor: pointer;
}
#${PANEL_ID} .md-pr-gear:hover {
color: var(--fgColor-default, #24292f);
}
#${PANEL_ID} .md-pr-settings {
display: none;
margin-top: 8px;
}
#${PANEL_ID} .md-pr-settings.md-pr-open {
display: block;
}
#${PANEL_ID} .md-pr-settings label {
display: block;
margin-bottom: 4px;
font-size: 12px;
color: var(--fgColor-muted, #57606a);
}
#${PANEL_ID} .md-pr-settings input[type="password"] {
width: 100%;
border: 1px solid var(--borderColor-default, #d0d7de);
border-radius: 6px;
padding: 5px 8px;
font-size: 12px;
color: var(--fgColor-default, #24292f);
background: var(--bgColor-default, #ffffff);
}
#${PANEL_ID} .md-pr-status {
color: var(--fgColor-muted, #57606a);
}
#${PANEL_ID} .md-pr-warning {
color: var(--fgColor-danger, #cf222e);
}
#${PANEL_ID} .md-pr-details {
color: var(--fgColor-muted, #57606a);
}
#${PANEL_ID} .md-pr-summary {
margin-bottom: 8px;
color: var(--fgColor-default, #24292f);
}
#${PANEL_ID} .md-pr-card-header {
display: flex;
gap: 8px;
align-items: flex-start;
}
#${PANEL_ID} .md-pr-avatar {
width: 32px;
height: 32px;
border-radius: 50%;
overflow: hidden;
background: var(--bgColor-muted, #f6f8fa);
display: inline-flex;
align-items: center;
justify-content: center;
font-weight: 600;
color: var(--fgColor-muted, #57606a);
flex-shrink: 0;
}
#${PANEL_ID} .md-pr-avatar img {
width: 100%;
height: 100%;
object-fit: cover;
}
#${PANEL_ID} .md-pr-name {
font-size: 13px;
font-weight: 600;
color: var(--fgColor-default, #24292f);
}
#${PANEL_ID} .md-pr-meta {
color: var(--fgColor-muted, #57606a);
}
#${PANEL_ID} .md-pr-link {
color: var(--fgColor-accent, #0969da);
text-decoration: none;
}
#${PANEL_ID} .md-pr-link:hover {
text-decoration: underline;
}
#${PANEL_ID} .md-pr-stats {
margin-top: 8px;
}
#${PANEL_ID} .md-pr-stat-item {
color: var(--fgColor-default, #24292f);
}
#${PANEL_ID} .md-pr-stat-label {
color: var(--fgColor-muted, #57606a);
}
#${PANEL_ID} .md-pr-stat-sep {
margin: 0 4px;
color: var(--fgColor-muted, #57606a);
}
#${PANEL_ID} .md-pr-section {
margin-top: 8px;
}
#${PANEL_ID} .md-pr-section-title {
margin-bottom: 2px;
font-weight: 600;
color: var(--fgColor-muted, #57606a);
}
#${PANEL_ID} .md-pr-ecosystems {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
#${PANEL_ID} .md-pr-ecosystem-pill {
color: var(--fgColor-accent, #0969da);
text-decoration: none;
}
#${PANEL_ID} .md-pr-ecosystem-pill:hover {
text-decoration: underline;
}
#${PANEL_ID} .md-pr-project-list {
display: flex;
flex-direction: column;
gap: 2px;
}
#${PANEL_ID} .md-pr-project-item {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 8px;
}
#${PANEL_ID} .md-pr-project-meta {
color: var(--fgColor-muted, #57606a);
flex-shrink: 0;
}
#${PANEL_ID} .md-pr-powered {
margin-top: 8px;
font-size: 11px;
color: var(--fgColor-muted, #57606a);
opacity: 0.65;
}
#${PANEL_ID} .md-pr-powered-link {
color: inherit;
text-decoration: none;
}
#${PANEL_ID} .md-pr-powered-link:hover {
text-decoration: underline;
}
#${NAV_BUTTONS_ID} {
position: absolute;
z-index: 30;
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 6px;
}
#${NAV_BUTTONS_ID} .md-pr-nav-btn {
appearance: none;
border: 1px solid var(--button-default-borderColor-rest, var(--borderColor-default, #d0d7de));
background: var(--button-default-bgColor-rest, var(--bgColor-muted, #f6f8fa));
color: var(--button-default-fgColor-rest, var(--fgColor-default, #24292f));
border-radius: var(--md-pr-nav-btn-radius, 6px);
height: var(--md-pr-nav-btn-height, 32px);
padding: 0;
display: inline-flex;
align-items: center;
justify-content: center;
font-size: 14px;
font-weight: 600;
font-family: inherit;
line-height: 1;
letter-spacing: 0;
cursor: pointer;
}
#${NAV_BUTTONS_ID} .md-pr-nav-btn:hover:not(:disabled) {
background: var(--button-default-bgColor-hover, var(--bgColor-neutral-muted, #f3f4f6));
}
#${NAV_BUTTONS_ID} .md-pr-nav-btn:disabled {
cursor: default;
opacity: 0.55;
}
.md-pr-list-indicator {
display: inline-flex;
align-items: center;
justify-content: center;
width: 8px;
height: 8px;
border-radius: 999px;
margin-left: 6px;
border: 1px solid #d0d7de;
}
.md-pr-list-indicator.md-pr-list-expert {
background: #2da44e;
border-color: #2da44e;
}
.md-pr-list-indicator.md-pr-list-missing {
background: #afb8c1;
}
#${BADGE_ID} {
display: inline-flex;
align-items: center;
gap: 6px;
margin-left: 8px;
padding: 2px 8px;
border-radius: 999px;
font-size: 11px;
font-weight: 600;
}
#${BADGE_ID}.md-pr-badge-error {
background: #ffe4e8;
color: #9f1239;
}
#${BADGE_ID}.md-pr-badge-success {
background: #dcfce7;
color: #166534;
}
`;
document.head.appendChild(style);
}
function clearMountRetry() {
if (!state.mountRetryTimer) return;
window.clearTimeout(state.mountRetryTimer);
state.mountRetryTimer = null;
}
function scheduleMountRetry() {
if (state.mountRetryTimer || state.mountRetryCount >= 40 || !isPullDetailPage()) return;
state.mountRetryTimer = window.setTimeout(() => {
state.mountRetryTimer = null;
state.mountRetryCount += 1;
ensurePanel();
}, 250);
}
function normalizeText(value) {
return String(value || "").replace(/\s+/g, " ").trim().toLowerCase();
}
function isVisibleElement(element) {
return Boolean(element && element.isConnected && element.getClientRects().length > 0);
}
function findSidebar() {
const selectors = [
".discussion-sidebar",
".Layout-sidebar .discussion-sidebar",
".Layout-sidebar",
".js-discussion-sidebar",
"#partial-discussion-sidebar",
"[data-testid*='sidebar']",
"aside"
];
const seen = new Set();
const candidates = [];
for (const selector of selectors) {
document.querySelectorAll(selector).forEach((element) => {
if (seen.has(element)) return;
seen.add(element);
candidates.push(element);
});
}
const scoredVisible = candidates
.filter((element) => isVisibleElement(element))
.map((element) => {
const text = normalizeText(element.textContent);
let score = 0;
if (text.includes("reviewers")) score += 5;
if (text.includes("assignees")) score += 2;
if (normalizeText(element.className).includes("sidebar")) score += 2;
if (element.tagName === "ASIDE") score += 1;
return { element, score };
})
.sort((a, b) => b.score - a.score);
if (scoredVisible.length) return scoredVisible[0].element;
if (candidates.length) return candidates[0];
return null;
}
function findReviewersSection(sidebar) {
const roots = [];
if (sidebar) roots.push(sidebar);
const discoveredSidebar = findSidebar();
if (discoveredSidebar && !roots.includes(discoveredSidebar)) roots.push(discoveredSidebar);
roots.push(document);
for (const root of roots) {
const byClass = root.querySelector(
".discussion-sidebar-item.sidebar-reviewers, .js-discussion-sidebar-item.sidebar-reviewers"
);
if (byClass && isVisibleElement(byClass)) return byClass;
const byTestId = root.querySelector("[data-testid*='reviewer']");
if (byTestId && isVisibleElement(byTestId)) {
const item = byTestId.closest(
".discussion-sidebar-item, .js-discussion-sidebar-item, [class*='sidebar-item'], section, li"
);
if (item && isVisibleElement(item)) return item;
}
const headings = root.querySelectorAll(".discussion-sidebar-heading, h2, h3, h4, [role='heading']");
for (const heading of headings) {
if (normalizeText(heading.textContent) !== "reviewers") continue;
const item = heading.closest(
".discussion-sidebar-item, .js-discussion-sidebar-item, [class*='sidebar-item'], section, li, aside"
);
if (item && isVisibleElement(item)) return item;
}
}
return null;
}
function findFallbackAnchor() {
const selectors = [
".gh-header-show",
".gh-header-meta",
".js-pull-discussion-timeline",
"main [data-testid='issue-viewer']",
"main"
];
for (const selector of selectors) {
const element = document.querySelector(selector);
if (element && isVisibleElement(element)) return element;
}
return null;
}
function setWrapperPlacementClass(wrapper, inSidebar) {
if (inSidebar) {
wrapper.classList.add("discussion-sidebar-item");
wrapper.classList.remove("md-pr-fallback");
return;
}
wrapper.classList.remove("discussion-sidebar-item");
wrapper.classList.add("md-pr-fallback");
}
function mountPanel(wrapper) {
const reviewersSection = findReviewersSection();
if (reviewersSection) {
setWrapperPlacementClass(wrapper, true);
if (reviewersSection.nextElementSibling !== wrapper) {
reviewersSection.insertAdjacentElement("afterend", wrapper);
}
return true;
}
const sidebar = findSidebar();
if (sidebar) {
setWrapperPlacementClass(wrapper, true);
if (wrapper.parentElement !== sidebar) {
sidebar.appendChild(wrapper);
}
return true;
}
const fallbackAnchor = findFallbackAnchor();
if (fallbackAnchor) {
setWrapperPlacementClass(wrapper, false);
if (fallbackAnchor.tagName === "MAIN") {
if (wrapper.parentElement !== fallbackAnchor || fallbackAnchor.firstElementChild !== wrapper) {
fallbackAnchor.prepend(wrapper);
}
return true;
}
if (fallbackAnchor.nextElementSibling !== wrapper) {
fallbackAnchor.insertAdjacentElement("afterend", wrapper);
}
return true;
}
return false;
}
function ensurePanel() {
const existing = document.getElementById(PANEL_ID);
if (!isPullDetailPage()) {
if (existing) existing.remove();
clearMountRetry();
state.mountRetryCount = 0;
removeBadge();
return;
}
ensureStyles();
if (existing) {
if (!mountPanel(existing)) {
scheduleMountRetry();
return;
}
clearMountRetry();
state.mountRetryCount = 0;
updatePanel(existing);
return;
}
const wrapper = document.createElement("div");
wrapper.id = PANEL_ID;
wrapper.innerHTML = `
<div class="md-pr-panel">
<div class="md-pr-header">
<h3 class="discussion-sidebar-heading md-pr-heading">Contributor insights</h3>
<button class="md-pr-gear" type="button" aria-label="Settings">
<span aria-hidden="true">⚙</span>
</button>
</div>
<div class="md-pr-body">
<div class="md-pr-summary"></div>
<div class="md-pr-status"></div>
<div class="md-pr-details"></div>
</div>
<div class="md-pr-settings ${state.config.settingsOpen ? "md-pr-open" : ""}">
<label for="${PANEL_ID}-api-key">API key (optional)</label>
<input id="${PANEL_ID}-api-key" type="password" data-config="apiKey" />
<div class="md-pr-status"></div>
</div>
<div class="md-pr-powered">Powered by the <a class="md-pr-powered-link" href="https://explore.market.dev" target="_blank" rel="noopener noreferrer">Open Source Explorer</a></div>
</div>
`;
wrapper.querySelector(".md-pr-gear").addEventListener("click", () => {
const settings = wrapper.querySelector(".md-pr-settings");
const open = settings.classList.toggle("md-pr-open");
saveConfig({ ...state.config, settingsOpen: open });
});
wrapper.querySelectorAll("[data-config]").forEach((input) => {
const key = input.getAttribute("data-config");
input.value = state.config[key] ?? "";
input.addEventListener("change", () => {
if (key === "apiKey") {
state.listCache.clear();
}
saveConfig({ ...state.config, [key]: input.value });
applyCheck();
applyListIndicators();
});
});
if (!mountPanel(wrapper)) {
scheduleMountRetry();
return;
}
clearMountRetry();
state.mountRetryCount = 0;
updatePanel(wrapper);
}
function updatePanel(wrapper) {
const summary = wrapper.querySelector(".md-pr-summary");
const statusBlocks = wrapper.querySelectorAll(".md-pr-status");
const details = wrapper.querySelector(".md-pr-details");
const result = state.currentResult;
statusBlocks.forEach((status) => {
status.textContent = "";
status.innerHTML = "";
});
if (!result) {
statusBlocks.forEach((status) => {
status.textContent = "Checking PR author...";
});
summary.textContent = "";
details.textContent = "";
return;
}
// if (result.state === "missing-key") {
// statusBlocks.forEach((status) => {
// status.innerHTML = `<span class="md-pr-warning">API key required</span>`;
// });
// summary.textContent = "";
// details.textContent = "";
// return;
// }
if (result.state === "error") {
statusBlocks.forEach((status) => {
status.innerHTML = `<span class="md-pr-warning">${result.message}</span>`;
});
summary.textContent = "";
details.textContent = "";
return;
}
if (result.state === "not-expert") {
statusBlocks.forEach((status) => {
status.innerHTML = "";
});
summary.textContent = "No contributor profile found yet.";
details.textContent = "";
return;
}
if (result.state === "expert") {
statusBlocks.forEach((status) => {
status.innerHTML = "";
});
const info = result.expert && result.expert.expert ? result.expert.expert : result.expert;
summary.textContent = buildSummary(info, result.username);
details.innerHTML = renderExpertDetails(info, result.username);
}
}
function buildSummary(info, username) {
if (!info) return `This PR was opened by ${username}.`;
const name = info.name || username;
const downloadsRaw = Number(info.total_downloads || 0);
const downloads = downloadsRaw > 0 ? formatCompactNumber(downloadsRaw) : null;
const stars = formatCompactNumber(info.total_stars);
const downloadText = downloads ? `${downloads} total downloads` : "";
const starsText = stars ? `${stars} stars on repos` : "";
const stats = [downloadText, starsText].filter(Boolean).join(", ");
if (!stats) return `This PR was opened by ${name} (${username}).`;
return `This PR was opened by ${name} (${username}). They have received ${stats}.`;
}
function formatCompactNumber(value) {
if (value === null || value === undefined) return null;
const num = Number(value);
if (Number.isNaN(num)) return null;
return new Intl.NumberFormat("en", {
notation: "compact",
maximumFractionDigits: 1
}).format(num);
}
function renderExpertDetails(info, username) {
const profileUrl = `https://explore.market.dev/experts/${encodeURIComponent(username)}`;
if (!info) {
return `Expert profile: <a class="md-pr-link" href="${profileUrl}" target="_blank" rel="noopener noreferrer">Open</a>`;
}
const name = info.name || username;
const avatarUrl = info.avatar_url || info.avatar || null;
const location = info.location || info.display_location || "";
const stats = [
{ label: "Projects", value: formatCompactNumber(info.projects_count) },
{ label: "Downloads", value: formatCompactNumber(info.total_downloads) },
{ label: "Stars", value: formatCompactNumber(info.total_stars) }
].filter((stat) => stat.value !== null);
const projects = Array.isArray(info.projects) ? info.projects : [];
const sortedProjects = [...projects].sort((a, b) => {
const starsA = Number(a.total_stars || a.stars || 0);
const starsB = Number(b.total_stars || b.stars || 0);
if (starsB !== starsA) return starsB - starsA;
const downloadsA = Number(a.total_downloads || a.downloads || 0);
const downloadsB = Number(b.total_downloads || b.downloads || 0);
return downloadsB - downloadsA;
});
const maintainerItems = sortedProjects.slice(0, 10).map((project) => {
const role = project.role || project.project_experts?.[0]?.role;
const name = project.name || project.slug || "";
if (!name) return null;
const stars = formatCompactNumber(project.total_stars || project.stars);
const downloads = formatCompactNumber(project.total_downloads || project.downloads);
const metaParts = [stars ? `${stars} stars` : null, downloads ? `${downloads} downloads` : null]
.filter(Boolean)
.join(" · ");
const label = role ? `${role} of ${name}` : name;
const projectSlug = project.slug || project.name || "";
const projectUrl =
project.github_url ||
project.repo_url ||
project.url ||
(projectSlug ? `https://explore.market.dev/projects/${encodeURIComponent(projectSlug)}` : null);
return { label, meta: metaParts, url: projectUrl };
}).filter(Boolean);
const ecosystems =
(Array.isArray(info.ecosystems) && info.ecosystems) ||
(Array.isArray(info.ecosystem_names) && info.ecosystem_names) ||
[];
const ecosystemNames = ecosystems
.map((eco) => (typeof eco === "string" ? eco : eco.name))
.filter(Boolean)
.slice(0, 8)
.map((name) => ({
name,
url: `https://explore.market.dev/ecosystems/${encodeURIComponent(name)}`
}));
return `
<div class="md-pr-card">
<div class="md-pr-card-header">
<div class="md-pr-avatar">
${avatarUrl ? `<img src="${avatarUrl}" alt="${name}" />` : name.slice(0, 1).toUpperCase()}
</div>
<div>
<div class="md-pr-name"><a class="md-pr-link" href="https://github.com/${encodeURIComponent(username)}" target="_blank" rel="noopener noreferrer">${name}</a></div>
<div class="md-pr-meta">@${username}${location ? ` · ${location}` : ""}</div>
</div>
</div>