-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathghp.js
More file actions
1243 lines (1217 loc) · 50.5 KB
/
ghp.js
File metadata and controls
1243 lines (1217 loc) · 50.5 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
// ==UserScript==
// @name GitHub Plus
// @name:zh-CN GitHub 增强
// @namespace http://tampermonkey.net/
// @version 0.4.7
// @description Enhance GitHub with additional features.
// @description:zh-CN 为 GitHub 增加额外的功能。
// @author PRO-2684
// @match https://github.com/*
// @match https://*.github.com/*
// @run-at document-start
// @icon http://github.com/favicon.ico
// @license gpl-3.0
// @grant GM_setValue
// @grant GM_getValue
// @grant GM_deleteValue
// @grant GM_registerMenuCommand
// @grant GM_unregisterMenuCommand
// @grant GM_addValueChangeListener
// @grant GM_addElement
// @grant GM_getResourceText
// @grant unsafeWindow
// @require https://github.com/PRO-2684/GM_config/releases/download/v1.2.2/config.min.js#md5=c45f9b0d19ba69bb2d44918746c4d7ae
// @resource catppuccin-associations https://raw.githubusercontent.com/PRO-2684/gadgets/refs/heads/main/github_plus/associations.json
// @resource catppuccin-icons https://raw.githubusercontent.com/PRO-2684/gadgets/refs/heads/main/github_plus/icons.json
// @resource catppuccin-palette https://raw.githubusercontent.com/PRO-2684/gadgets/refs/heads/main/github_plus/palette.json
// ==/UserScript==
(function () {
"use strict";
const { name, version } = GM_info.script;
const idPrefix = "ghp-"; // Prefix for the IDs of the elements
/**
* The top domain of the current page.
* @type {string}
*/
const topDomain = location.hostname.split(".").slice(-2).join(".");
/**
* The official domain of GitHub.
* @type {string}
*/
const officialDomain = "github.com";
/**
* The color used for logging. Matches the color of the GitHub.
* @type {string}
*/
const themeColor = "#f78166";
/**
* Regular expression to match the expanded assets URL. (https://<host>/<username>/<repo>/releases/expanded_assets/<version>)
*/
const expandedAssetsRegex = new RegExp(
`https://${topDomain.replaceAll(".", "\\.")}/([^/]+)/([^/]+)/releases/expanded_assets/([^/]+)`,
);
/**
* Data about the release. Maps `owner`, `repo` and `version` to the details of a release. Details are `Promise` objects if exist.
*/
let releaseData = {};
/**
* Rate limit data for the GitHub API.
* @type {Object}
* @property {number} limit The maximum number of requests that the consumer is permitted to make per hour.
* @property {number} remaining The number of requests remaining in the current rate limit window.
* @property {number} reset The time at which the current rate limit window resets in UTC epoch seconds.
*/
let rateLimit = {
limit: -1,
remaining: -1,
reset: -1,
};
// Configuration
const configDesc = {
$default: {
autoClose: false,
},
code: {
name: "🔢 Code Features",
type: "folder",
items: {
tabSize: {
name: "➡️ Tab Size",
title: "Set Tab indentation size",
type: "int",
min: 0,
value: 4,
},
cursorBlink: {
name: "😉 Cursor Blink",
title: "Enable cursor blinking",
type: "bool",
value: false,
},
cursorAnimation: {
name: "🌊 Cursor Animation",
title: "Make cursor move smoothly",
type: "bool",
value: false,
},
fullWidth: {
name: "🔲 Full Width",
title: "Make the code block full width (copilot button may cover the end of the line)",
type: "bool",
value: false,
},
},
},
appearance: {
name: "🎨 Appearance",
type: "folder",
items: {
dashboard: {
name: "📰 Dashboard",
title: "Configures the dashboard",
type: "enum",
options: [
"Default",
"Hide Copilot",
"Hide Feed",
"Mobile-Like",
],
},
leftSidebar: {
name: "↖️ Left Sidebar",
title: "Configures the left sidebar",
type: "enum",
options: ["Default", "Hidden"],
},
rightSidebar: {
name: "↗️ Right Sidebar",
title: "Configures the right sidebar",
type: "enum",
options: [
"Default",
"Hide 'Latest changes'",
"Hide 'Explore repositories'",
"Hide Completely",
],
},
stickyAvatar: {
name: "📌 Sticky Avatar",
title: "Make the avatar sticky",
type: "bool",
value: false,
},
hideHeaderUnderline: {
name: "🫥 Hide Header Underline",
title: "Hide the underline of the header (the border below the header)",
type: "bool",
value: false,
},
catppuccinIcons: {
name: "🐱 Catppuccin Icons",
title: "Use catppuccin icons for folders and files (HIGHLY EXPERIMENTAL), need refresh to apply changes",
type: "enum",
options: [
"🚫 Default",
"🌻 Latte",
"🪴 Frappé",
"🌺 Macchiato",
"🌿 Mocha",
],
},
},
},
release: {
name: "📦 Release Features",
type: "folder",
items: {
uploader: {
name: "⬆️ Release Uploader",
title: "Show uploader of release assets",
type: "bool",
value: true,
},
downloads: {
name: "📥 Release Downloads",
title: "Show download counts of release assets",
type: "bool",
value: true,
},
histogram: {
name: "📊 Release Histogram",
title: "Show a histogram of download counts for each release asset",
type: "bool",
},
hideArchives: {
name: "🫥 Hide Archives",
title: "Hide source code archives (zip, tar.gz) in the release assets",
type: "bool",
},
},
},
extendedSearch: {
name: "🔍 Extended Search",
type: "folder",
items: {
goTo: {
name: "🚀 Go To",
title: "Add items for going to repositories, issues etc. in search suggestions",
type: "bool",
value: false,
},
},
},
additional: {
name: "🪄 Additional Features",
type: "folder",
items: {
extendedUserInfo: {
name: "👤 Extended User Info",
title: "Show extended information about users",
type: "bool",
value: false,
},
previewPlus: {
name: "🔮 Preview Plus",
title: "Allow previewing more file types (e.g. MP4, WEBM) (may not work, see README)",
type: "bool",
value: false,
},
trackingPrevention: {
name: "🎭 Tracking Prevention",
title: () => {
return `Prevent some tracking by GitHub (${name} has prevented tracking ${GM_getValue("trackingPrevented", 0)} time(s))`;
},
type: "bool",
value: false,
},
},
},
advanced: {
name: "⚙️ Advanced Settings",
type: "folder",
items: {
token: {
name: "🔑 Personal Access Token",
title: "Your personal access token for GitHub API, starting with `github_pat_` (used for increasing rate limit)",
type: "str",
},
rateLimit: {
name: "📈 Rate Limit",
title: "View the current rate limit status",
type: "action",
},
debug: {
name: "🐞 Debug",
title: "Enable debug mode",
type: "bool",
},
},
},
};
const config = new GM_config(configDesc);
// Helper function for css
function injectCSS(id, css) {
const style = document.head.appendChild(
document.createElement("style"),
);
style.id = idPrefix + id;
style.textContent = css;
return style;
}
function cssHelper(id, enable) {
const current = document.getElementById(idPrefix + id);
if (current) {
current.disabled = !enable;
} else if (enable) {
injectCSS(id, dynamicStyles[id]);
}
}
// General functions
const $ = document.querySelector.bind(document);
const $$ = document.querySelectorAll.bind(document);
/**
* Log the given arguments if debug mode is enabled.
* @param {...any} args The arguments to log.
*/
function log(...args) {
if (config.get("advanced.debug"))
console.log(
`%c[${name}]%c`,
`color:${themeColor};`,
"color: unset;",
...args,
);
}
/**
* Warn the given arguments.
* @param {...any} args The arguments to warn.
*/
function warn(...args) {
console.warn(
`%c[${name}]%c`,
`color:${themeColor};`,
"color: unset;",
...args,
);
}
/**
* Replace the domain of the given URL with the top domain if needed.
* @param {string} url The URL to fix.
* @returns {string} The fixed URL.
*/
function fixDomain(url) {
return topDomain === officialDomain
? url
: url.replace(
`https://${officialDomain}/`,
`https://${topDomain}/`,
); // Replace top domain
}
/**
* Fetch the given URL with the personal access token, if given. Also updates rate limit.
* @param {string} url The URL to fetch.
* @param {RequestInit} options The options to pass to `fetch`.
* @returns {Promise<Response>} The response from the fetch.
*/
async function fetchWithToken(url, options) {
const token = config.get("advanced.token");
if (token) {
if (!options) options = {};
if (!options.headers) options.headers = {};
options.headers.accept = "application/vnd.github+json";
options.headers["X-GitHub-Api-Version"] = "2022-11-28";
options.headers.Authorization = `Bearer ${token}`;
}
const r = await fetch(url, options);
function parseRateLimit(suffix, defaultValue = -1) {
const parsed = parseInt(r.headers.get(`X-RateLimit-${suffix}`));
return isNaN(parsed) ? defaultValue : parsed;
}
// Update rate limit
for (const key of Object.keys(rateLimit)) {
rateLimit[key] = parseRateLimit(key); // Case-insensitive
}
const resetDate = new Date(rateLimit.reset * 1000).toLocaleString();
log(
`Rate limit: remaining ${rateLimit.remaining}/${rateLimit.limit}, resets at ${resetDate}`,
);
if (r.status === 403 || r.status === 429) {
// If we get 403 or 429, we've hit the rate limit.
throw new Error(`Rate limit exceeded! Will reset at ${resetDate}`);
} else if (rateLimit.remaining === 0) {
warn(`Rate limit has been exhausted! Will reset at ${resetDate}`);
}
return r;
}
// CSS-related features
const dynamicStyles = {
"code.cursorBlink":
"[data-testid='navigation-cursor'] { animation: blink 1s step-end infinite; }",
"code.cursorAnimation":
"[data-testid='navigation-cursor'] { transition: top 0.1s ease-in-out, left 0.1s ease-in-out; }",
"code.fullWidth": "#copilot-button-positioner { padding-right: 0; }",
"appearance.stickyAvatar": `
.pull-discussion-timeline .TimelineItem-avatar {
position: relative;
margin-left: -40px;
left: -32px;
& > a[data-hovercard-type='user'], & > img.avatar {
position: sticky;
top: 5em;
}
}
#issue-timeline [class*='Avatar-module__avatarOuter__'] {
position: sticky;
top: 3em;
}
[data-testid='issue-viewer-issue-container'] [class*='Avatar-module__avatarOuter__'] {
position: sticky;
top: 4em;
}
/* .page-responsive .timeline-comment--caret {
&::before, &::after {
position: sticky;
top: 4em;
margin-top: -1em;
transform: translate(-0.5em, 2em);
}
} */
`,
"appearance.hideHeaderUnderline": `.markdown-heading > .heading-element { border-bottom: none; }`,
};
for (const prop in dynamicStyles) {
cssHelper(prop, config.get(prop));
}
// Code features
/**
* Set the tab size for the code blocks.
* @param {number} size The tab size to set.
*/
function tabSize(size) {
const id = idPrefix + "tabSize";
const style = document.getElementById(id) ?? injectCSS(id, "");
style.textContent = `pre, code { tab-size: ${size}; }`;
}
// Appearance features
/**
* Dynamic styles for the enum settings.
* @type {Object<string, Array<string>>}
*/
const enumStyles = {
"appearance.dashboard": [
"/* Default */",
"/* Hide Copilot */ #dashboard > .news > .copilotPreview__container { display: none; }",
"/* Hide Feed */ #dashboard > .news > feed-container { display: none; }",
`/* Mobile-Like */
.application-main > div > aside[aria-label="Account context"] {
display: block !important;
}
#dashboard > .news {
> .copilotPreview__container { display: none; }
> feed-container { display: none; }
> .d-block.d-md-none { display: block !important; }
}`,
],
"appearance.leftSidebar": [
"/* Default */",
"/* Hidden */ .application-main .feed-background > aside.feed-left-sidebar { display: none; }",
],
"appearance.rightSidebar": [
"/* Default */",
"/* Hide 'Latest changes' */ aside.feed-right-sidebar > .dashboard-changelog { display: none; }",
"/* Hide 'Explore repositories' */ aside.feed-right-sidebar > [aria-label='Explore repositories'] { display: none; }",
"/* Hide Completely */ aside.feed-right-sidebar { display: none; }",
],
};
/**
* Helper function to configure enum styles.
* @param {string} id The ID of the style.
* @param {string} mode The mode to set.
*/
function enumStyleHelper(id, mode) {
const style =
document.getElementById(idPrefix + id) ?? injectCSS(id, "");
style.textContent = enumStyles[id][mode];
}
for (const prop in enumStyles) {
enumStyleHelper(prop, config.get(prop));
}
// Catppuccin icons
const flavors = ["default", "latte", "frappe", "macchiato", "mocha"];
const flavor = flavors[config.get("appearance.catppuccinIcons")];
const catppuccinPalette = JSON.parse(
GM_getResourceText("catppuccin-palette"),
);
function updateCatppuccinColors(flavor = "mocha") {
const id = "ghp-catppuccin-icons-css-variables";
let styleEl = $(`#${id}`);
if (!styleEl) {
styleEl = document.createElement("style");
styleEl.setAttribute("id", id);
document.documentElement.appendChild(styleEl);
}
if (flavor === "default") {
styleEl.textContent = "";
return;
}
const colors = catppuccinPalette[flavor];
const vars = Object.entries(colors)
.map(([name, hex]) => ` --ctp-${name}: ${hex};`)
.join("\n");
styleEl.textContent = `:root {\n${vars}\n}`;
}
updateCatppuccinColors(flavor);
const associations = JSON.parse(
GM_getResourceText("catppuccin-associations"),
);
const icons = JSON.parse(GM_getResourceText("catppuccin-icons"));
// https://github.com/catppuccin/web-file-explorer-icons/blob/2eded13cf948ad05d20d9de91f12fd1f75ff0c23/src/entries/content/lib.ts#L64-L102
function getIconName(filename, filetype = "file") {
if (filetype === "submodule") {
return "folder_git";
}
if (filetype === "folder" || filetype === "folder-open") {
let iconName = "_folder";
if (filename in associations.folderNames) {
iconName = associations.folderNames[filename];
} else if (filename.toLowerCase() in associations.folderNames) {
iconName = associations.folderNames[filename.toLowerCase()];
}
if (filetype === "folder-open") {
return iconName + "_open";
} else {
return iconName;
}
}
// Match by exact file name (case-sensitive first, then case-insensitive)
if (filename in associations.fileNames)
return associations.fileNames[filename];
if (filename.toLowerCase() in associations.fileNames)
return associations.fileNames[filename.toLowerCase()];
// Match by exact file name (case-sensitive first, then case-insensitive)
if (filename in associations.fileNames)
return associations.fileNames[filename];
if (filename.toLowerCase() in associations.fileNames)
return associations.fileNames[filename.toLowerCase()];
// Compute all possible extensions (e.g. "foo.test.ts" → ["test.ts", "ts"])
const fileExtensions = [];
if (filename.length <= 255) {
for (let i = 0; i < filename.length; i++) {
if (filename[i] === ".") {
fileExtensions.push(filename.toLowerCase().slice(i + 1));
}
}
}
// Match by extension, then language ID
for (const ext of fileExtensions) {
if (ext in associations.fileExtensions)
return associations.fileExtensions[ext];
if (ext in associations.languageIds)
return associations.languageIds[ext];
}
// Fallback
return "_file";
}
const iconClass = "ghp-catppuccin-icon";
const selectors = [
{
// Main file explorer
rows: ".react-directory-row .react-directory-filename-column",
icon: "svg.octicon",
filename: ".react-directory-filename-cell a",
},
{
// Main file explorer - parent directory
rows: "#folder-row-0 a",
icon: "svg.octicon",
filename: "div",
},
{
// Sidebar file explorer
rows: ".PRIVATE_TreeView-item > .PRIVATE_TreeView-item-container > .PRIVATE_TreeView-item-content",
icon: ".PRIVATE_TreeView-item-visual svg.octicon",
filename: ".PRIVATE_TreeView-item-content-text",
},
];
injectCSS(
"catppuccin-icons-hide",
// "svg.octicon:has(+ .ghp-catppuccin-icon) { display: none; }",
".ghp-catppuccin-icon + svg.octicon { display: none; }",
);
function updateIcons(body = document.body) {
if (config.get("appearance.catppuccinIcons") === 0) return;
selectors.forEach(({ rows, icon, filename }) => {
body.querySelectorAll(rows).forEach((row) => {
const iconEl = row.querySelector(icon);
const filenameEl = row.querySelector(filename);
if (!iconEl || !filenameEl) return;
let filetype = "file";
if (
iconEl.classList.contains("octicon-file-directory") ||
iconEl.classList.contains("octicon-file-directory-fill")
) {
filetype = "folder";
} else if (
iconEl.classList.contains("octicon-file-directory-open") ||
iconEl.classList.contains(
"octicon-file-directory-open-fill",
)
) {
filetype = "folder-open";
} else if (
iconEl.classList.contains("octicon-file-submodule")
) {
filetype = "submodule";
}
const name = filenameEl.textContent.trim();
const iconName = getIconName(name, filetype);
log(`${name} -> ${iconName}`);
const svg = icons[iconName];
const newIcon = new DOMParser()
.parseFromString(svg, "image/svg+xml")
.querySelector("svg");
if (newIcon) {
newIcon.setAttribute("width", "16");
newIcon.setAttribute("height", "16");
newIcon.classList.add(iconClass);
// Remove existing custom icon if any
const existingIcon = row.querySelector(`.${iconClass}`);
existingIcon?.remove();
// Insert the new icon
iconEl.insertAdjacentElement("beforebegin", newIcon);
} else {
warn(`Icon "${iconName}" not found for file "${name}"`);
}
});
});
}
document.addEventListener("soft-nav:react-done", () => {
updateIcons();
});
document.addEventListener("turbo:load", () => {
updateIcons();
});
// Release features
/**
* Get the release data for the given owner, repo and version.
* @param {string} owner The owner of the repository.
* @param {string} repo The repository name.
* @param {string} version The version tag of the release.
* @returns {Promise<Object>} The release data, which resolves to an object mapping download link to details.
*/
async function getReleaseData(owner, repo, version) {
if (!releaseData[owner]) releaseData[owner] = {};
if (!releaseData[owner][repo]) releaseData[owner][repo] = {};
if (!releaseData[owner][repo][version]) {
const url = `https://api.${topDomain}/repos/${owner}/${repo}/releases/tags/${version}`;
const promise = fetchWithToken(url)
.then((response) => response.json())
.then((data) => {
log(
`Fetched release data for ${owner}/${repo}@${version}:`,
data,
);
const assets = {};
for (const asset of data.assets) {
assets[fixDomain(asset.browser_download_url)] = {
downloads: asset.download_count,
uploader: {
name: asset.uploader.login,
url: fixDomain(asset.uploader.html_url),
},
};
}
log(
`Processed release data for ${owner}/${repo}@${version}:`,
assets,
);
return assets;
});
releaseData[owner][repo][version] = promise;
}
return releaseData[owner][repo][version];
}
/**
* Create a link to the uploader's profile.
* @param {Object} uploader The uploader information.
* @param {string} uploader.name The name of the uploader.
* @param {string} uploader.url The URL to the uploader's profile.
*/
function createUploaderLink(uploader) {
const link = document.createElement("a");
link.href = uploader.url;
link.setAttribute("class", "text-sm-left flex-auto ml-md-3 nowrap");
if (uploader.url.startsWith(`https://${topDomain}/apps/`)) {
link.classList.add("color-fg-success");
// Remove suffix `[bot]` from the name if exists
const name = uploader.name.endsWith("[bot]")
? uploader.name.slice(0, -5)
: uploader.name;
link.title = `Uploaded by GitHub App @${name}`;
link.textContent = `@${name}`;
} else {
link.classList.add("color-fg-muted");
link.setAttribute(
"data-hovercard-url",
`/users/${uploader.name}/hovercard`,
);
link.title = `Uploaded by @${uploader.name}`;
link.textContent = `@${uploader.name}`;
}
return link;
}
/**
* Create a span element with the given download count.
* @param {number} downloads The download count.
*/
function createDownloadCount(downloads) {
const downloadCount = document.createElement("span");
downloadCount.textContent = `${downloads} DL`;
downloadCount.title = `${downloads} downloads`;
downloadCount.setAttribute(
"class",
"color-fg-muted text-sm-left flex-shrink-0 flex-grow-0 ml-md-3 nowrap",
);
return downloadCount;
}
/**
* Show a histogram of the download counts for the given release entry.
* @param {HTMLElement} asset One of the release assets.
* @param {number} value The download count of the asset.
* @param {number} max The maximum download count of all assets.
*/
function showHistogram(asset, value, max) {
asset.style.setProperty("--percent", `${(value / max) * 100}%`);
}
/**
* Adding additional info (download count) to the release entries under the given element.
* @param {HTMLElement} el The element to search for release entries.
* @param {Object} info Additional information about the release (owner, repo, version).
* @param {string} info.owner The owner of the repository.
* @param {string} info.repo The repository name.
* @param {string} info.version The version of the release.
*/
async function addAdditionalInfoToRelease(el, info) {
const entries = el.querySelectorAll("ul > li");
const assets = [];
const hideArchives = config.get("release.hideArchives");
entries.forEach((asset) => {
if (asset.querySelector("svg.octicon-package")) {
// Release asset
assets.push(asset);
} else if (hideArchives) {
// Source code archive
asset.remove();
}
});
const releaseData = await getReleaseData(
info.owner,
info.repo,
info.version,
);
if (!releaseData) return;
const maxDownloads = Math.max(
0,
...Object.values(releaseData).map((asset) => asset.downloads),
);
assets.forEach((asset) => {
const downloadLink = asset.children[0].querySelector("a")?.href;
const statistics = asset.children[1];
const assetInfo = releaseData[downloadLink];
if (!assetInfo) return;
asset.classList.add("ghp-release-asset");
if (config.get("release.downloads")) {
const downloadCount = createDownloadCount(assetInfo.downloads);
statistics.prepend(downloadCount);
}
if (config.get("release.uploader")) {
const uploaderLink = createUploaderLink(assetInfo.uploader);
statistics.prepend(uploaderLink);
}
if (
config.get("release.histogram") &&
maxDownloads > 0 &&
assets.length > 1
) {
showHistogram(asset, assetInfo.downloads, maxDownloads);
}
});
}
/**
* Handle the `include-fragment-replace` event.
* @param {CustomEvent} event The event object.
*/
function onFragmentReplace(event) {
const self = event.target;
const src = self.src;
const match = expandedAssetsRegex.exec(src);
if (!match) return;
const [_, owner, repo, version] = match;
const info = { owner, repo, version };
const fragment = event.detail.fragment;
log("Found expanded assets:", fragment);
for (const child of fragment.children) {
addAdditionalInfoToRelease(child, info);
}
}
/**
* Find all release entries and setup listeners to show the download count.
*/
function setupListeners() {
log("Calling setupListeners");
if (
!config.get("release.downloads") &&
!config.get("release.uploader") &&
!config.get("release.histogram")
)
return; // No need to run
// IncludeFragmentElement: https://github.com/github/include-fragment-element/blob/main/src/include-fragment-element.ts
const fragments = document.querySelectorAll(
'[data-hpc] details[data-view-component="true"] include-fragment',
);
fragments.forEach((fragment) => {
if (!fragment.hasAttribute("data-ghp-listening")) {
fragment.toggleAttribute("data-ghp-listening", true);
fragment.addEventListener(
"include-fragment-replace",
onFragmentReplace,
{ once: true },
);
if (config.get("release.hideArchives")) {
// Fix assets count
const summary =
fragment.parentElement.previousElementSibling;
if (
summary.tagName === "SUMMARY" &&
summary.firstElementChild.textContent === "Assets"
) {
const counter = summary.querySelector("span.Counter");
if (counter) {
const count = parseInt(counter.textContent) - 2; // Exclude the source code archives
log(counter, count + 2, count);
counter.textContent = count.toString();
counter.title = count.toString();
}
}
}
}
});
}
if (location.hostname === topDomain) {
// Only run on GitHub main site
document.addEventListener("DOMContentLoaded", setupListeners, {
once: true,
});
// Examine event listeners on `document`, and you can see the event listeners for the `turbo:*` events. (Remember to check `Framework Listeners`)
document.addEventListener("turbo:load", setupListeners);
// Other possible approaches and reasons against them:
// - Use `MutationObserver` - Not efficient
// - Hook `CustomEvent` to make `include-fragment-replace` events bubble - Monkey-patching
// - Patch `IncludeFragmentElement.prototype.fetch`, just like GitHub itself did at `https://github.githubassets.com/assets/app/assets/modules/github/include-fragment-element-hacks.ts`
// - Monkey-patching
// - If using regex to modify the response, it would be tedious to maintain
// - If using `DOMParser`, the same HTML would be parsed twice
injectCSS(
"release",
`
@media (min-width: 1012px) { /* Making more room for the additional info */
.ghp-release-asset .col-lg-6 {
width: 40%; /* Originally ~50% */
}
}
.nowrap { /* Preventing text wrapping */
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.ghp-release-asset { /* Styling the histogram */
background: linear-gradient(to right, var(--bgColor-accent-muted) var(--percent, 0%), transparent 0);
}
`,
);
}
// Extended search features
// Go To provider
const REF_REGEX =
/^@?(?<owner>[A-Za-z0-9_.-]+)?(?:\/(?<repo>[A-Za-z0-9_.-]+))?(?:#(?<number>\d+))?$/;
class GoToProvider extends EventTarget {
priority = 1;
icon = "rocket";
name = "Go to..."; // plural group name (i.e. "repositories" or "teams") - will be the visual header
description = "Go to...";
singularItemName = "go to"; // singular name for an item (i.e. "repository" or "team") to construct a meaningful aria-label, doesn't appear visually
value = "go-to"; // visual name of the filter (i.e. "is:")
type = "search";
constructor(queryBuilder, input) {
super();
queryBuilder.addEventListener("query", (e) => {
this.handleEvent(e);
});
this.input = input;
}
/**
* Parses a reference string like:
* - `@owner`
* - `owner/repo`
* - `@owner/repo#123`
* - `#123`
*
* Returns:
* { owner: string|null, repo: string|null, number: number|null }
* or null if no valid parts are found.
*/
parseRef(str) {
const match = str.match(REF_REGEX);
const { owner, repo, number } = match?.groups || {};
const result = {
owner: owner ?? null,
repo: repo ?? null,
number: number ? Number(number) : null,
};
// Filling missing owner/repo from the current page if possible
const owner_present = Boolean(owner);
const repo_present = Boolean(repo);
const number_present = Boolean(number);
switch (true) {
// 000 No valid parts
case !owner_present && !repo_present && !number_present:
// 101 Only owner and number
case owner_present && !repo_present && number_present:
return null;
// 11x owner/repo provided
case owner_present && repo_present:
return result;
// 100 Only owner - Check leading `@`
case owner_present && !repo_present && !number_present: {
if (str.startsWith("@")) {
return result;
} else {
return null;
}
}
// case [false, true, true]:
// case [false, true, false]: {
// 01x Repo (and number) provided - try to get owner
case !owner_present && repo_present: {
const owner =
this.input.getAttribute("data-current-owner") ||
this.input.getAttribute("data-current-org");
if (owner) {
result.owner = owner;
return result;
} else {
return null;
}
}
// 001 Only number provided - try to get owner/repo
case !owner_present && !repo_present && number_present: {
const owner_repo = this.input.getAttribute(
"data-current-repository",
);
if (owner_repo) {
const [owner, repo] = owner_repo.split("/");
result.owner = owner;
result.repo = repo;
return result;
} else {
return null;
}
}
}
}
handleEvent(event) {
const query = event.rawQuery.trim();
log("GoToProvider handling query event:", event);
this.handleQuery(query);
}
handleQuery(query) {
const ref = this.parseRef(query);
if (!ref) return;
let value, url, icon;
if (ref.number) {
// Issue or PR
value = `${ref.owner}/${ref.repo}#${ref.number}`;
url = `/${ref.owner}/${ref.repo}/issues/${ref.number}`;
icon = "issue-opened"; // Use issue icon for both issues and PRs
} else if (ref.repo) {
// Repository
value = `${ref.owner}/${ref.repo}`;
url = `/${value}`;
icon = "repo";
} else {
// User or Organization
value = `@${ref.owner}`;
url = `/${ref.owner}`;
icon = "team"; // The person icon does not show up, so we use the team icon instead
}
this.dispatchEvent(
new SearchItem({
value,
url,
priority: 1,
icon,
}),
);
}
}
class SearchItem extends Event {
constructor({
value,
url,
priority = 1,
description = "",
icon = undefined, // Octicon
scope = "DEFAULT", // SearchScopeText
prefixText = undefined,
prefixColor = undefined,
isFallbackSuggestion = undefined,
isUpdate = undefined,
}) {
super(isUpdate ? "update-item" : "search-item");
this.value = value;
this.action = { url };
this.priority = priority;
this.description = description;
this.icon = icon;
this.scope = scope;
this.prefixText = prefixText;
this.prefixColor = prefixColor;
this.isFallbackSuggestion = isFallbackSuggestion || false;
}
}
async function setupGoTo() {