Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
347 lines (307 loc) · 12.5 KB
/
Copy pathapp.js
File metadata and controls
347 lines (307 loc) · 12.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
const loadButton = document.getElementById("load-btn");
const usernameInput = document.getElementById("username");
const themeToggle = document.getElementById("theme-toggle");
const profileCard = document.getElementById("profile");
const statusEl = document.getElementById("status");
const avatarEl = document.getElementById("avatar");
const nameEl = document.getElementById("name");
const bioEl = document.getElementById("bio");
const followersEl = document.getElementById("followers");
const followingEl = document.getElementById("following");
const reposEl = document.getElementById("public-repos");
const statMap = {
stars: document.querySelector("#stat-stars .stat-value"),
forks: document.querySelector("#stat-forks .stat-value"),
watchers: document.querySelector("#stat-watchers .stat-value"),
issues: document.querySelector("#stat-issues .stat-value"),
openPrs: document.querySelector("#stat-open-prs .stat-value"),
totalIssues: document.querySelector("#stat-total-issues .stat-value"),
totalPrs: document.querySelector("#stat-total-prs .stat-value"),
size: document.querySelector("#stat-size .stat-value"),
age: document.querySelector("#stat-age .stat-value"),
};
const topReposList = document.getElementById("top-repos");
const languagesList = document.getElementById("languages");
const eventsList = document.getElementById("events");
const activeReposList = document.getElementById("active-repos");
const timelineList = document.getElementById("repo-timeline");
const topicsList = document.getElementById("topics");
const streakList = document.getElementById("streak");
const prIssueList = document.getElementById("pr-issue-counts");
const apiBase = "https://api.github.com";
function setStatus(text) {
statusEl.textContent = text;
}
function animateNumber(element, value) {
const current = parseInt(element.dataset.count || "0", 10);
element.dataset.count = value;
gsap.fromTo(
{ val: current },
{ val: value },
{
duration: 0.8,
ease: "power2.out",
onUpdate: function () {
element.textContent = Math.round(this.targets()[0].val).toString();
},
}
);
}
function renderList(listEl, items) {
listEl.innerHTML = "";
if (!items.length) {
listEl.innerHTML = "<li>No data</li>";
return;
}
items.forEach((item) => {
const li = document.createElement("li");
li.innerHTML = item;
listEl.appendChild(li);
});
}
function formatNumber(value) {
return value.toLocaleString("en-US");
}
async function fetchJson(url) {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Request failed: ${response.status}`);
}
return response.json();
}
async function fetchJsonWithHeaders(url, headers = {}) {
const response = await fetch(url, { headers });
if (!response.ok) {
throw new Error(`Request failed: ${response.status}`);
}
return response.json();
}
function daysBetween(dateString) {
const ms = Date.now() - new Date(dateString).getTime();
return Math.max(0, Math.floor(ms / (1000 * 60 * 60 * 24)));
}
function formatDate(dateString) {
const date = new Date(dateString);
return date.toLocaleDateString("en-US", { year: "numeric", month: "short", day: "numeric" });
}
async function loadAnalytics() {
const username = usernameInput.value.trim();
if (!username) {
setStatus("Enter a GitHub username.");
return;
}
setStatus("Loading public analytics...");
profileCard.classList.add("hidden");
try {
const user = await fetchJson(`${apiBase}/users/${username}`);
const repos = await fetchJson(`${apiBase}/users/${username}/repos?per_page=100&type=public&sort=updated`);
const events = await fetchJson(`${apiBase}/users/${username}/events/public?per_page=100`);
avatarEl.src = user.avatar_url;
nameEl.textContent = user.name || user.login;
bioEl.textContent = user.bio || "No bio available.";
followersEl.textContent = `${formatNumber(user.followers)} followers`;
followingEl.textContent = `${formatNumber(user.following)} following`;
reposEl.textContent = `${formatNumber(user.public_repos)} repos`;
profileCard.classList.remove("hidden");
const totals = repos.reduce(
(acc, repo) => {
acc.stars += repo.stargazers_count;
acc.forks += repo.forks_count;
acc.watchers += repo.watchers_count;
acc.issues += repo.open_issues_count;
acc.size += repo.size || 0;
acc.ages.push(daysBetween(repo.created_at));
if (repo.language) {
acc.languages[repo.language] = (acc.languages[repo.language] || 0) + 1;
}
acc.pushedAt.push({ name: repo.name, pushed_at: repo.pushed_at });
acc.createdAt.push({ name: repo.name, created_at: repo.created_at });
return acc;
},
{
stars: 0,
forks: 0,
watchers: 0,
issues: 0,
size: 0,
ages: [],
languages: {},
pushedAt: [],
createdAt: [],
}
);
animateNumber(statMap.stars, totals.stars);
animateNumber(statMap.forks, totals.forks);
animateNumber(statMap.watchers, totals.watchers);
animateNumber(statMap.issues, totals.issues);
animateNumber(statMap.size, Math.round(totals.size / 1024));
const avgAge = totals.ages.length
? Math.round(totals.ages.reduce((sum, value) => sum + value, 0) / totals.ages.length)
: 0;
animateNumber(statMap.age, avgAge);
const topRepos = [...repos]
.sort((a, b) => b.stargazers_count - a.stargazers_count)
.slice(0, 5)
.map((repo) => `<span>${repo.name}</span><span>★ ${repo.stargazers_count}</span>`);
renderList(topReposList, topRepos);
const languageItems = Object.entries(totals.languages)
.sort((a, b) => b[1] - a[1])
.slice(0, 8)
.map(([lang, count]) => `<span>${lang}</span><span>${count} repos</span>`);
renderList(languagesList, languageItems);
const eventItems = events.map((event) => {
const repoName = event.repo ? event.repo.name : "Unknown repo";
return `<span>${event.type.replace("Event", "")}</span><span>${repoName}</span>`;
});
renderList(eventsList, eventItems);
const activeRepos = [...totals.pushedAt]
.filter((repo) => repo.pushed_at)
.sort((a, b) => new Date(b.pushed_at) - new Date(a.pushed_at))
.slice(0, 6)
.map((repo) => `<span>${repo.name}</span><span>${formatDate(repo.pushed_at)}</span>`);
renderList(activeReposList, activeRepos);
const timelineItems = [...totals.createdAt]
.filter((repo) => repo.created_at)
.sort((a, b) => new Date(a.created_at) - new Date(b.created_at));
const oldest = timelineItems[0];
const newest = timelineItems[timelineItems.length - 1];
const timelineListItems = [];
if (oldest) {
timelineListItems.push(`<span>Oldest repo</span><span>${oldest.name}</span>`);
timelineListItems.push(`<span>Created</span><span>${formatDate(oldest.created_at)}</span>`);
}
if (newest) {
timelineListItems.push(`<span>Newest repo</span><span>${newest.name}</span>`);
timelineListItems.push(`<span>Created</span><span>${formatDate(newest.created_at)}</span>`);
}
renderList(timelineList, timelineListItems);
const topTopicRepos = [...repos]
.sort((a, b) => b.stargazers_count - a.stargazers_count)
.slice(0, 8);
const topicsCounter = {};
for (const repo of topTopicRepos) {
try {
const repoDetails = await fetchJsonWithHeaders(
`${apiBase}/repos/${username}/${repo.name}`,
{ Accept: "application/vnd.github+json" }
);
if (Array.isArray(repoDetails.topics)) {
repoDetails.topics.forEach((topic) => {
topicsCounter[topic] = (topicsCounter[topic] || 0) + 1;
});
}
} catch (error) {
console.warn("Topic fetch failed", error);
}
}
const topicItems = Object.entries(topicsCounter)
.sort((a, b) => b[1] - a[1])
.slice(0, 8)
.map(([topic, count]) => `<span>${topic}</span><span>${count}</span>`);
renderList(topicsList, topicItems);
const streakInfo = buildStreak(events);
const streakItems = [
`<span>Current streak</span><span>${streakInfo.current} days</span>`,
`<span>Longest streak (30d)</span><span>${streakInfo.longest} days</span>`,
`<span>Event days (30d)</span><span>${streakInfo.activeDays}</span>`,
];
renderList(streakList, streakItems);
const issuePrCounts = await fetchIssuePrCounts(username);
animateNumber(statMap.totalIssues, issuePrCounts.totalIssues);
animateNumber(statMap.openPrs, issuePrCounts.openPrs);
animateNumber(statMap.totalPrs, issuePrCounts.totalPrs);
const prIssueItems = [
`<span>Total issues</span><span>${formatNumber(issuePrCounts.totalIssues)}</span>`,
`<span>Open issues</span><span>${formatNumber(issuePrCounts.openIssues)}</span>`,
`<span>Total PRs</span><span>${formatNumber(issuePrCounts.totalPrs)}</span>`,
`<span>Open PRs</span><span>${formatNumber(issuePrCounts.openPrs)}</span>`,
];
renderList(prIssueList, prIssueItems);
gsap.from(".stat-card, .panel, .profile-card", {
opacity: 0,
y: 20,
duration: 0.6,
stagger: 0.05,
ease: "power2.out",
});
setStatus("Loaded.");
} catch (error) {
setStatus("Unable to load analytics. Check username or try again.");
console.error(error);
}
}
function buildStreak(events) {
const dayMap = {};
const now = new Date();
const cutoff = new Date();
cutoff.setDate(now.getDate() - 30);
events.forEach((event) => {
const date = new Date(event.created_at);
if (date < cutoff) return;
const key = date.toISOString().slice(0, 10);
dayMap[key] = true;
});
const days = Object.keys(dayMap).sort();
let longest = 0;
let current = 0;
let activeDays = days.length;
let streak = 0;
let last = null;
days.forEach((day) => {
if (!last) {
streak = 1;
} else {
const prev = new Date(last);
const currentDate = new Date(day);
const diff = (currentDate - prev) / (1000 * 60 * 60 * 24);
streak = diff === 1 ? streak + 1 : 1;
}
longest = Math.max(longest, streak);
last = day;
});
const todayKey = now.toISOString().slice(0, 10);
if (dayMap[todayKey]) {
current = 1;
for (let i = 1; i < 31; i++) {
const back = new Date(now);
back.setDate(now.getDate() - i);
const key = back.toISOString().slice(0, 10);
if (dayMap[key]) {
current += 1;
} else {
break;
}
}
}
return { current, longest, activeDays };
}
async function fetchIssuePrCounts(username) {
const totalIssues = await fetchJson(
`${apiBase}/search/issues?q=author:${username}+type:issue`
);
const openIssues = await fetchJson(
`${apiBase}/search/issues?q=author:${username}+type:issue+state:open`
);
const totalPrs = await fetchJson(
`${apiBase}/search/issues?q=author:${username}+type:pr`
);
const openPrs = await fetchJson(
`${apiBase}/search/issues?q=author:${username}+type:pr+state:open`
);
return {
totalIssues: totalIssues.total_count || 0,
openIssues: openIssues.total_count || 0,
totalPrs: totalPrs.total_count || 0,
openPrs: openPrs.total_count || 0,
};
}
themeToggle.addEventListener("click", () => {
document.body.classList.toggle("theme-light");
document.body.classList.toggle("theme-dark");
});
loadButton.addEventListener("click", loadAnalytics);
usernameInput.addEventListener("keydown", (event) => {
if (event.key === "Enter") {
loadAnalytics();
}
});