-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
462 lines (413 loc) · 13.8 KB
/
content.js
File metadata and controls
462 lines (413 loc) · 13.8 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
(() => {
"use strict";
// ── Config ──────────────────────────────────────────────
const BATCH_SIZE = 30;
const BATCH_DELAY_MS = 100;
const CACHE_TTL_MS = 30 * 60 * 1000;
const REPO_REGEX =
/^https?:\/\/github\.com\/([a-zA-Z0-9\-_.]+)\/([a-zA-Z0-9\-_.]+)\/?(?:[#?].*)?$/;
const PROCESSED_ATTR = "data-grc-processed";
const DEFAULT_DISPLAY = {
badge_time: true,
badge_stars: true,
badge_archived: true,
tt_description: true,
tt_last_push: true,
tt_created: false,
tt_stars: true,
tt_forks: true,
tt_issues: true,
tt_language: true,
tt_license: true,
tt_topics: true,
};
let displaySettings = { ...DEFAULT_DISPLAY };
async function loadDisplaySettings() {
try {
const result = await chrome.storage.sync.get("display");
if (result.display)
displaySettings = { ...DEFAULT_DISPLAY, ...result.display };
} catch {}
}
// Live-reload settings
try {
chrome.storage.onChanged.addListener((changes, area) => {
if (area !== "sync") return;
if (changes.display) {
displaySettings = { ...DEFAULT_DISPLAY, ...changes.display.newValue };
}
if (changes.github_pat) {
const newToken = changes.github_pat.newValue || "";
document
.querySelectorAll(".grc-rate-limited[data-grc-repo]")
.forEach(async (badge) => {
const [owner, repo] = badge.dataset.grcRepo.split("/");
const data = await fetchRepo(owner, repo, newToken);
if (data) badge.replaceWith(createBadge(data));
});
}
});
} catch {}
// ── Helpers ─────────────────────────────────────────────
function timeAgo(dateStr) {
const diff = Date.now() - new Date(dateStr).getTime();
const m = Math.floor(diff / 60000);
const h = Math.floor(diff / 3600000);
const d = Math.floor(diff / 86400000);
const mo = Math.floor(d / 30);
const y = Math.floor(d / 365);
if (m < 1) return "just now";
if (m < 60) return `${m}m ago`;
if (h < 24) return `${h}h ago`;
if (d < 30) return `${d}d ago`;
if (mo < 12) return `${mo}mo ago`;
return `${y}y ago`;
}
function freshnessLevel(dateStr) {
const d = (Date.now() - new Date(dateStr).getTime()) / 86400000;
if (d < 90) return "fresh";
if (d < 365) return "aging";
return "stale";
}
function fmtK(n) {
return n >= 1000
? `${(n / 1000).toFixed(1).replace(/\.0$/, "")}k`
: String(n);
}
function fmtDate(s) {
return new Date(s).toLocaleDateString("en-US", {
year: "numeric",
month: "short",
day: "numeric",
});
}
function esc(str) {
const d = document.createElement("div");
d.textContent = str;
return d.innerHTML;
}
/** Check if an element sits inside a container with a flipping CSS transform */
function isInFlippedContainer(el) {
let node = el.parentElement;
while (node && node !== document.body) {
const t = getComputedStyle(node).transform;
if (t && t !== "none") {
try {
const m = new DOMMatrix(t);
if (m.a < -0.5 || m.d < -0.5) return true;
} catch {}
}
node = node.parentElement;
}
return false;
}
// ── Cache ───────────────────────────────────────────────
const mem = new Map();
async function getCached(key) {
if (mem.has(key)) {
const e = mem.get(key);
if (Date.now() - e.ts < CACHE_TTL_MS) return e.data;
mem.delete(key);
}
try {
const r = await chrome.storage.local.get(key);
if (r[key] && Date.now() - r[key].ts < CACHE_TTL_MS) {
mem.set(key, r[key]);
return r[key].data;
}
} catch {}
return null;
}
async function setCache(key, data) {
const entry = { data, ts: Date.now() };
mem.set(key, entry);
try {
await chrome.storage.local.set({ [key]: entry });
} catch {}
}
// ── GitHub API ──────────────────────────────────────────
async function getToken() {
try {
const r = await chrome.storage.sync.get("github_pat");
return r.github_pat || "";
} catch {
return "";
}
}
async function fetchRepo(owner, repo, token) {
const ck = `grc:${owner}/${repo}`;
const cached = await getCached(ck);
if (cached) return cached;
const headers = { Accept: "application/vnd.github.v3+json" };
if (token) headers.Authorization = `Bearer ${token}`;
try {
const res = await fetch(`https://api.github.com/repos/${owner}/${repo}`, {
headers,
});
if (res.status === 404) {
const d = { notFound: true };
await setCache(ck, d);
return d;
}
if (res.status === 403 || res.status === 429)
return { rateLimited: true };
if (!res.ok) return { error: true, status: res.status };
const j = await res.json();
const data = {
pushed_at: j.pushed_at,
created_at: j.created_at,
stargazers_count: j.stargazers_count,
forks_count: j.forks_count,
open_issues_count: j.open_issues_count,
archived: j.archived,
description: j.description || "",
full_name: j.full_name,
language: j.language,
license: j.license?.spdx_id || j.license?.name || null,
topics: j.topics || [],
};
await setCache(ck, data);
return data;
} catch (err) {
return { error: true, message: err.message };
}
}
// ── Badge & Tooltip ─────────────────────────────────────
function createBadge(data) {
const s = displaySettings;
const el = document.createElement("span");
el.className = "grc-badge";
// Error states
if (data.notFound) {
el.classList.add("grc-not-found");
el.textContent = "404";
el.title = "Repository not found";
return el;
}
if (data.rateLimited) {
el.classList.add("grc-rate-limited");
el.textContent = "⏳";
el.title = "Rate limited — add token in settings";
return el;
}
if (data.error) {
el.classList.add("grc-error");
el.textContent = "⚠";
el.title = "Failed to fetch";
return el;
}
// Archived
if (data.archived) {
el.classList.add("grc-archived");
if (s.badge_archived)
el.innerHTML = `<span class="grc-label">archived</span>`;
} else {
const level = freshnessLevel(data.pushed_at);
el.classList.add(`grc-${level}`);
if (s.badge_time)
el.innerHTML = `<span class="grc-time">${timeAgo(data.pushed_at)}</span>`;
}
// Stars on badge
if (s.badge_stars) {
const sp = document.createElement("span");
sp.className = "grc-stars";
sp.textContent = `★ ${fmtK(data.stargazers_count)}`;
el.appendChild(sp);
}
// Tooltip — appended to body on hover to escape overflow:hidden containers
const tt = document.createElement("div");
tt.className = "grc-tooltip";
tt.innerHTML = buildTooltip(data);
el.appendChild(tt);
el.addEventListener("mouseenter", () => {
const rect = el.getBoundingClientRect();
document.body.appendChild(tt);
tt.style.display = "block";
const ttHeight = tt.offsetHeight || 200;
const spaceBelow = window.innerHeight - rect.bottom;
const flip = spaceBelow < ttHeight + 10;
tt.classList.toggle("grc-flip", flip);
tt.style.left = rect.left + rect.width / 2 + "px";
tt.style.top = flip
? rect.top - ttHeight - 6 + "px"
: rect.bottom + 6 + "px";
});
el.addEventListener("mouseleave", () => {
tt.style.display = "none";
el.appendChild(tt);
});
return el;
}
function buildTooltip(data) {
const s = displaySettings;
const L = [];
L.push(`<div class="grc-tt-header">${esc(data.full_name)}</div>`);
if (s.tt_description && data.description)
L.push(`<div class="grc-tt-desc">${esc(data.description)}</div>`);
if (s.tt_topics && data.topics && data.topics.length > 0) {
const tags = data.topics
.slice(0, 8)
.map((t) => `<span class="grc-tt-topic">${esc(t)}</span>`)
.join("");
L.push(`<div class="grc-tt-topics">${tags}</div>`);
}
L.push(`<div class="grc-tt-divider"></div>`);
const row = (label, val) =>
`<div class="grc-tt-row"><span>${label}</span><span>${val}</span></div>`;
if (s.tt_last_push)
L.push(
row(
"Last push:",
`${fmtDate(data.pushed_at)} (${timeAgo(data.pushed_at)})`,
),
);
if (s.tt_created)
L.push(
row(
"Created:",
`${fmtDate(data.created_at)} (${timeAgo(data.created_at)})`,
),
);
if (s.tt_stars)
L.push(row("Stars:", `★ ${data.stargazers_count.toLocaleString()}`));
if (s.tt_forks)
L.push(row("Forks:", `🍴 ${data.forks_count.toLocaleString()}`));
if (s.tt_issues)
L.push(row("Open issues:", data.open_issues_count.toLocaleString()));
if (s.tt_language && data.language)
L.push(row("Language:", esc(data.language)));
if (s.tt_license && data.license)
L.push(row("License:", esc(data.license)));
if (data.archived)
L.push(
`<div class="grc-tt-archived">⚫ This repository is archived</div>`,
);
return L.join("");
}
// ── Scan & Process ──────────────────────────────────────
function extractRepoLinks() {
const links = document.querySelectorAll(
`a[href*="github.com"]:not([${PROCESSED_ATTR}])`,
);
const results = [];
// Skip links pointing to the same repo as the current page
const pageMatch = location.href.match(REPO_REGEX);
const pageRepo = pageMatch
? `${pageMatch[1].toLowerCase()}/${pageMatch[2].toLowerCase().replace(/\.git$/, "").split("/")[0].split("#")[0].split("?")[0]}`
: null;
const skipOwners = new Set([
"topics",
"explore",
"settings",
"notifications",
"pulls",
"issues",
"marketplace",
"sponsors",
"orgs",
"users",
"features",
"security",
"pricing",
"enterprise",
"login",
"join",
"about",
"collections",
"events",
"customer-stories",
]);
for (const link of links) {
const match = link.href.match(REPO_REGEX);
if (!match) continue;
// Skip links inside editable areas (e.g. Gmail compose, rich text editors)
if (link.closest('[contenteditable="true"], [contenteditable=""], [role="textbox"]'))
continue;
// Skip links inside CSS-flipped containers (e.g. Google search breadcrumb area)
if (isInFlippedContainer(link)) {
link.setAttribute(PROCESSED_ATTR, "1");
continue;
}
let [, owner, repo] = match;
repo = repo
.replace(/\.git$/, "")
.split("/")[0]
.split("#")[0]
.split("?")[0];
const repoKey = `${owner.toLowerCase()}/${repo.toLowerCase()}`;
if (skipOwners.has(owner.toLowerCase()) || !repo) continue;
if (pageRepo && repoKey === pageRepo) continue;
link.setAttribute(PROCESSED_ATTR, "1");
results.push({ link, owner, repo });
}
return results;
}
function createLoader() {
const el = document.createElement("span");
el.className = "grc-loader";
return el;
}
async function processPage() {
const entries = extractRepoLinks();
if (!entries.length) return;
const token = await getToken();
// Insert loaders immediately
for (const entry of entries) {
const loader = createLoader();
entry.link.parentNode.insertBefore(loader, entry.link.nextSibling);
entry.loader = loader;
}
// Fetch and replace loaders with badges
for (let i = 0; i < entries.length; i += BATCH_SIZE) {
const batch = entries.slice(i, i + BATCH_SIZE);
await Promise.all(
batch.map(({ link, owner, repo, loader }) =>
fetchRepo(owner, repo, token).then((data) => {
if (!data) {
loader.remove();
return;
}
const badge = createBadge(data);
if (data.rateLimited) badge.dataset.grcRepo = `${owner}/${repo}`;
loader.replaceWith(badge);
}),
),
);
if (i + BATCH_SIZE < entries.length)
await new Promise((r) => setTimeout(r, BATCH_DELAY_MS));
}
}
// ── Init ────────────────────────────────────────────────
async function init() {
try {
const r = await chrome.storage.sync.get("enabled");
if (r.enabled === false) return;
} catch {}
await loadDisplaySettings();
await processPage();
const observer = new MutationObserver((mutations) => {
let found = false;
for (const m of mutations) {
for (const n of m.addedNodes) {
if (
n.nodeType === 1 &&
(n.matches?.("a[href*='github.com']") ||
n.querySelector?.("a[href*='github.com']"))
) {
found = true;
break;
}
}
if (found) break;
}
if (found) {
clearTimeout(observer._t);
observer._t = setTimeout(processPage, 500);
}
});
observer.observe(document.body, { childList: true, subtree: true });
}
if (document.readyState === "loading")
document.addEventListener("DOMContentLoaded", init);
else init();
})();