-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcontent.js
More file actions
1915 lines (1769 loc) · 81.9 KB
/
Copy pathcontent.js
File metadata and controls
1915 lines (1769 loc) · 81.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 api = typeof browser !== "undefined" && browser.runtime ? browser : chrome;
const ISSUE_PATH = /^\/([^/]+)\/([^/]+)\/issues\/(\d+)\/?$/;
const PULL_PATH = /^\/([^/]+)\/([^/]+)\/pull\/(\d+)\/?$/;
const PROJECT_PATH = /^\/(?:orgs|users)\/[^/]+\/projects\/\d+(?:\/|$)|^\/[^/]+\/[^/]+\/projects\/\d+(?:\/|$)/;
const CACHE_TTL_MS = 5 * 60 * 1000;
const DAY_MS = 24 * 60 * 60 * 1000;
const FETCH_CHUNK = 60;
const cache = new Map(); // "owner/repo#n" -> { at, values, createdAt }
const pending = new Set();
let scheduled = null;
let noticeShown = false;
let settings = { ageEnabled: false, ageUnit: "months", ageWarnDays: 90, pinsEnabled: true, skipShownFields: true, prAssociation: true, prFork: false, prSize: false, prMergeState: false, kanbanEnabled: true, kanbanDrag: true, sidebarToggle: true };
const prCache = new Map(); // "owner/repo!n" -> { at, info }
const prPending = new Set();
let pins = [];
let pinsCollapsed = true;
// ---------------------------------------------------------------------------
// Issue references
// ---------------------------------------------------------------------------
function refFromPath(path) {
const m = ISSUE_PATH.exec(path);
if (!m) return null;
return { owner: m[1], repo: m[2], number: Number(m[3]), key: `${m[1]}/${m[2]}#${m[3]}` };
}
function issueRef(anchor) {
try {
return refFromPath(new URL(anchor.href, location.origin).pathname);
} catch {
return null;
}
}
// Accepts a URL, "owner/repo#123", or "#123" / "123" when a repository can be inferred from the page.
function parseIssueInput(text, fallbackRepo) {
const s = String(text || "").trim();
if (!s) return null;
let m = /^([^/\s]+)\/([^#\s]+)#(\d+)$/.exec(s);
if (m) return { owner: m[1], repo: m[2], number: Number(m[3]), key: `${m[1]}/${m[2]}#${m[3]}` };
m = /^#?(\d+)$/.exec(s);
if (m) {
if (!fallbackRepo) return null;
return { owner: fallbackRepo.owner, repo: fallbackRepo.repo, number: Number(m[1]), key: `${fallbackRepo.owner}/${fallbackRepo.repo}#${m[1]}` };
}
// Only absolute URLs: a relative value would resolve against the current page and pick up its issue number.
if (/^https?:\/\//i.test(s)) {
try {
const url = new URL(s);
if (/(^|\.)github\.com$/.test(url.hostname)) return refFromPath(url.pathname);
} catch { /* not a url */ }
}
return null;
}
// The issue the user is currently looking at: an issue page, or the item opened in a project side panel.
function currentIssue() {
const fromPath = refFromPath(location.pathname);
if (fromPath) return fromPath;
const param = new URLSearchParams(location.search).get("issue");
if (param) {
const parts = param.split("|");
if (parts.length === 3 && /^\d+$/.test(parts[2])) {
return { owner: parts[0], repo: parts[1], number: Number(parts[2]), key: `${parts[0]}/${parts[1]}#${parts[2]}` };
}
}
const dialog = document.querySelector('[role="dialog"][class*="SidePanel"], [role="dialog"] [class*="SidePanel"]');
if (dialog) {
for (const a of dialog.querySelectorAll("a[href]")) {
if (a.closest(".gsf-pins, .gsf-kanban")) continue;
const ref = issueRef(a);
if (ref) return ref;
}
}
return null;
}
// Title of an issue as shown on the current page: issue header, side panel, project row or board card.
function titleFromPage(ref) {
if (refFromPath(location.pathname) && refFromPath(location.pathname).key === ref.key) {
const h1 = document.querySelector('[data-testid="issue-title"], h1 bdi, .js-issue-title');
if (h1 && h1.textContent.trim()) return h1.textContent.trim();
}
const suffix = `/${ref.owner}/${ref.repo}/issues/${ref.number}`;
for (const a of document.querySelectorAll("a[href]")) {
if (a.closest(".gsf-pins, .gsf-badge, .gsf-kanban")) continue;
let path;
try { path = new URL(a.href, location.origin).pathname.replace(/\/$/, ""); } catch { continue; }
if (path !== suffix) continue;
const text = a.textContent.replace(/\s+/g, " ").trim();
if (text && !/^#?\d+$/.test(text) && !/^(?:[^/\s]+\/[^#\s]+)?#\d+$/.test(text)) return text;
}
return "";
}
function currentRepo() {
const m = /^\/([^/]+)\/([^/]+)(?:\/|$)/.exec(location.pathname);
if (!m || m[1] === "orgs" || m[1] === "users") return null;
return { owner: m[1], repo: m[2] };
}
// ---------------------------------------------------------------------------
// Rows: sub-issue lists, project table rows, project board cards
// ---------------------------------------------------------------------------
function collectRows() {
const rows = [];
const seen = new Set();
const containers = document.querySelectorAll('[data-testid="sub-issues-issue-container"], [data-testid*="sub-issues"]');
for (const container of containers) {
// A list the kanban board has replaced is hidden: its rows are not worth a query or a badge.
if (container.closest(".gsf-kanban-hidden")) continue;
for (const li of container.querySelectorAll('li[role="treeitem"]')) {
if (seen.has(li)) continue;
seen.add(li);
const titleLink = [...li.querySelectorAll("a[href]")].find((a) => issueRef(a) && !a.closest(".gsf-badge"));
if (!titleLink) continue;
const ownContent = li.querySelector(":scope > .PRIVATE_TreeView-item-container, :scope > [class*='TreeViewItemContainer']") || li;
if (!ownContent.contains(titleLink)) continue;
rows.push({ kind: "sub", li, titleLink, ref: issueRef(titleLink), content: ownContent });
}
}
// Project table layout: the title cell of each row.
for (const cell of document.querySelectorAll('[role="grid"] [role="rowheader"]')) {
if (seen.has(cell)) continue;
seen.add(cell);
const titleLink = [...cell.querySelectorAll("a[href]")].find((a) => issueRef(a) && !a.closest(".gsf-badge"));
if (!titleLink) continue;
rows.push({ kind: "table", li: cell, titleLink, ref: issueRef(titleLink), content: cell });
}
// Project board layout: one card per item.
for (const h3 of document.querySelectorAll('h3[id^="board-card-title-"]')) {
const titleLink = h3.closest("a[href]");
if (!titleLink) continue;
const ref = issueRef(titleLink);
if (!ref) continue;
// The title link itself has role="button"; the card is the closest one above it.
const card = titleLink.parentElement.closest('[role="button"]') || titleLink.parentElement;
if (seen.has(card)) continue;
seen.add(card);
rows.push({ kind: "board", li: card, titleLink, ref, content: card });
}
return rows;
}
// What GitHub already displays for this row, so a badge would only repeat it:
// board cards list their fields under a "Fields" list whose chips carry a "Field: value" tooltip,
// table views show fields as columns, and a board grouped by a field names that field's value in the column header.
function shownOnPage(row) {
const fields = new Set();
const values = new Set();
if (row.kind === "board") {
for (const chip of row.content.querySelectorAll('ul[aria-label="Fields"] li, [data-testid*="card-field"], [class*="cardLabel"]')) {
const text = (chip.querySelector('[data-component="Tooltip"]') || chip).textContent.trim();
const m = /^([^:]{1,60}):\s/.exec(text);
if (m) fields.add(m[1].trim().toLowerCase());
}
const column = row.content.closest("[data-board-column]");
if (column) values.add(String(column.getAttribute("data-board-column")).trim().toLowerCase());
} else if (row.kind === "table") {
const grid = row.content.closest('[role="grid"]');
for (const th of grid ? grid.querySelectorAll('[role="columnheader"]') : []) {
// The header holds the column name followed by a "<name> column options" menu label; take the first leaf.
const leaf = [...th.querySelectorAll("*")].find((el) => el.children.length === 0 && el.textContent.trim());
const text = (leaf ? leaf.textContent : th.textContent).replace(/\s*column options$/i, "").trim().toLowerCase();
if (text) fields.add(text);
}
}
return { fields, values };
}
function findAnchorSlot(row) {
if (row.kind === "table") {
return { parent: row.titleLink.parentElement, before: null };
}
if (row.kind === "board") {
let wrap = row.titleLink.parentElement.querySelector(":scope > .gsf-badges");
if (!wrap) {
wrap = document.createElement("div");
wrap.className = "gsf-badges";
row.titleLink.parentElement.insertBefore(wrap, row.titleLink.nextSibling);
}
return { parent: wrap, before: null };
}
const typeIndicator = row.content.querySelector('[data-testid*="sub-issue-type-indicator"]');
if (typeIndicator) {
const link = typeIndicator.closest("a") || typeIndicator;
return { parent: link.parentElement, before: link.nextSibling };
}
const titleContainer = row.titleLink.closest('[class*="Title-module__container"]') || row.titleLink.parentElement;
return { parent: titleContainer, before: titleContainer.firstChild };
}
// ---------------------------------------------------------------------------
// Age
// ---------------------------------------------------------------------------
function ageOf(createdAt) {
const created = new Date(createdAt);
if (Number.isNaN(created.getTime())) return null;
const days = Math.max(0, Math.floor((Date.now() - created.getTime()) / DAY_MS));
let text;
if (settings.ageUnit === "days") {
text = days === 0 ? "today" : `${days}d`;
} else if (settings.ageUnit === "weeks") {
const weeks = Math.floor(days / 7);
text = weeks < 1 ? "this week" : `${weeks}w`;
} else {
const months = Math.floor(days / 30.4375);
text = months < 1 ? "this month" : `${months} mo`;
}
const months = Math.floor(days / 30.4375);
const warn = settings.ageWarnDays > 0 && days >= settings.ageWarnDays;
const title = `Age: ${months} month${months === 1 ? "" : "s"} (${days} day${days === 1 ? "" : "s"}), created ${created.toISOString().slice(0, 10)}`
+ (warn ? `. Open for more than ${settings.ageWarnDays} days.` : "");
return { text, title, days, color: warn ? "YELLOW" : "GRAY" };
}
// ---------------------------------------------------------------------------
// Badges
// ---------------------------------------------------------------------------
function render(row, hit) {
const shown = settings.skipShownFields ? shownOnPage(row) : { fields: new Set(), values: new Set() };
const values = ((hit && hit.values) || []).filter((v) => !shown.fields.has(String(v.field).toLowerCase()) && !shown.values.has(String(v.value).trim().toLowerCase()));
const scope = row.content.contains(row.titleLink) ? row.content : row.titleLink.parentElement;
scope.querySelectorAll(`.gsf-badge[data-gsf-for="${row.ref.key}"]`).forEach((el) => el.remove());
row.titleLink.parentElement.querySelectorAll(`.gsf-badge[data-gsf-for="${row.ref.key}"]`).forEach((el) => el.remove());
const age = settings.ageEnabled && hit && hit.createdAt ? ageOf(hit.createdAt) : null;
if (!values.length && !age) {
row.li.dataset.gsfState = "empty";
return;
}
const slot = findAnchorSlot(row);
if (!slot || !slot.parent) return;
const frag = document.createDocumentFragment();
for (const v of values) {
const badge = document.createElement("a");
badge.className = "gsf-badge";
badge.dataset.gsfColor = v.color || "GRAY";
badge.dataset.gsfFor = row.ref.key;
badge.textContent = v.value;
badge.title = `${v.field}: ${v.value}`;
const q = `field.${v.field}:"${v.value}"`;
badge.href = `/${row.ref.owner}/${row.ref.repo}/issues?q=${encodeURIComponent(q)}`;
badge.addEventListener("click", (e) => e.stopPropagation());
frag.appendChild(badge);
}
if (age) {
const badge = document.createElement("span");
badge.className = "gsf-badge gsf-age";
badge.dataset.gsfColor = age.color;
badge.dataset.gsfFor = row.ref.key;
badge.textContent = age.text;
badge.title = age.title;
frag.appendChild(badge);
}
slot.parent.insertBefore(frag, slot.before);
row.li.dataset.gsfState = "done";
}
function hasBadges(row) {
const sel = `.gsf-badge[data-gsf-for="${row.ref.key}"]`;
return Boolean(row.content.querySelector(sel) || row.titleLink.parentElement.querySelector(sel));
}
function showNotice(message, withOptionsButton) {
if (noticeShown) return;
const container = document.querySelector('[data-testid="sub-issues-issue-container"]');
if (!container) {
// No sub-issues list on this page (project view): report through the pins panel and flag its button.
if (panel) setPanelStatus(message, false, withOptionsButton);
flagHeaderButton(message);
return;
}
noticeShown = true;
const box = document.createElement("div");
box.className = "gsf-notice";
const text = document.createElement("span");
text.textContent = message;
box.appendChild(text);
if (withOptionsButton) {
const btn = document.createElement("button");
btn.type = "button";
btn.textContent = "Open extension options";
btn.addEventListener("click", () => api.runtime.sendMessage({ type: "openOptions" }));
box.appendChild(btn);
}
const close = document.createElement("button");
close.type = "button";
close.textContent = "Dismiss";
close.addEventListener("click", () => box.remove());
box.appendChild(close);
container.prepend(box);
}
async function scan() {
scheduled = null;
syncPanel();
syncKanban();
syncSidebar();
scanPulls().catch((err) => console.warn("[github-issue-toolkit]", err));
const rows = collectRows();
if (!rows.length) return;
const now = Date.now();
const toFetch = new Map();
for (const row of rows) {
const hit = cache.get(row.ref.key);
if (hit && now - hit.at < CACHE_TTL_MS) {
if (!hasBadges(row) && row.li.dataset.gsfState !== "empty") render(row, hit);
continue;
}
if (!pending.has(row.ref.key)) toFetch.set(row.ref.key, row.ref);
}
if (!toFetch.size) return;
for (const key of toFetch.keys()) pending.add(key);
const issues = [...toFetch.values()].map(({ owner, repo, number }) => ({ owner, repo, number }));
// Project tables can hold hundreds of rows: keep each GraphQL request small enough for GitHub's limits.
const chunks = [];
for (let i = 0; i < issues.length; i += FETCH_CHUNK) chunks.push(issues.slice(i, i + FETCH_CHUNK));
let response;
try {
const parts = await Promise.all(chunks.map((chunk) => api.runtime.sendMessage({ type: "fetchFieldValues", issues: chunk })));
const failed = parts.find((part) => !part || part.error);
response = failed || parts.reduce((acc, part) => {
Object.assign(acc.values, part.values || {});
Object.assign(acc.created, part.created || {});
return acc;
}, { values: {}, created: {} });
} catch (err) {
response = { error: err && err.message ? err.message : String(err) };
} finally {
for (const key of toFetch.keys()) pending.delete(key);
}
if (!response || response.error) {
if (response && response.error === "NO_TOKEN") {
showNotice("GitHub Issue Toolkit: add a GitHub token in the extension settings to show field values here.", true);
} else if (response && response.error === "NO_FIELDS") {
showNotice("GitHub Issue Toolkit: choose which fields to show, or enable the age badge, in the extension settings.", true);
} else {
showNotice(`GitHub Issue Toolkit: ${response ? response.error : "unknown error"}`, true);
}
return;
}
const at = Date.now();
for (const key of toFetch.keys()) {
cache.set(key, {
at,
values: (response.values && response.values[key]) || [],
createdAt: (response.created && response.created[key]) || null
});
}
for (const row of collectRows()) {
const hit = cache.get(row.ref.key);
if (hit && toFetch.has(row.ref.key)) render(row, hit);
}
}
// ---------------------------------------------------------------------------
// Pull request lists: author association, fork, size and merge state badges
// ---------------------------------------------------------------------------
function prEnabled() {
return settings.prAssociation || settings.prFork || settings.prSize || settings.prMergeState;
}
function pullRef(anchor) {
let path;
try { path = new URL(anchor.href, location.origin).pathname; } catch { return null; }
const m = PULL_PATH.exec(path);
if (!m) return null;
return { owner: m[1], repo: m[2], number: Number(m[3]), key: `${m[1]}/${m[2]}!${m[3]}` };
}
// Pull request rows: the pull request list (repository /pulls and the global /pulls pages),
// and Projects views whose items are pull requests (table title cells and board cards).
function collectPullRows() {
const rows = [];
const seen = new Set();
for (const link of document.querySelectorAll('li a[data-testid="listitem-title-link"], li a[data-testid="issue-pr-title-link"]')) {
const ref = pullRef(link);
const li = ref && link.closest("li");
if (!li || seen.has(li)) continue;
seen.add(li);
rows.push({ kind: "list", li, titleLink: link, ref });
}
for (const cell of document.querySelectorAll('[role="grid"] [role="rowheader"]')) {
if (seen.has(cell)) continue;
const link = [...cell.querySelectorAll("a[href]")].find((a) => pullRef(a) && !a.closest(".gsf-badge"));
if (!link) continue;
seen.add(cell);
rows.push({ kind: "table", li: cell, titleLink: link, ref: pullRef(link) });
}
for (const h3 of document.querySelectorAll('h3[id^="board-card-title-"]')) {
const link = h3.closest("a[href]");
const ref = link && pullRef(link);
if (!ref) continue;
const card = link.parentElement.closest('[role="button"]') || link.parentElement;
if (seen.has(card)) continue;
seen.add(card);
rows.push({ kind: "board", li: card, titleLink: link, ref });
}
return rows;
}
const ASSOCIATION = {
FIRST_TIMER: ["First PR on GitHub", "GREEN", "This is the author's first pull request on GitHub"],
FIRST_TIME_CONTRIBUTOR: ["First-time contributor", "GREEN", "First pull request from this author to this repository"],
NONE: ["External", "PURPLE", "The author has no previous contributions to this repository"],
CONTRIBUTOR: ["Contributor", "GRAY", "The author has contributed to this repository before"],
COLLABORATOR: ["Collaborator", "BLUE", "The author has write access to this repository"],
MEMBER: ["Member", "BLUE", "The author is a member of the organization"],
OWNER: ["Owner", "BLUE", "The author owns the repository"]
};
const MERGE_STATE = {
CLEAN: ["Mergeable", "GREEN", "All requirements are met"],
BEHIND: ["Behind base", "YELLOW", "The branch is behind its base branch"],
BLOCKED: ["Blocked", "RED", "Branch rules are not satisfied yet"],
DIRTY: ["Conflicts", "RED", "The branch has merge conflicts"],
UNSTABLE: ["Checks failing", "YELLOW", "Required checks are failing or pending"]
};
function pullBadges(info) {
const out = [];
if (settings.prAssociation) {
if (info.bot) out.push(["Bot", "GRAY", "Opened by an app"]);
else if (ASSOCIATION[info.association]) out.push(ASSOCIATION[info.association]);
}
if (settings.prFork && info.fork) out.push(["From fork", "GRAY", "Opened from a fork of the repository"]);
if (settings.prSize && Number.isFinite(info.additions)) {
out.push([{ additions: info.additions, deletions: info.deletions }, "GRAY", `${info.files} changed file${info.files === 1 ? "" : "s"}`]);
}
if (settings.prMergeState && !info.draft && MERGE_STATE[info.mergeState]) out.push(MERGE_STATE[info.mergeState]);
return out;
}
function renderPull(row, info) {
row.li.querySelectorAll(`.gsf-badge[data-gsf-for="${row.ref.key}"]`).forEach((el) => el.remove());
const badges = pullBadges(info);
row.li.dataset.gsfPr = "done";
if (!badges.length) return;
let parent;
if (row.kind === "board") {
parent = row.titleLink.parentElement.querySelector(":scope > .gsf-badges");
if (!parent) {
parent = document.createElement("div");
parent.className = "gsf-badges";
row.titleLink.parentElement.insertBefore(parent, row.titleLink.nextSibling);
}
} else if (row.kind === "table") {
parent = row.titleLink.parentElement;
} else {
const container = row.titleLink.closest('[class*="Title-module__container"]');
parent = (container && container.querySelector('[class*="trailingBadgesContainer"]')) || container || row.titleLink.parentElement;
}
const frag = document.createDocumentFragment();
for (const [text, color, title] of badges) {
const badge = document.createElement("span");
badge.className = "gsf-badge gsf-pr";
badge.dataset.gsfColor = color;
badge.dataset.gsfFor = row.ref.key;
badge.title = title;
if (typeof text === "object") {
// diffstat: green additions, red deletions, like GitHub's own file counters
const add = document.createElement("span");
add.className = "gsf-add";
add.textContent = `+${text.additions}`;
const del = document.createElement("span");
del.className = "gsf-del";
del.textContent = `-${text.deletions}`;
badge.classList.add("gsf-size");
badge.append(add, " ", del);
} else {
badge.textContent = text;
}
frag.appendChild(badge);
}
parent.appendChild(frag);
}
async function scanPulls() {
if (!prEnabled()) return;
const rows = collectPullRows();
if (!rows.length) return;
const now = Date.now();
const toFetch = new Map();
for (const row of rows) {
const hit = prCache.get(row.ref.key);
if (hit && now - hit.at < CACHE_TTL_MS) {
if (!row.li.querySelector(`.gsf-badge[data-gsf-for="${row.ref.key}"]`) && row.li.dataset.gsfPr !== "done") renderPull(row, hit.info);
continue;
}
if (!prPending.has(row.ref.key)) toFetch.set(row.ref.key, row.ref);
}
if (!toFetch.size) return;
for (const key of toFetch.keys()) prPending.add(key);
const pulls = [...toFetch.values()].map(({ owner, repo, number }) => ({ owner, repo, number }));
const chunks = [];
for (let i = 0; i < pulls.length; i += FETCH_CHUNK) chunks.push(pulls.slice(i, i + FETCH_CHUNK));
let response;
try {
const parts = await Promise.all(chunks.map((chunk) => api.runtime.sendMessage({ type: "fetchPullRequests", pulls: chunk })));
const failed = parts.find((part) => !part || part.error);
response = failed || parts.reduce((acc, part) => Object.assign(acc, part.pulls || {}), {});
if (!failed) response = { pulls: response };
} catch (err) {
response = { error: err && err.message ? err.message : String(err) };
} finally {
for (const key of toFetch.keys()) prPending.delete(key);
}
if (!response || response.error) {
if (response && response.error === "NO_TOKEN") flagHeaderButton("GitHub Issue Toolkit: add a GitHub token in the extension settings to show pull request badges.");
else flagHeaderButton(`GitHub Issue Toolkit: ${response ? response.error : "unknown error"}`);
return;
}
const at = Date.now();
for (const key of toFetch.keys()) prCache.set(key, { at, info: response.pulls[key] || null });
for (const row of collectPullRows()) {
const hit = prCache.get(row.ref.key);
if (hit && hit.info && toFetch.has(row.ref.key)) renderPull(row, hit.info);
}
}
function clearBadges() {
cache.clear();
prCache.clear();
epicCache.clear();
boardSignature = null;
document.querySelectorAll("[data-gsf-pr]").forEach((el) => delete el.dataset.gsfPr);
noticeShown = false;
if (headerButton) {
headerButton.classList.remove("gsf-has-error");
headerButton.title = "Pinned issues";
}
document.querySelectorAll(".gsf-badge, .gsf-badges, .gsf-notice").forEach((el) => el.remove());
document.querySelectorAll("[data-gsf-state]").forEach((el) => delete el.dataset.gsfState);
}
// ---------------------------------------------------------------------------
// Epic kanban: the sub-issues of an issue shown as a board
// ---------------------------------------------------------------------------
const SUB_ISSUES_LIST = '[data-testid*="sub-issues-issue-container"]';
const STATE_ICONS = {
open: ["M8 9.5a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3Z", "M8 0a8 8 0 1 1 0 16A8 8 0 0 1 8 0ZM1.5 8a6.5 6.5 0 1 0 13 0 6.5 6.5 0 0 0-13 0Z"],
closed: ["M11.28 6.78a.75.75 0 0 0-1.06-1.06L7.25 8.69 5.78 7.22a.75.75 0 0 0-1.06 1.06l2 2a.75.75 0 0 0 1.06 0l3.5-3.5Z", "M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0Zm-1.5 0a6.5 6.5 0 1 0-13 0 6.5 6.5 0 0 0 13 0Z"]
};
const GROUP_BUILTINS = [
{ id: "state", label: "State" },
{ id: "type", label: "Type" },
{ id: "assignee", label: "Assignee" }
];
const SORT_BUILTINS = [
{ id: "number", label: "Issue number" },
{ id: "created", label: "Creation date" },
{ id: "title", label: "Title" },
{ id: "state", label: "State" },
{ id: "type", label: "Type" },
{ id: "assignee", label: "Assignee" }
];
// A short option list keeps its empty columns, because a stage nothing sits in is worth seeing;
// a long one would push the board off screen, so only the columns that hold something are drawn.
const EMPTY_COLUMN_LIMIT = 10;
// `filterValue` is a column key, so "" is a real value (the items with nothing) and "*" means every value.
// `hideClosed` takes the finished sub-issues off the board whatever the columns are made of.
let kanban = { on: false, groupBy: "", sortBy: "number", sortDir: "asc", filterBy: "", filterValue: "*", hideClosed: false };
const epicCache = new Map(); // "owner/repo#n" -> { at, items, total, fields, fieldDefs }
const epicPending = new Set();
let barParts = null;
let boardRoot = null;
let boardEpicKey = null;
let boardSignature = null;
let noteTimer = null;
let dragKey = null;
const moving = new Set();
// The sub-issues list of the issue page we are on, if GitHub has rendered one.
function epicList() {
if (!refFromPath(location.pathname)) return null;
return document.querySelector(SUB_ISSUES_LIST);
}
function saveKanbanView() {
api.storage.local.set({ kanban: { ...kanban } });
}
// Keeping only one dimension's value is enough to answer "show me just S1": the columns still say the rest.
function matchesFilter(item) {
if (kanban.hideClosed && item.state === "CLOSED") return false;
if (!kanban.filterBy || kanban.filterValue === "*") return true;
const bucket = bucketOf(item, kanban.filterBy);
return (bucket ? bucket.key : "") === kanban.filterValue;
}
// The values that dimension actually holds, in column order, each with how many issues carry it.
function filterValueChoices(data) {
if (!kanban.filterBy) return [];
const columns = columnsOf(data.items, kanban.filterBy, data.fieldDefs).filter((column) => column.items.length);
return [{ id: "*", label: "Any value" }, ...columns.map((column) => ({ id: column.key, label: `${column.label} (${column.items.length})` }))];
}
function valueOf(item, field) {
const name = String(field).toLowerCase();
return item.values.find((v) => v.field.toLowerCase() === name) || null;
}
// The fields the loaded sub-issues carry, with the id and option list of the single-select ones, taken
// once from the fetched payload: a board grouped by a field keeps its columns and stays droppable even
// after the last card holding a value for it is dragged into the "No field" column.
function fieldDefsOf(items) {
const defs = new Map();
for (const item of items) {
for (const v of item.values) {
const key = v.field.toLowerCase();
const def = defs.get(key) || { name: v.field, fieldId: null, options: [] };
if (!def.fieldId && v.fieldId) def.fieldId = v.fieldId;
if (!def.options.length && v.options && v.options.length) def.options = v.options;
defs.set(key, def);
}
}
return defs;
}
// Everything the loaded sub-issues can be grouped or ordered by: the fields they carry, in the order the
// settings list them so the field you care about comes first, then the ones GitHub gives every issue.
function fieldChoices(data) {
const configured = (data.fields || []).map((f) => f.toLowerCase());
const found = new Map();
for (const [key, def] of data.fieldDefs || []) found.set(key, def.name);
for (const item of data.items) {
for (const v of item.values) if (!found.has(v.field.toLowerCase())) found.set(v.field.toLowerCase(), v.field);
}
const names = [...found.entries()]
.sort((a, b) => {
const ia = configured.indexOf(a[0]);
const ib = configured.indexOf(b[0]);
if (ia !== ib) return (ia < 0 ? configured.length : ia) - (ib < 0 ? configured.length : ib);
return a[1].localeCompare(b[1]);
})
.map(([, name]) => name);
return names.map((name) => ({ id: `field:${name}`, label: name }));
}
function groupChoices(data) {
return [...fieldChoices(data), ...GROUP_BUILTINS];
}
function sortChoices(data) {
return [...SORT_BUILTINS, ...fieldChoices(data)];
}
// The column an item belongs to, or null when it has no value for the grouping.
function bucketOf(item, groupBy) {
if (groupBy === "state") {
const closed = item.state === "CLOSED";
return { key: closed ? "closed" : "open", label: closed ? "Closed" : "Open", color: closed ? "PURPLE" : "GREEN" };
}
if (groupBy === "type") {
return item.type ? { key: `type:${item.type}`, label: item.type, color: item.typeColor || "GRAY" } : null;
}
if (groupBy === "assignee") {
const who = item.assignees[0];
return who ? { key: `user:${who.login}`, label: who.login, color: "GRAY" } : null;
}
const value = valueOf(item, groupBy.slice(6));
return value ? { key: `value:${value.value}`, label: value.value, color: value.color || "GRAY" } : null;
}
function emptyLabel(groupBy) {
if (groupBy === "assignee") return "Unassigned";
if (groupBy === "type") return "No type";
return `No ${groupBy.startsWith("field:") ? groupBy.slice(6) : groupBy}`;
}
// Columns in the order the organization defined the field's options, so a board grouped by a stage reads
// left to right the way the stage does. Without an option list there is nothing to follow but the labels.
function columnsOf(items, groupBy, fieldDefs) {
const columns = new Map();
const none = { key: "", label: emptyLabel(groupBy), color: "GRAY", items: [] };
const order = [];
let trimEmpty = false;
const seed = (column) => {
order.push(column.key);
columns.set(column.key, column);
};
if (groupBy === "state") {
seed({ key: "open", label: "Open", color: "GREEN", state: "OPEN", items: [] });
seed({ key: "closed", label: "Closed", color: "PURPLE", state: "CLOSED", items: [] });
} else if (groupBy.startsWith("field:")) {
const name = groupBy.slice(6);
const def = fieldDefs ? fieldDefs.get(name.toLowerCase()) : null;
const defined = def && def.options.length ? def : items.map((item) => valueOf(item, name)).find((v) => v && v.options && v.options.length);
const options = defined ? defined.options : [];
none.fieldId = defined ? defined.fieldId : null;
none.options = options;
// Every option gets a column carrying the ids a drop needs, whatever the length of the list; whether
// the empty ones are drawn is decided below.
for (const option of options) {
seed({ key: `value:${option.name}`, label: option.name, color: option.color || "GRAY", fieldId: none.fieldId, optionId: option.id, options, items: [] });
}
trimEmpty = options.length > EMPTY_COLUMN_LIMIT;
}
for (const item of items) {
const bucket = bucketOf(item, groupBy);
if (!bucket) {
none.items.push(item);
continue;
}
if (!columns.has(bucket.key)) columns.set(bucket.key, { ...bucket, items: [] });
columns.get(bucket.key).items.push(item);
}
let list = [...columns.values()];
if (trimEmpty) list = list.filter((column) => column.items.length);
if (order.length) {
const rank = (column) => (order.indexOf(column.key) < 0 ? order.length : order.indexOf(column.key));
list.sort((a, b) => rank(a) - rank(b));
} else {
list.sort((a, b) => a.label.localeCompare(b.label, undefined, { numeric: true }));
}
if (none.items.length) list.push(none);
return list;
}
// What to order by within a column. `missing` keeps the items without a value at the bottom in both
// directions, and the comparison stays inside one type because every item is measured on the same key.
function sortKeyOf(item, sortBy) {
if (sortBy === "number") return { value: item.number };
if (sortBy === "created") return { value: new Date(item.createdAt).getTime() || 0 };
if (sortBy === "title") return { value: item.title.toLowerCase() };
if (sortBy === "state") return { value: item.state === "CLOSED" ? 1 : 0 };
if (sortBy === "type") return item.type ? { value: item.type.toLowerCase() } : { value: "", missing: true };
if (sortBy === "assignee") return item.assignees[0] ? { value: item.assignees[0].login.toLowerCase() } : { value: "", missing: true };
const value = valueOf(item, sortBy.slice(6));
if (!value) return { value: "", missing: true };
if (value.options && value.options.length) {
const index = value.options.findIndex((o) => o.name === value.value);
return { value: index < 0 ? value.options.length : index };
}
if (value.kind === "number") return { value: Number(value.value) || 0 };
if (value.kind === "date") return { value: new Date(value.value).getTime() || 0 };
return { value: value.value.toLowerCase() };
}
function sortItems(items, sortBy, sortDir) {
return items.sort((a, b) => {
const ka = sortKeyOf(a, sortBy);
const kb = sortKeyOf(b, sortBy);
if (Boolean(ka.missing) !== Boolean(kb.missing)) return ka.missing ? 1 : -1;
let order = ka.value < kb.value ? -1 : ka.value > kb.value ? 1 : a.number - b.number;
return sortDir === "desc" ? -order : order;
});
}
// A column can take a dropped card when the move is one GitHub can be asked to make: the state of an
// issue, or a single-select field whose options carry their ids. Everything else is read-only.
function canDrop(column, groupBy) {
if (!settings.kanbanDrag) return false;
if (groupBy === "state") return Boolean(column.state);
return Boolean(column.fieldId) && Boolean(column.optionId || column.key === "");
}
function moveOf(item, groupBy, column) {
if (groupBy === "state") return { kind: "state", issueId: item.id, state: column.state, stateReason: item.closedReason || null };
return { kind: "field", issueId: item.id, fieldId: column.fieldId, optionId: column.optionId || null };
}
// The same move applied to the copy the board holds, so the card lands in its new column right away.
function applyMove(item, groupBy, column) {
if (groupBy === "state") {
// Reopening remembers how the issue had been closed, so closing it again keeps a "not planned".
if (item.state === "CLOSED" && item.stateReason) item.closedReason = item.stateReason;
item.state = column.state;
item.stateReason = column.state === "CLOSED" ? item.closedReason || "COMPLETED" : null;
return;
}
const name = groupBy.slice(6);
const current = valueOf(item, name);
if (!column.optionId) {
item.values = item.values.filter((v) => v !== current);
return;
}
if (current) {
current.value = column.label;
current.color = column.color;
return;
}
item.values.push({ field: name, value: column.label, color: column.color, kind: "singleselect", options: column.options || null, fieldId: column.fieldId });
}
async function moveCard(key, column, groupBy) {
const epic = refFromPath(location.pathname);
const data = epic && epicCache.get(epic.key);
const item = data && data.items.find((candidate) => candidate.key === key);
if (!item || moving.has(key)) return;
const from = bucketOf(item, groupBy);
if ((from ? from.key : "") === column.key) return;
const before = { state: item.state, stateReason: item.stateReason, closedReason: item.closedReason || null, values: item.values.map((v) => ({ ...v })) };
applyMove(item, groupBy, column);
moving.add(key);
setBoardNote(`Moving #${item.number} to ${column.label}...`, false);
redrawBoard();
let response;
try {
response = await api.runtime.sendMessage({ type: "moveIssue", move: moveOf(item, groupBy, column) });
} catch (err) {
response = { error: err && err.message ? err.message : String(err) };
}
moving.delete(key);
if (!response || response.error) {
Object.assign(item, before);
setBoardNote(response && response.error === "NO_TOKEN"
? "Add a GitHub token in the extension settings to move cards."
: `Could not move #${item.number}: ${response ? response.error : "unknown error"}`, true);
redrawBoard();
return;
}
setBoardNote(`#${item.number} moved to ${column.label}.`, false);
}
function stateIcon(item) {
const closed = item.state === "CLOSED";
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute("viewBox", "0 0 16 16");
svg.setAttribute("aria-hidden", "true");
svg.setAttribute("class", "gsf-kanban-state");
svg.dataset.state = closed ? (item.stateReason === "NOT_PLANNED" ? "skipped" : "closed") : "open";
for (const d of STATE_ICONS[closed ? "closed" : "open"]) {
const path = document.createElementNS("http://www.w3.org/2000/svg", "path");
path.setAttribute("d", d);
svg.appendChild(path);
}
return svg;
}
function kanbanBadge(text, color, title, extraClass) {
const badge = document.createElement("span");
badge.className = `gsf-badge${extraClass ? ` ${extraClass}` : ""}`;
badge.dataset.gsfColor = color || "GRAY";
badge.textContent = text;
if (title) badge.title = title;
return badge;
}
function kanbanCard(item, data, groupBy, movable) {
const card = document.createElement("a");
card.className = "gsf-kanban-card";
card.href = item.url || `/${item.owner}/${item.repo}/issues/${item.number}`;
card.dataset.closed = String(item.state === "CLOSED");
if (movable && item.id) {
// An anchor drags its own link by default, so the card says what it carries instead.
card.draggable = true;
card.addEventListener("dragstart", (e) => {
dragKey = item.key;
card.classList.add("gsf-dragging");
e.dataTransfer.effectAllowed = "move";
e.dataTransfer.setData("text/plain", item.key);
e.stopPropagation();
});
card.addEventListener("dragend", () => {
dragKey = null;
card.classList.remove("gsf-dragging");
if (boardRoot) boardRoot.querySelectorAll(".gsf-over").forEach((el) => el.classList.remove("gsf-over"));
});
}
const head = document.createElement("span");
head.className = "gsf-kanban-card-head";
head.appendChild(stateIcon(item));
const ref = document.createElement("span");
ref.className = "gsf-kanban-ref";
const repo = currentRepo();
const sameRepo = repo && repo.owner === item.owner && repo.repo === item.repo;
ref.textContent = sameRepo ? `#${item.number}` : `${item.key}`;
head.appendChild(ref);
if (item.assignees.length) {
const who = document.createElement("span");
who.className = "gsf-kanban-assignees";
for (const assignee of item.assignees) {
if (!assignee.avatarUrl) continue;
const avatar = document.createElement("img");
avatar.className = "gsf-kanban-avatar";
avatar.src = assignee.avatarUrl;
avatar.alt = "";
avatar.title = assignee.login;
avatar.loading = "lazy";
who.appendChild(avatar);
}
if (who.childElementCount) head.appendChild(who);
}
card.appendChild(head);
const title = document.createElement("span");
title.className = "gsf-kanban-title";
title.textContent = item.title;
card.appendChild(title);
// The column already says what the grouping field holds, so the badges repeat the other fields only.
const grouped = groupBy.startsWith("field:") ? groupBy.slice(6).toLowerCase() : "";
const badges = document.createElement("span");
badges.className = "gsf-kanban-badges";
for (const name of data.fields || []) {
if (settings.skipShownFields && name.toLowerCase() === grouped) continue;
const value = valueOf(item, name);
if (value) badges.appendChild(kanbanBadge(value.value, value.color, `${value.field}: ${value.value}`));
}
if (item.type && groupBy !== "type") badges.appendChild(kanbanBadge(item.type, item.typeColor || "GRAY", `Type: ${item.type}`));
const age = settings.ageEnabled ? ageOf(item.createdAt) : null;
if (age) badges.appendChild(kanbanBadge(age.text, age.color, age.title, "gsf-age"));
if (badges.childElementCount) card.appendChild(badges);
return card;
}
function kanbanColumn(column, data, groupBy, movable) {
const col = document.createElement("section");
col.className = "gsf-kanban-col";
if (canDrop(column, groupBy)) {
col.addEventListener("dragover", (e) => {
if (!dragKey) return;
e.preventDefault();
e.dataTransfer.dropEffect = "move";
col.classList.add("gsf-over");
});
col.addEventListener("dragleave", (e) => {
if (!col.contains(e.relatedTarget)) col.classList.remove("gsf-over");
});
col.addEventListener("drop", (e) => {
e.preventDefault();
e.stopPropagation();
col.classList.remove("gsf-over");
const key = dragKey || e.dataTransfer.getData("text/plain");
dragKey = null;
if (key) moveCard(key, column, groupBy).catch((err) => console.warn("[github-issue-toolkit]", err));
});
}
const head = document.createElement("header");
head.className = "gsf-kanban-col-head";
const dot = document.createElement("span");
dot.className = "gsf-kanban-dot";
dot.dataset.gsfColor = column.color || "GRAY";
const name = document.createElement("span");
name.className = "gsf-kanban-col-name";
name.textContent = column.label;
name.title = column.label;
const count = document.createElement("span");
count.className = "gsf-kanban-count";
count.textContent = String(column.items.length);
head.append(dot, name, count);
col.appendChild(head);
const cards = document.createElement("div");
cards.className = "gsf-kanban-cards";
for (const item of column.items) cards.appendChild(kanbanCard(item, data, groupBy, movable));
col.appendChild(cards);
return col;
}
function setBarStatus(message) {
if (!barParts) return;
barParts.status.textContent = message || "";
}
// What a move is doing, or why it did not happen. An error stays until the next one; progress fades.
function setBoardNote(message, isError) {
if (!barParts) return;
const { note } = barParts;
note.textContent = message || "";
note.dataset.error = String(Boolean(isError));
clearTimeout(noteTimer);
if (message && !isError) noteTimer = setTimeout(() => { note.textContent = ""; }, 5000);
}
function redrawBoard() {
boardSignature = null;
syncKanban();
}
function fillSelect(select, choices, selected) {
select.textContent = "";
for (const choice of choices) {
const option = document.createElement("option");
option.value = choice.id;
option.textContent = choice.label;
select.appendChild(option);