forked from TheRealDuckers/hacktab
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
703 lines (615 loc) · 25.2 KB
/
app.js
File metadata and controls
703 lines (615 loc) · 25.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
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
// app.js
// Expose refresh functions globally so other scripts can call them
// Hackatime refresh
window.refreshHackatime = async function(username, apiKey) {
const BASE_V1 = 'https://hackatime.hackclub.com/api/v1';
const BASE_HACKATIME_V1 = 'https://hackatime.hackclub.com/api/hackatime/v1';
const summaryEl = document.getElementById('hackatimeSummary');
const table = document.getElementById('hackatimeTable');
const tbody = table ? table.querySelector('tbody') : null;
const projectsWrap = document.getElementById('hackatimeProjects');
const projectsList = document.getElementById('hackatimeProjectsList');
if (!summaryEl) return;
summaryEl.textContent = 'Loading Hackatime…';
if (tbody) tbody.innerHTML = '';
if (table) table.style.display = 'none';
if (projectsList) projectsList.innerHTML = '';
if (projectsWrap) projectsWrap.style.display = 'none';
try {
// Today’s status FIXED!????
const todayRes = await fetch(
`${BASE_V1}/users/current/statusbar/today?api_key=${encodeURIComponent(apiKey)}`
);
const todayJson = await todayRes.json();
const totalSeconds = todayJson?.data?.grand_total?.total_seconds || 0;
const hours = Math.floor(totalSeconds / 3600);
const minutes = Math.floor((totalSeconds % 3600) / 60);
const todayText = hours || minutes
? `${hours}h ${minutes}m`
: '';
summaryEl.textContent = todayText
? `Today: ${todayText}`
: 'No coding today';
// Stats
const statsRes = await fetch(`${BASE_V1}/users/${encodeURIComponent(username)}/stats?api_key=${encodeURIComponent(apiKey)}`);
const statsJson = await statsRes.json();
const totalSeconds = statsJson?.total_seconds || 0;
const totalHours = (totalSeconds / 3600).toFixed(2);
summaryEl.textContent += ` • Total: ${totalHours} hrs`;
// Languages
if (Array.isArray(statsJson?.languages) && tbody) {
tbody.innerHTML = '';
statsJson.languages.slice(0, 10).forEach(lang => {
const tr = document.createElement('tr');
tr.innerHTML = `<td>${lang.name}</td><td>${lang.text}</td>`;
tbody.appendChild(tr);
});
table.style.display = 'table';
}
// Projects
if (Array.isArray(statsJson?.projects) && projectsList) {
projectsList.innerHTML = '';
statsJson.projects.slice(0, 10).forEach(p => {
const li = document.createElement('li');
li.textContent = `${p.name} — ${p.text}`;
projectsList.appendChild(li);
});
projectsWrap.style.display = 'block';
}
} catch (err) {
console.error('Hackatime fetch error', err);
summaryEl.textContent = 'Error loading Hackatime, Do you have internet? You should get it, honestly, its really useful.';
}
};
// GitHub refresh
window.refreshGithub = async function(username) {
const githubSummary = document.getElementById('githubSummary');
const githubRepos = document.getElementById('githubRepos');
if (!githubSummary || !githubRepos) return;
githubSummary.textContent = 'Loading GitHub…';
githubRepos.innerHTML = '';
try {
const profileRes = await fetch(`https://api.github.com/users/${encodeURIComponent(username)}`);
const profile = await profileRes.json();
githubSummary.textContent = `${profile.login} • ${profile.public_repos} repos • ${profile.followers} followers`;
const reposRes = await fetch(`https://api.github.com/users/${encodeURIComponent(username)}/repos?per_page=100`);
const repos = await reposRes.json();
repos.sort((a, b) => b.stargazers_count - a.stargazers_count);
repos.slice(0, 8).forEach(r => {
const li = document.createElement('li');
li.innerHTML = `<a href="${r.html_url}" target="_blank">${r.name} (${r.stargazers_count}★)</a>`;
githubRepos.appendChild(li);
});
} catch (err) {
console.error('GitHub fetch error', err);
githubSummary.textContent = 'Error loading GitHub, Do you have internet?';
}
};
// Startup: load saved settings and shortcuts once DOM is ready
document.addEventListener('DOMContentLoaded', () => {
const settings = JSON.parse(localStorage.getItem('settings')) || {};
if (settings.hackatimeUsername && settings.hackatimeKey) {
window.refreshHackatime(settings.hackatimeUsername, settings.hackatimeKey);
}
if (settings.githubUsername) {
window.refreshGithub(settings.githubUsername);
}
});
document.addEventListener('DOMContentLoaded', () => {
const form = document.getElementById('searchForm');
const q = document.getElementById('q');
const engine = document.getElementById('engine');
form.addEventListener('submit', (e) => {
e.preventDefault();
const query = (q.value || '').trim();
if (!query) return;
const eVal = engine.value;
let url = '';
if (eVal === 'google') url = 'https://www.google.com/search?q=' + encodeURIComponent(query);
else if (eVal === 'duck') url = 'https://duckduckgo.com/?q=' + encodeURIComponent(query);
else if (eVal === 'bing') url = 'https://www.bing.com/search?q=' + encodeURIComponent(query);
else if (eVal === 'brave') url = 'https://search.brave.com/search?q=' + encodeURIComponent(query);
else if (eVal === 'perplexity') url = 'https://www.perplexity.ai/search/?q=' + encodeURIComponent(query);
else if (eVal === 'ecosia') url = 'https://www.ecosia.org/search?q=' + encodeURIComponent(query);
else if (eVal === 'wikipedia') url = 'https://en.wikipedia.org/w/index.php?search=' + encodeURIComponent(query);
else if (eVal === 'firefox') url = 'https://search.firefox.com/?q=' + encodeURIComponent(query);
else url = 'https://www.google.com/search?q=' + encodeURIComponent(query); // fallback
window.location.href = url;
});
// Terminal date
const dateLine = document.getElementById('dateLine');
const now = new Date();
dateLine.textContent = now.toString();
// Make window headers draggable cause why not
function makeDraggable(winId) {
const win = document.getElementById(winId);
const header = win.querySelector('.window-header');
let isDown = false, startX = 0, startY = 0, startLeft = 0, startTop = 0;
// this made it look better soooo.....
if (winId === 'win1') { win.style.transform = 'translate(0px, 0px)'; }
if (winId === 'win2') { win.style.transform = 'translate(0px, 0px)'; }
header.addEventListener('mousedown', (e) => {
isDown = true;
const rect = win.getBoundingClientRect();
startX = e.clientX;
startY = e.clientY;
startLeft = rect.left;
startTop = rect.top;
win.style.willChange = 'transform';
});
window.addEventListener('mousemove', (e) => {
if (!isDown) return;
const dx = e.clientX - startX;
const dy = e.clientY - startY;
win.style.transform = `translate(${dx}px, ${dy}px)`;
});
window.addEventListener('mouseup', () => {
isDown = false;
win.style.willChange = 'auto';
});
// Touch support
header.addEventListener('touchstart', (e) => {
const t = e.touches[0];
isDown = true;
const rect = win.getBoundingClientRect();
startX = t.clientX;
startY = t.clientY;
startLeft = rect.left;
startTop = rect.top;
win.style.willChange = 'transform';
}, { passive: true });
window.addEventListener('touchmove', (e) => {
if (!isDown) return;
const t = e.touches[0];
const dx = t.clientX - startX;
const dy = t.clientY - startY;
win.style.transform = `translate(${dx}px, ${dy}px)`;
}, { passive: true });
window.addEventListener('touchend', () => {
isDown = false;
win.style.willChange = 'auto';
});
}
makeDraggable('win1');
makeDraggable('win2');
});
document.addEventListener('DOMContentLoaded', () => {
const settingsBtn = document.getElementById('settingsBtn');
const settingsPopup = document.getElementById('settingsPopup');
const closeSettings = document.getElementById('closeSettings');
const darkModeToggle = document.getElementById('darkModeToggle');
const showShortcutsToggle = document.getElementById('showShortcutsToggle');
const animatedBgToggle = document.getElementById('animatedBgToggle');
const nameInput = document.getElementById('nameInput');
const saveNameBtn = document.getElementById('saveNameBtn');
const hackatimeUsernameInput = document.getElementById('hackatimeUsername');
const hackatimeKeyInput = document.getElementById('hackatimeKey');
const saveHackatimeBtn = document.getElementById('saveHackatimeBtn');
const githubUsernameInput = document.getElementById('githubUsername');
const saveGithubBtn = document.getElementById('saveGithubBtn');
let shortcuts = getShortcuts();
const shortcutNameInput = document.getElementById("shortcutName");
const shortcutURLInput = document.getElementById("shortcutURL");
const saveShortcutBtn = document.getElementById("saveShortcutButton");
const clearShortcutsBtn = document.getElementById("clearCustomShortcuts");
const shortcutListElement = document.getElementById("shortcutList");
function getSettings() {
return JSON.parse(localStorage.getItem('settings')) || {};
}
function getShortcuts() {
return JSON.parse(localStorage.getItem("customShortcuts")) || [];
}
function saveSettings(settings) {
localStorage.setItem('settings', JSON.stringify(settings));
applySettings(settings);
}
function saveShortcuts() {
localStorage.setItem("customShortcuts", JSON.stringify(shortcuts));
renderShortcuts(shortcuts);
}
function clearShortcuts() {
shortcuts = [];
saveShortcuts();
}
function applySettings(settings) {
document.body.classList.toggle('dark', !!settings.darkMode);
const win2 = document.getElementById('win2');
if (win2) win2.style.display = settings.showShortcuts === false ? 'none' : '';
const matrix = document.querySelector('.matrix');
if (matrix) matrix.style.display = settings.animatedBg === false ? 'none' : '';
}
function loadSettingsToUI() {
const s = getSettings();
if (!s || Object.keys(s).length === 0) return;
if (darkModeToggle) darkModeToggle.checked = !!s.darkMode;
if (showShortcutsToggle) showShortcutsToggle.checked = s.showShortcuts !== false;
if (animatedBgToggle) animatedBgToggle.checked = s.animatedBg !== false;
if (nameInput) nameInput.value = s.name || '';
if (hackatimeUsernameInput) hackatimeUsernameInput.value = s.hackatimeUsername || '';
if (hackatimeKeyInput) hackatimeKeyInput.value = s.hackatimeKey || '';
if (githubUsernameInput) githubUsernameInput.value = s.githubUsername || '';
applySettings(s);
}
function addShortcut(name, url) {
shortcuts.push({"name": name, "URL": url});
saveShortcuts();
renderShortcuts();
}
function renderShortcuts() {
shortcutListElement.innerHTML = '';
let defaultShortcuts = [
{
"name": "Hack Club",
"URL": "https://hackclub.com"
},
{
"name": "Hack Club Slack",
"URL": "https://hackclub.slack.com"
},
{
"name": "GitHub",
"URL": "https://github.com"
},
{
"name": "Hacker News",
"URL": "https://news.ycombinator.com"
}
];
const customShortcuts = getShortcuts();
defaultShortcuts.concat(customShortcuts).forEach((shortcut) => {
let listElement = document.createElement("li");
let nextAccent = "";
switch (shortcutListElement.childElementCount % 3) {
case 0:
nextAccent = "accent";
break;
case 1:
nextAccent = "accent-2";
break;
case 2:
nextAccent = "accent-3";
break;
}
listElement.innerHTML = `<a href="${shortcut["URL"]}" style="color: var(--${nextAccent}); text-decoration: none;">${shortcut["name"]}</a>`;
shortcutListElement.appendChild(listElement);
})
}
function updateAndSaveFromUI() {
const current = getSettings();
const updated = {
...current,
darkMode: !!darkModeToggle.checked,
showShortcuts: !!showShortcutsToggle.checked,
animatedBg: !!animatedBgToggle.checked,
name: nameInput.value.trim(),
hackatimeUsername: hackatimeUsernameInput.value.trim(),
hackatimeKey: hackatimeKeyInput.value.trim(),
githubUsername: githubUsernameInput.value.trim()
};
saveSettings(updated);
return updated;
}
console.log("checkpoint 1");
settingsBtn?.addEventListener('click', () => {
if (settingsPopup) settingsPopup.style.display = 'block';
});
closeSettings?.addEventListener('click', () => {
if (settingsPopup) settingsPopup.style.display = 'none';
});
darkModeToggle?.addEventListener('change', () => {
updateAndSaveFromUI();
});
showShortcutsToggle?.addEventListener('change', () => {
updateAndSaveFromUI();
});
animatedBgToggle?.addEventListener('change', () => {
updateAndSaveFromUI();
});
saveNameBtn?.addEventListener('click', () => {
const s = updateAndSaveFromUI();
// inject greeting if terminal exists
const term = document.getElementById('term1');
if (term && s.name) {
const oldG = term.querySelector('.greetingLine');
if (oldG) oldG.remove();
const oldO = term.querySelector('.greetingOutput');
if (oldO) oldO.remove();
const greetingLine = document.createElement('span');
greetingLine.className = 'line greetingLine';
greetingLine.textContent = `$ echo "Hello, ${s.name}!"`;
term.appendChild(greetingLine);
const outputLine = document.createElement('span');
outputLine.className = 'line greetingOutput';
outputLine.textContent = `Hello, ${s.name}!`;
term.appendChild(outputLine);
}
alert(`Name saved as "${s.name}"`);
});
saveShortcutBtn.addEventListener('click', (e) => {
console.log("Correct button pressed.");
e.preventDefault();
const name = shortcutNameInput.value.trim();
const url = shortcutURLInput.value.trim();
if (!name || !url) return;
try {
new URL(url);
} catch (_) {
console.error("invalid URL");
alert("Invalid URL. Please remember to include the protocol (http:// or https://).");
return;
}
addShortcut(name, url);
shortcutNameInput.value = '';
shortcutURLInput.value = '';
alert(`Shortcut "${name}" added!`);
})
clearShortcutsBtn.addEventListener('click', () => { clearShortcuts() });
saveHackatimeBtn?.addEventListener('click', () => {
const s = updateAndSaveFromUI();
alert('Hackatime settings saved.');
// optional: trigger a refresh if your hackatime functions exist
if (typeof refreshHackatime === 'function' && s.hackatimeUsername && s.hackatimeKey) {
refreshHackatime(s.hackatimeUsername, s.hackatimeKey);
}
});
saveGithubBtn?.addEventListener('click', () => {
const s = updateAndSaveFromUI();
alert('GitHub username saved.');
if (typeof refreshGithub === 'function' && s.githubUsername) {
refreshGithub(s.githubUsername);
}
});
// keyboard: close settings on Escape
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && settingsPopup && settingsPopup.style.display === 'block') {
settingsPopup.style.display = 'none';
}
});
renderShortcuts();
loadSettingsToUI();
});
document.addEventListener('DOMContentLoaded', () => {
const BASE_V1 = 'https://hackatime.hackclub.com/api/v1';
const BASE_HACKATIME_V1 = 'https://hackatime.hackclub.com/api/hackatime/v1';
// Settings inputs
const usernameInput = document.getElementById('hackatimeUsername');
const keyInput = document.getElementById('hackatimeKey');
const saveHackatimeBtn = document.getElementById('saveHackatimeBtn');
const githubInput = document.getElementById('githubUsername');
const saveGithubBtn = document.getElementById('saveGithubBtn');
// Hackatime UI
const summaryEl = document.getElementById('hackatimeSummary');
const table = document.getElementById('hackatimeTable');
const tbody = table.querySelector('tbody');
const projectsWrap = document.getElementById('hackatimeProjects');
const projectsList = document.getElementById('hackatimeProjectsList');
// GitHub UI
const githubSummary = document.getElementById('githubSummary');
const githubRepos = document.getElementById('githubRepos');
function loadSettings() {
const s = JSON.parse(localStorage.getItem('settings')) || {};
usernameInput.value = s.hackatimeUsername || '';
keyInput.value = s.hackatimeKey || '';
githubInput.value = s.githubUsername || '';
if (s.hackatimeUsername && s.hackatimeKey) {
refreshHackatime(s.hackatimeUsername, s.hackatimeKey);
} else {
summaryEl.textContent = '';
table.style.display = 'none';
projectsWrap.style.display = 'none';
}
if (s.githubUsername) {
refreshGithub(s.githubUsername);
} else {
githubSummary.textContent = '';
githubRepos.innerHTML = '';
}
}
function saveSettings() {
const settings = JSON.parse(localStorage.getItem('settings')) || {};
settings.hackatimeUsername = usernameInput.value.trim();
settings.hackatimeKey = keyInput.value.trim();
settings.githubUsername = githubInput.value.trim();
localStorage.setItem('settings', JSON.stringify(settings));
return settings;
}
saveHackatimeBtn.addEventListener('click', () => {
const s = saveSettings();
if (s.hackatimeUsername && s.hackatimeKey) refreshHackatime(s.hackatimeUsername, s.hackatimeKey);
else {
summaryEl.textContent = 'Please enter both Hackatime username and API key.';
table.style.display = 'none';
projectsWrap.style.display = 'none';
}
});
saveGithubBtn.addEventListener('click', () => {
const s = saveSettings();
if (s.githubUsername) refreshGithub(s.githubUsername);
else {
githubSummary.textContent = 'Enter a GitHub username to load repos.';
githubRepos.innerHTML = '';
}
});
// --- Hackatime functions ---
async function refreshHackatime(username, apiKey) {
// reset UI
summaryEl.textContent = '';
summaryEl.dataset.loading = 'true';
summaryEl.textContent = 'Loading Hackatime...';
tbody.innerHTML = '';
table.style.display = 'none';
projectsList.innerHTML = '';
projectsWrap.style.display = 'none';
// fetch today and stats in parallel
const p1 = fetchTodayStatus(apiKey);
const p2 = fetchUserStats(username, apiKey);
const p3 = fetchUserProjects(username, apiKey);
await Promise.allSettled([p1, p2, p3]);
// remove loading marker
if (summaryEl.dataset.loading === 'true') {
delete summaryEl.dataset.loading;
if (summaryEl.textContent === 'Loading Hackatime...') summaryEl.textContent = '';
}
}
async function fetchTodayStatus(apiKey) {
try {
const url = `${BASE_HACKATIME_V1}/users/current/statusbar/today?api_key=${encodeURIComponent(apiKey)}`;
const res = await fetch(url);
if (!res.ok) {
console.warn('Today status fetch failed', res.status);
return;
}
const json = await res.json();
const text = json?.data?.grand_total?.text || null;
const seconds = json?.data?.grand_total?.total_seconds || 0;
const todayLine = text ? `Today: ${text}` : `Today: ${(seconds / 3600).toFixed(2)} hrs`;
// show only today's time (replace previous today line if present)
// If totals already present, keep them and prepend today
const prev = summaryEl.textContent || '';
// Remove any previous "Today:" prefix to avoid duplicates
const cleaned = prev.replace(/^Today:[^•]*•\s?/, '');
summaryEl.textContent = cleaned ? `${todayLine} • ${cleaned}` : todayLine;
} catch (err) {
console.error('fetchTodayStatus error', err);
}
}
async function fetchUserStats(username, apiKey) {
try {
const url = `${BASE_V1}/users/${encodeURIComponent(username)}/stats?api_key=${encodeURIComponent(apiKey)}`;
const res = await fetch(url);
if (!res.ok) {
console.error('User stats fetch failed', res.status);
summaryEl.textContent = 'Unable to load user stats.';
return;
}
const data = await res.json();
// totals
const totalSeconds = data?.total_seconds || 0;
const totalHours = (totalSeconds / 3600).toFixed(2);
const totalsLine = `Total: ${totalHours} hrs`;
const prev = summaryEl.textContent || '';
// Avoid duplicating totals
const cleanedPrev = prev.replace(/Total:[^•]*•\s?/, '');
summaryEl.textContent = cleanedPrev ? `${cleanedPrev} • ${totalsLine}` : totalsLine;
// languages
renderLanguages(data?.languages || []);
// if projects included in stats payload, render them
if (Array.isArray(data?.projects) && data.projects.length) renderProjects(data.projects);
} catch (err) {
console.error('fetchUserStats error', err);
summaryEl.textContent = 'Error fetching user stats.';
}
}
async function fetchUserProjects(username, apiKey) {
try {
const url = `${BASE_V1}/users/${encodeURIComponent(username)}/projects?api_key=${encodeURIComponent(apiKey)}`;
const res = await fetch(url);
if (!res.ok) {
console.warn('Projects fetch failed', res.status);
return;
}
const data = await res.json();
const projects = Array.isArray(data) ? data : data?.projects || [];
if (projects.length) renderProjects(projects);
} catch (err) {
console.error('fetchUserProjects error', err);
}
}
function renderLanguages(languages) {
if (!Array.isArray(languages) || languages.length === 0) return;
const headerRow = table.querySelector('thead tr');
headerRow.innerHTML = `
<th style="padding:6px; border:1px solid #12202a;">Language</th>
<th style="padding:6px; border:1px solid #12202a;">Time</th>
`;
tbody.innerHTML = '';
languages.slice(0, 10).forEach(lang => {
const tr = document.createElement('tr');
const nameCell = document.createElement('td');
const timeCell = document.createElement('td');
nameCell.textContent = lang.name || '';
timeCell.textContent = lang.text || formatSeconds(lang.seconds);
nameCell.style.padding = '6px';
nameCell.style.border = '1px solid #12202a';
timeCell.style.padding = '6px';
timeCell.style.border = '1px solid #12202a';
tr.appendChild(nameCell);
tr.appendChild(timeCell);
tbody.appendChild(tr);
});
table.style.display = 'table';
}
function renderProjects(projects) {
if (!Array.isArray(projects) || projects.length === 0) return;
projectsList.innerHTML = '';
projects.slice(0, 10).forEach(p => {
const li = document.createElement('li');
li.style.padding = '6px 0';
li.style.borderBottom = '1px dashed rgba(255,255,255,0.03)';
const name = p.name || p.repo || p.title || 'Unnamed';
const timeText = p.text || formatSeconds(p.seconds) || '';
li.textContent = `${name}${timeText ? ' — ' + timeText : ''}`;
projectsList.appendChild(li);
});
projectsWrap.style.display = 'block';
}
function formatSeconds(sec) {
if (typeof sec !== 'number' || !isFinite(sec) || sec <= 0) return '';
const h = Math.floor(sec / 3600);
const m = Math.floor((sec % 3600) / 60);
const parts = [];
if (h) parts.push(`${h}h`);
if (m) parts.push(`${m}m`);
return parts.join(' ');
}
// --- GitHub integration ---
async function refreshGithub(githubUsername) {
githubSummary.textContent = 'Loading GitHub...';
githubRepos.innerHTML = '';
try {
// Basic profile
const profileRes = await fetch(`https://api.github.com/users/${encodeURIComponent(githubUsername)}`);
if (!profileRes.ok) {
githubSummary.textContent = 'GitHub user not found.';
return;
}
const profile = await profileRes.json();
githubSummary.textContent = `${profile.login} • ${profile.public_repos} repos • ${profile.followers} followers`;
// Top repos (by stargazers, fetch first page then sort)
const reposRes = await fetch(`https://api.github.com/users/${encodeURIComponent(githubUsername)}/repos?per_page=100`);
if (!reposRes.ok) {
githubRepos.innerHTML = '<li>Unable to load repos.</li>';
return;
}
const repos = await reposRes.json();
// sort by stargazers_count desc then updated_at
repos.sort((a, b) => (b.stargazers_count - a.stargazers_count) || (new Date(b.updated_at) - new Date(a.updated_at)));
githubRepos.innerHTML = '';
repos.slice(0, 8).forEach(r => {
const li = document.createElement('li');
li.style.padding = '6px 0';
li.style.borderBottom = '1px dashed rgba(255,255,255,0.03)';
const a = document.createElement('a');
a.href = r.html_url;
a.target = '_blank';
a.rel = 'noopener noreferrer';
a.style.color = '#cbd5e1';
a.textContent = `${r.name} (${r.stargazers_count}★)`;
li.appendChild(a);
if (r.description) {
const desc = document.createElement('div');
desc.style.fontSize = '12px';
desc.style.color = '#9fb3c8';
desc.textContent = r.description;
li.appendChild(desc);
}
githubRepos.appendChild(li);
});
} catch (err) {
console.error('refreshGithub error', err);
githubSummary.textContent = 'Error loading GitHub.';
}
}
// Initialize
loadSettings();
});