Repository navigation
Expand file tree
/
Copy pathgithubrepocardinaboutsidebar.user.js
More file actions
592 lines (493 loc) · 16.2 KB
/
Copy pathgithubrepocardinaboutsidebar.user.js
File metadata and controls
592 lines (493 loc) · 16.2 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
// ==UserScript==
// @name GitHub Social Preview Card in About Sidebar
// @namespace https://github.com/
// @version 1.8.0
// @author MrKoby07
// @description Adds a repository social-preview image card directly below the About heading on GitHub repository home pages
// @license MIT
// @match https://github.com/*/*
// @match https://github.com/*/*/
// @exclude https://github.com/*/*/blob/*
// @exclude https://github.com/*/*/tree/*
// @exclude https://github.com/*/*/issues*
// @exclude https://github.com/*/*/pull*
// @exclude https://github.com/*/*/actions*
// @exclude https://github.com/*/*/projects*
// @exclude https://github.com/*/*/wiki*
// @exclude https://github.com/*/*/settings*
// @exclude https://github.com/*/*/security*
// @exclude https://github.com/*/*/network*
// @exclude https://github.com/*/*/stargazers*
// @exclude https://github.com/*/*/watchers*
// @exclude https://github.com/*/*/forks*
// @exclude https://github.com/*/*/releases*
// @exclude https://github.com/*/*/tags*
// @exclude https://github.com/*/*/commits*
// @exclude https://github.com/*/*/branches*
// @exclude https://github.com/*/*/compare/*
// @run-at document-idle
// @grant GM_getValue
// @grant GM_setValue
// @grant GM_registerMenuCommand
// @grant GM_xmlhttpRequest
// @grant GM_addStyle
// @connect api.github.com
// @homepageURL https://github.com/Master3307/GitHubRepoCardInAboutSidebar
// @supportURL https://github.com/Master3307/GitHubRepoCardInAboutSidebar/issues
// @icon https://github.com/favicon.ico
// @updateURL https://github.com/Master3307/GitHubRepoCardInAboutSidebar/raw/refs/heads/master/githubrepocardinaboutsidebar.user.js
// @downloadURL https://github.com/Master3307/GitHubRepoCardInAboutSidebar/raw/refs/heads/master/githubrepocardinaboutsidebar.user.js
// ==/UserScript==
(() => {
"use strict";
const TOKEN_KEY = "github_repo_card_token";
const TOKEN_BUTTON_VISIBLE_KEY = "github_repo_card_token_button_visible";
const FOOTER_VISIBLE_KEY = "github_repo_card_footer_visible";
const CARD_ID = "master3307-github-repo-card";
const CACHE_PREFIX = "github_repo_card_cache:";
const CACHE_TTL_MS = 15 * 60 * 1000;
const ABOUT_RETRY_ATTEMPTS = 20;
const ABOUT_RETRY_DELAY_MS = 100;
let navigationId = 0;
let retryTimer = null;
let observerTimer = null;
GM_addStyle(`
#${CARD_ID} {
margin: 8px 0 16px;
overflow: hidden;
border: 1px solid var(--borderColor-default, #30363d);
border-radius: 13px;
background: var(--bgColor-muted, #161b22);
color: var(--fgColor-default, #f0f6fc);
transition: border-color 120ms ease, background-color 120ms ease;
}
#${CARD_ID}:hover {
border-color: var(--borderColor-accent-emphasis, #1f6feb);
background: var(--bgColor-neutral-muted, #21262d);
}
#${CARD_ID} .ghrc-preview-link {
display: block;
color: inherit;
text-decoration: none;
}
#${CARD_ID} .ghrc-preview-link:hover .ghrc-preview {
filter: brightness(0.92);
}
#${CARD_ID} .ghrc-preview {
display: block;
width: 100%;
aspect-ratio: 2 / 1;
background: var(--bgColor-inset, #010409);
object-fit: cover;
transition: filter 120ms ease;
}
#${CARD_ID} .ghrc-footer {
display: flex;
align-items: center;
gap: 7px;
min-width: 0;
padding: 9px 10px;
border-top: 1px solid var(--borderColor-default, #30363d);
}
#${CARD_ID} .ghrc-footer[hidden] {
display: none;
}
#${CARD_ID} .ghrc-name {
min-width: 0;
overflow: hidden;
color: var(--fgColor-default, #f0f6fc);
font-size: 12px;
font-weight: 600;
line-height: 18px;
text-overflow: ellipsis;
white-space: nowrap;
}
#${CARD_ID} .ghrc-name:hover {
color: var(--fgColor-accent, #58a6ff);
text-decoration: none;
}
#${CARD_ID} .ghrc-private {
flex: 0 0 auto;
padding: 1px 5px;
border: 1px solid var(--borderColor-default, #30363d);
border-radius: 999px;
color: var(--fgColor-muted, #8b949e);
font-size: 10px;
line-height: 14px;
}
#${CARD_ID} .ghrc-settings {
flex: 0 0 auto;
margin-left: auto;
padding: 0;
border: 0;
color: var(--fgColor-muted, #8b949e);
background: transparent;
cursor: pointer;
font-size: 11px;
line-height: 18px;
}
#${CARD_ID} .ghrc-settings:hover {
color: var(--fgColor-accent, #58a6ff);
}
`);
function getCurrentRepository() {
const parts = location.pathname.split("/").filter(Boolean);
if (parts.length !== 2) return null;
const [owner, repo] = parts;
if (!owner || !repo) return null;
return {
owner,
repo,
fullName: `${owner}/${repo}`,
};
}
function isCurrentRepository(current) {
return (
location.pathname.replace(/\/$/, "") ===
`/${current.owner}/${current.repo}`
);
}
function getToken() {
return GM_getValue(TOKEN_KEY, "");
}
function setToken(token) {
GM_setValue(TOKEN_KEY, token.trim());
}
function isTokenButtonVisible() {
return GM_getValue(TOKEN_BUTTON_VISIBLE_KEY, true);
}
function setTokenButtonVisible(visible) {
GM_setValue(TOKEN_BUTTON_VISIBLE_KEY, visible);
}
function toggleTokenButtonVisibility() {
const shouldShow = !isTokenButtonVisible();
setTokenButtonVisible(shouldShow);
const tokenButton = document.querySelector(`#${CARD_ID} .ghrc-settings`);
if (tokenButton) tokenButton.hidden = !shouldShow;
}
function isFooterVisible() {
return GM_getValue(FOOTER_VISIBLE_KEY, true);
}
function setFooterVisible(visible) {
GM_setValue(FOOTER_VISIBLE_KEY, visible);
}
function toggleFooterVisibility() {
const shouldShow = !isFooterVisible();
setFooterVisible(shouldShow);
const footer = document.querySelector(`#${CARD_ID} .ghrc-footer`);
if (footer) footer.hidden = !shouldShow;
}
function cacheKey(fullName) {
return `${CACHE_PREFIX}${fullName.toLowerCase()}`;
}
function getCachedRepo(fullName) {
const cached = GM_getValue(cacheKey(fullName), null);
if (!cached || Date.now() - cached.savedAt > CACHE_TTL_MS) {
return null;
}
return cached.data;
}
function saveCachedRepo(fullName, data) {
GM_setValue(cacheKey(fullName), {
savedAt: Date.now(),
data,
});
}
function apiRequest(path) {
const token = getToken();
return new Promise((resolve, reject) => {
GM_xmlhttpRequest({
method: "GET",
url: `https://api.github.com${path}`,
responseType: "json",
headers: {
Accept: "application/vnd.github+json",
"X-GitHub-Api-Version": "2026-03-10",
...(token ? { Authorization: `Bearer ${token}` } : {}),
},
onload(response) {
if (response.status >= 200 && response.status < 300) {
resolve(response.response);
return;
}
reject({
status: response.status,
message: response.response?.message || response.statusText,
});
},
onerror() {
reject({
status: 0,
message: "Network request failed",
});
},
});
});
}
async function fetchRepository(owner, repo) {
const fullName = `${owner}/${repo}`;
const cached = getCachedRepo(fullName);
if (cached) return cached;
const data = await apiRequest(
`/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}`,
);
saveCachedRepo(fullName, data);
return data;
}
function textElement(tagName, className, text) {
const element = document.createElement(tagName);
element.className = className;
element.textContent = text;
return element;
}
function getPageSocialPreviewUrl() {
const selectors = [
'meta[property="og:image"]',
'meta[property="og:image:secure_url"]',
'meta[name="twitter:image"]',
'meta[name="twitter:image:src"]',
];
for (const selector of selectors) {
const imageUrl = document.querySelector(selector)?.content?.trim();
if (imageUrl) return imageUrl;
}
return null;
}
function getOpenGraphFallbackUrl(fullName) {
return `https://opengraph.githubassets.com/1/${encodeURIComponent(fullName)}`;
}
function getSocialPreviewUrl(
repository,
pageImageUrl = getPageSocialPreviewUrl(),
) {
const apiImageUrl =
typeof repository.social_preview_image_url === "string"
? repository.social_preview_image_url.trim()
: "";
return (
pageImageUrl ||
apiImageUrl ||
getOpenGraphFallbackUrl(repository.full_name)
);
}
function makeCard(
repository,
{ pageImageUrl = getPageSocialPreviewUrl() } = {},
) {
const card = document.createElement("div");
card.id = CARD_ID;
card.dataset.repo = repository.full_name;
const imageUrl = getSocialPreviewUrl(repository, pageImageUrl);
const previewLink = document.createElement("a");
previewLink.className = "ghrc-preview-link";
previewLink.href = imageUrl;
previewLink.target = "_blank";
previewLink.rel = "noopener noreferrer";
previewLink.title = "Open social-preview image";
const preview = document.createElement("img");
preview.className = "ghrc-preview";
preview.src = imageUrl;
preview.alt = `${repository.full_name} social preview`;
preview.loading = "eager";
preview.decoding = "async";
preview.addEventListener(
"error",
() => {
previewLink.remove();
},
{ once: true },
);
previewLink.append(preview);
const footer = document.createElement("div");
footer.className = "ghrc-footer";
footer.hidden = !isFooterVisible();
const repoLink = document.createElement("a");
repoLink.className = "ghrc-name";
repoLink.href = repository.html_url;
repoLink.target = "_blank";
repoLink.rel = "noopener noreferrer";
repoLink.textContent = repository.full_name;
repoLink.title = `Open ${repository.full_name}`;
footer.append(repoLink);
if (repository.private) {
footer.append(textElement("span", "ghrc-private", "Private"));
}
const settings = document.createElement("button");
settings.type = "button";
settings.className = "ghrc-settings";
settings.textContent = "Token";
settings.title = "Configure GitHub token";
settings.hidden = !isTokenButtonVisible();
settings.addEventListener("click", configureToken);
footer.append(settings);
card.append(previewLink, footer);
return card;
}
function makeQuickRepository(current, pageImageUrl) {
return {
full_name: current.fullName,
html_url: location.href,
private: false,
social_preview_image_url:
pageImageUrl || getOpenGraphFallbackUrl(current.fullName),
};
}
function upgradeCard(card, repository, pageImageUrl) {
if (!card.isConnected) return;
card.dataset.repo = repository.full_name;
const imageUrl = getSocialPreviewUrl(repository, pageImageUrl);
const previewLink = card.querySelector(".ghrc-preview-link");
const preview = card.querySelector(".ghrc-preview");
const repoLink = card.querySelector(".ghrc-name");
const footer = card.querySelector(".ghrc-footer");
const settings = card.querySelector(".ghrc-settings");
const privateBadge = card.querySelector(".ghrc-private");
if (previewLink) {
previewLink.href = imageUrl;
}
if (preview) {
const currentImageUrl = preview.getAttribute("src");
if (currentImageUrl !== imageUrl) {
preview.src = imageUrl;
}
preview.alt = `${repository.full_name} social preview`;
}
if (repoLink) {
repoLink.href = repository.html_url;
repoLink.textContent = repository.full_name;
repoLink.title = `Open ${repository.full_name}`;
}
if (repository.private && !privateBadge && footer) {
footer.insertBefore(
textElement("span", "ghrc-private", "Private"),
settings || null,
);
} else if (!repository.private && privateBadge) {
privateBadge.remove();
}
}
function findAboutHeading() {
const sidebar =
document.querySelector('[data-testid="repository-sidebar"]') ||
document.querySelector('aside[aria-label="Repository details"]') ||
document.querySelector(".Layout-sidebar");
const headings = sidebar
? [...sidebar.querySelectorAll("h2")]
: [...document.querySelectorAll("h2")];
return headings.find(
(heading) => heading.textContent.trim().replace(/\s+/g, " ") === "About",
);
}
function removeExistingCard() {
document.getElementById(CARD_ID)?.remove();
}
function scheduleInject({
attempts = ABOUT_RETRY_ATTEMPTS,
delay = ABOUT_RETRY_DELAY_MS,
} = {}) {
clearTimeout(retryTimer);
const current = getCurrentRepository();
if (!current) {
navigationId += 1;
removeExistingCard();
return;
}
const thisNavigation = ++navigationId;
const tryInject = async (remaining) => {
if (thisNavigation !== navigationId || !isCurrentRepository(current)) {
return;
}
const aboutHeading = findAboutHeading();
const existing = document.getElementById(CARD_ID);
if (
existing &&
existing.dataset.repo === current.fullName &&
aboutHeading &&
existing.previousElementSibling === aboutHeading
) {
return;
}
existing?.remove();
if (!aboutHeading) {
if (remaining > 0) {
retryTimer = setTimeout(() => tryInject(remaining - 1), delay);
}
return;
}
const pageImageUrl = getPageSocialPreviewUrl();
const quickRepository = makeQuickRepository(current, pageImageUrl);
const card = makeCard(quickRepository, { pageImageUrl });
aboutHeading.insertAdjacentElement("afterend", card);
try {
const repository = await fetchRepository(current.owner, current.repo);
if (
thisNavigation !== navigationId ||
!isCurrentRepository(current) ||
!card.isConnected
) {
return;
}
upgradeCard(card, repository, pageImageUrl);
} catch {
// Keep the immediately rendered page-metadata/Open Graph card.
}
};
void tryInject(attempts);
}
function configureToken() {
const currentToken = getToken();
const nextToken = prompt(
currentToken
? "Paste a replacement token, or leave this blank to remove the saved token."
: "Paste a fine-grained GitHub token. It is stored only in this userscript manager.",
"",
);
if (nextToken === null) return;
setToken(nextToken);
removeExistingCard();
scheduleInject();
}
GM_registerMenuCommand("Toggle footer visibility", toggleFooterVisibility);
GM_registerMenuCommand(
"Toggle Token button visibility",
toggleTokenButtonVisibility,
);
GM_registerMenuCommand("Configure GitHub repo-card token", configureToken);
GM_registerMenuCommand("Remove GitHub repo-card token", () => {
setToken("");
alert("The saved GitHub repo-card token was removed.");
removeExistingCard();
scheduleInject();
});
document.addEventListener("turbo:load", () => {
removeExistingCard();
scheduleInject();
});
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", () => scheduleInject(), {
once: true,
});
} else {
scheduleInject();
}
const observer = new MutationObserver(() => {
const current = getCurrentRepository();
if (!current) return;
const aboutHeading = findAboutHeading();
const card = document.getElementById(CARD_ID);
const cardIsCorrectlyPlaced =
card &&
card.dataset.repo === current.fullName &&
aboutHeading &&
card.previousElementSibling === aboutHeading;
if (!aboutHeading || cardIsCorrectlyPlaced || observerTimer) return;
observerTimer = setTimeout(() => {
observerTimer = null;
scheduleInject({ attempts: 5, delay: 150 });
}, 100);
});
observer.observe(document.documentElement, {
childList: true,
subtree: true,
});
})();