Repository navigation
Expand file tree
/
Copy pathcontent.js
More file actions
405 lines (366 loc) · 15.1 KB
/
Copy pathcontent.js
File metadata and controls
405 lines (366 loc) · 15.1 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
// Adds two pickers to GitHub's header breadcrumb:
// - an org switcher next to the owner crumb, on every page that has one
// - a full repository picker after the owner crumb on org pages and your own
// profile, where the built-in repo picker would sit on a repo page
// All data comes from github.com with the existing session, so no token is needed.
const ORG_BUTTON_ID = "gos-org-button";
const REPO_BUTTON_ID = "gos-repo-button";
const PANEL_ID = "gos-panel";
const ORG_CACHE_MS = 24 * 60 * 60 * 1000;
const REPO_CACHE_MS = 5 * 60 * 1000;
const CARET =
'<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path fill="currentColor" d="m4.427 7.427 3.396 3.396a.25.25 0 0 0 .354 0l3.396-3.396A.25.25 0 0 0 11.396 7H4.604a.25.25 0 0 0-.177.427Z"/></svg>';
// ---------------------------------------------------------------------------
// Data
function storageGet(area, defaults) {
return new Promise((resolve) => chrome.storage[area].get(defaults, resolve));
}
// Scrapes the org list from the settings page, which renders it server side.
async function discoverOrgs() {
const res = await fetch("/settings/organizations");
if (!res.ok) return [];
const doc = new DOMParser().parseFromString(await res.text(), "text/html");
return [...doc.querySelectorAll('.Box-row strong > a[href^="/"]')]
.map((a) => a.getAttribute("href").slice(1))
.filter((name) => name && !name.includes("/"));
}
async function getOrgs() {
const { extraOrgs } = await storageGet("sync", { extraOrgs: [] });
const { orgCache } = await storageGet("local", { orgCache: null });
let found = orgCache && Date.now() - orgCache.at < ORG_CACHE_MS ? orgCache.orgs : null;
if (!found) {
try {
found = await discoverOrgs();
} catch {
found = [];
}
if (found.length) chrome.storage.local.set({ orgCache: { at: Date.now(), orgs: found } });
}
const all = [...found, ...extraOrgs, ...(viewerLogin() ? [viewerLogin()] : [])];
return [...new Map(all.map((o) => [o.toLowerCase(), o])).values()];
}
// The signed-in user, so the personal account can sit next to the orgs.
function viewerLogin() {
return document.querySelector('meta[name="user-login"]')?.content || "";
}
// Search used by the org switcher. This is the endpoint behind GitHub's own repo picker.
async function searchRepos(org, query) {
const url = `/_global-navigation/repositories/${encodeURIComponent(org)}?query=${encodeURIComponent(query)}`;
try {
const res = await fetch(url, {
headers: { Accept: "application/json", "X-Requested-With": "XMLHttpRequest" },
});
if (!res.ok) return [];
return ((await res.json()).repositories || []).map((r) => ({
name: r.name,
href: `/${r.nameWithOwner}`,
badge: r.visibility === "public" ? "" : r.visibility,
}));
} catch {
return [];
}
}
// Full list from the org's Repositories page, which serves JSON when asked for it.
// Sorted by last update, the same as that page.
async function fetchRepoPage(org, page) {
const res = await fetch(`/orgs/${encodeURIComponent(org)}/repositories?type=all&page=${page}`, {
headers: { Accept: "application/json" },
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return (await res.json()).payload.orgReposPageRoute;
}
async function orgRepos(org) {
const first = await fetchRepoPage(org, 1);
const rest = await Promise.all(
Array.from({ length: Math.max(0, first.pageCount - 1) }, (_, i) => fetchRepoPage(org, i + 2))
);
return [first, ...rest]
.flatMap((p) => p.repositories)
.map((r) => ({
name: r.name,
href: `/${r.owner}/${r.name}`,
description: r.description || "",
badge: /^public$/i.test(r.type) ? "" : r.type.toLowerCase(),
}));
}
// User profiles only render their repository tab as HTML, so scrape it page by page.
async function userRepos(user) {
const repos = [];
for (let page = 1; page <= 20; page++) {
const res = await fetch(`/${encodeURIComponent(user)}?tab=repositories&page=${page}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const doc = new DOMParser().parseFromString(await res.text(), "text/html");
for (const li of doc.querySelectorAll("#user-repositories-list li")) {
const link = li.querySelector('[itemprop="name codeRepository"]');
if (!link) continue;
const label = li.querySelector(".Label")?.textContent.trim() || "";
repos.push({
name: link.textContent.trim(),
href: link.getAttribute("href"),
description: li.querySelector('[itemprop="description"]')?.textContent.trim() || "",
badge: /^public$/i.test(label) ? "" : label.toLowerCase(),
});
}
if (!doc.querySelector('a.next_page, .pagination a[rel="next"]')) break;
}
return repos;
}
async function allRepos(owner) {
const key = `gos-repos:${owner.toLowerCase()}`;
const cached = JSON.parse(sessionStorage.getItem(key) || "null");
if (cached && Date.now() - cached.at < REPO_CACHE_MS) return cached.repos;
let repos;
try {
repos = await orgRepos(owner);
} catch {
repos = await userRepos(owner);
}
sessionStorage.setItem(key, JSON.stringify({ at: Date.now(), repos }));
return repos;
}
// ---------------------------------------------------------------------------
// Panel
function closePanel() {
const panel = document.getElementById(PANEL_ID);
if (!panel) return;
panel.remove();
document.removeEventListener("mousedown", onOutside, true);
document.querySelectorAll(`#${ORG_BUTTON_ID}, #${REPO_BUTTON_ID}`).forEach((b) => b.setAttribute("aria-expanded", "false"));
}
function onOutside(e) {
const panel = document.getElementById(PANEL_ID);
if (panel && !panel.contains(e.target) && !e.target.closest(`#${ORG_BUTTON_ID}, #${REPO_BUTTON_ID}`)) {
closePanel();
}
}
// Opens a panel with a search box. `render(query, list)` fills the list and
// returns the item to highlight first.
function openPanel(btn, title, placeholder, render) {
closePanel();
const panel = document.createElement("div");
panel.id = PANEL_ID;
panel.innerHTML = `
<div class="gos-title"></div>
<input class="gos-search" type="text" autocomplete="off" spellcheck="false">
<div class="gos-list" role="listbox"></div>`;
panel.querySelector(".gos-title").textContent = title;
const input = panel.querySelector(".gos-search");
input.placeholder = placeholder;
const list = panel.querySelector(".gos-list");
const rect = btn.getBoundingClientRect();
panel.style.top = `${rect.bottom + 6}px`;
panel.style.left = `${Math.max(8, Math.min(rect.left, window.innerWidth - 380))}px`;
document.body.appendChild(panel);
btn.setAttribute("aria-expanded", "true");
document.addEventListener("mousedown", onOutside, true);
let seq = 0;
let timer;
const setActive = (el) => {
list.querySelector(".gos-active")?.classList.remove("gos-active");
if (el) {
el.classList.add("gos-active");
el.scrollIntoView({ block: "nearest" });
}
};
const update = async () => {
const mine = ++seq;
const frag = document.createDocumentFragment();
await render(input.value.trim(), frag);
if (mine !== seq || !panel.isConnected) return;
list.replaceChildren(frag);
setActive(list.querySelector(".gos-item"));
};
input.addEventListener("input", () => {
clearTimeout(timer);
timer = setTimeout(update, 120);
});
input.addEventListener("keydown", (e) => {
const items = [...list.querySelectorAll(".gos-item")];
const idx = items.indexOf(list.querySelector(".gos-active"));
if (e.key === "ArrowDown") {
e.preventDefault();
setActive(items[Math.min(items.length - 1, idx + 1)]);
} else if (e.key === "ArrowUp") {
e.preventDefault();
setActive(items[Math.max(0, idx - 1)]);
} else if (e.key === "Enter") {
const active = list.querySelector(".gos-active");
if (active) {
e.preventDefault();
if (e.metaKey || e.ctrlKey) window.open(active.href, "_blank");
else location.href = active.href;
}
} else if (e.key === "Escape") {
closePanel();
btn.focus();
}
});
list.addEventListener("mousemove", (e) => {
const item = e.target.closest(".gos-item");
if (item) setActive(item);
});
input.focus();
list.innerHTML = '<div class="gos-note">Loading…</div>';
update();
}
function el(tag, className, text) {
const node = document.createElement(tag);
if (className) node.className = className;
if (text != null) node.textContent = text;
return node;
}
function orgRow(org, current) {
const a = el("a", "gos-org gos-item");
a.href = `/${org}`;
const img = el("img");
img.src = `https://github.com/${encodeURIComponent(org)}.png?size=40`;
img.alt = "";
a.append(img, el("span", "gos-name", org));
const personal = org.toLowerCase() === viewerLogin().toLowerCase();
if (current || personal) {
a.append(el("span", "gos-tag", [current && "current", personal && "personal"].filter(Boolean).join(", ")));
}
return a;
}
const HOME_ICON =
'<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path fill="currentColor" d="M6.906.664a1.749 1.749 0 0 1 2.187 0l5.25 4.2c.415.332.657.835.657 1.367v7.019A1.75 1.75 0 0 1 13.25 15h-3.5a.75.75 0 0 1-.75-.75V9H7v5.25a.75.75 0 0 1-.75.75h-3.5A1.75 1.75 0 0 1 1 13.25V6.23c0-.531.242-1.034.657-1.366l5.25-4.2Zm1.25 1.171a.25.25 0 0 0-.312 0l-5.25 4.2a.25.25 0 0 0-.094.196v7.019c0 .138.112.25.25.25H5.5V8.25a.75.75 0 0 1 .75-.75h3.5a.75.75 0 0 1 .75.75v5.25h2.75a.25.25 0 0 0 .25-.25V6.23a.25.25 0 0 0-.094-.195Z"/></svg>';
function dashboardRow(current) {
const a = el("a", "gos-org gos-item");
a.href = "/";
const icon = el("span", "gos-icon");
icon.innerHTML = HOME_ICON;
a.append(icon, el("span", "gos-name", "Dashboard"));
if (current) a.append(el("span", "gos-tag", "current"));
return a;
}
function repoRow(repo, indent) {
const a = el("a", `gos-repo gos-item${indent ? " gos-indent" : ""}`);
a.href = repo.href;
a.title = repo.description || "";
a.append(el("span", "gos-name", repo.name));
if (repo.badge) a.append(el("span", "gos-badge", repo.badge));
return a;
}
// ---------------------------------------------------------------------------
// Pickers
// The personal dashboard and the per-org dashboards (/orgs/<org>/dashboard) share the
// same "Dashboard" crumb, so they all count as the dashboard.
function onDashboard() {
return /^\/(dashboard\/?)?$|^\/orgs\/[^/]+\/dashboard/.test(location.pathname);
}
function currentOwner() {
if (onDashboard()) return "";
return (location.pathname.split("/")[1] === "orgs" ? location.pathname.split("/")[2] : location.pathname.split("/")[1]) || "";
}
function openOrgPicker(btn) {
const here = currentOwner().toLowerCase();
const orgsPromise = getOrgs();
openPanel(btn, "Switch organization", "Filter orgs or search their repositories", async (query, list) => {
const orgs = await orgsPromise;
if (!orgs.length) {
list.append(el("div", "gos-note", "No organizations found. Add them in the extension options."));
return;
}
// Put the orgs you are not in first, since those are the switch targets.
const ordered = [...orgs].sort((a, b) => (a.toLowerCase() === here) - (b.toLowerCase() === here));
if (!query) {
list.append(dashboardRow(onDashboard()));
ordered.forEach((o) => list.append(orgRow(o, o.toLowerCase() === here)));
return;
}
const q = query.toLowerCase();
if ("dashboard".startsWith(q)) list.append(dashboardRow(onDashboard()));
const results = await Promise.all(ordered.map((o) => searchRepos(o, query)));
ordered.forEach((org, i) => {
const repos = results[i].slice(0, 5);
if (!repos.length && !org.toLowerCase().includes(q)) return;
list.append(orgRow(org, org.toLowerCase() === here));
repos.forEach((r) => list.append(repoRow(r, true)));
});
if (!list.childNodes.length) list.append(el("div", "gos-note", "No matches"));
});
}
function openRepoPicker(btn, org) {
const reposPromise = allRepos(org);
openPanel(btn, `Repositories in ${org}`, "Filter repositories", async (query, list) => {
let repos;
try {
repos = await reposPromise;
} catch {
list.append(el("div", "gos-note", "Could not load repositories."));
return;
}
const q = query.toLowerCase();
const matches = q
? repos
.filter((r) => r.name.toLowerCase().includes(q))
.sort((a, b) => b.name.toLowerCase().startsWith(q) - a.name.toLowerCase().startsWith(q))
: repos;
matches.forEach((r) => list.append(repoRow(r, false)));
list.append(el("div", "gos-note", q ? `${matches.length} of ${repos.length}` : `${repos.length} repositories, recently updated first`));
});
}
// ---------------------------------------------------------------------------
// Injection
function makeButton(id, title, html) {
const btn = el("button");
btn.id = id;
btn.type = "button";
btn.title = title;
btn.setAttribute("aria-haspopup", "true");
btn.setAttribute("aria-expanded", "false");
btn.innerHTML = html;
return btn;
}
function togglePanel(btn, open) {
return (e) => {
e.preventDefault();
e.stopPropagation();
if (btn.getAttribute("aria-expanded") === "true") closePanel();
else open(btn);
};
}
function inject() {
const nav = document.querySelector('nav[aria-label="Breadcrumbs"]');
const ownerLi = nav?.querySelector('li[data-index="0"]');
if (!ownerLi) return;
const href = ownerLi.querySelector("a")?.getAttribute("href") || "";
const isDashboard = href === "/" || href === `${location.origin}/`;
const org = href.slice(1);
if (!isDashboard && (!org || org.includes("/"))) return;
if (!ownerLi.querySelector(`#${ORG_BUTTON_ID}`)) {
const btn = makeButton(ORG_BUTTON_ID, "Switch organization", CARET);
btn.addEventListener("click", togglePanel(btn, openOrgPicker));
ownerLi.appendChild(btn);
}
// The dashboard has no owner, so it only gets the org switcher.
if (isDashboard) return;
// On org and profile pages the owner is the only crumb, so offer a repo picker after it.
// The meta tag can be stale after client-side navigation, so known orgs count too.
const isOrgPage =
!nav.querySelector('li[data-index="1"]') &&
(knownOrgs.has(org.toLowerCase()) ||
!!document.querySelector('meta[name="hovercard-subject-tag"][content^="organization:"]'));
const existing = nav.querySelector(`#${REPO_BUTTON_ID}`);
if (isOrgPage && !existing) {
// GitHub's CSS draws the "/" separator once the owner crumb is no longer last.
const li = el("li", "gos-repo-crumb");
const btn = makeButton(REPO_BUTTON_ID, "Switch repository", `<span>Repositories</span>${CARET}`);
btn.addEventListener("click", togglePanel(btn, (b) => openRepoPicker(b, org)));
li.append(btn);
ownerLi.after(li);
} else if (!isOrgPage && existing) {
existing.closest("li").remove();
}
}
let knownOrgs = new Set();
getOrgs().then((orgs) => {
knownOrgs = new Set(orgs.map((o) => o.toLowerCase()));
inject();
});
// GitHub swaps the header on client-side navigation, so re-inject when it changes.
inject();
new MutationObserver(() => {
inject();
if (!document.querySelector('nav[aria-label="Breadcrumbs"]')) closePanel();
}).observe(document.body, { childList: true, subtree: true });