-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
400 lines (346 loc) · 16.4 KB
/
Copy pathscript.js
File metadata and controls
400 lines (346 loc) · 16.4 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
document.addEventListener('DOMContentLoaded', () => {
const feedContainer = document.querySelector('.gittok-feed');
const progressEl = document.querySelector('.scroll-progress');
const timeRangeButtons = document.querySelectorAll('.time-range-btn');
const baseApiUrl = '/api/trending';
let currentSince = 'daily';
let summaryObserver = null; // lazy AI summaries
let positionObserver = null; // tracks the current card (progress + keyboard nav)
let currentIndex = 0;
let itemCount = 0;
let inFlightController = null; // AbortController for the trending fetch
const trendingCache = new Map(); // since -> repos[]
// Inline monochrome icons (inherit the button color via currentColor)
const SHARE_ICON = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><line x1="8.59" y1="13.51" x2="15.42" y2="17.49"/><line x1="15.41" y1="6.51" x2="8.59" y2="10.49"/></svg>';
const CHECK_ICON = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="20 6 9 17 4 12"/></svg>';
// ============================================================
// Helpers
// ============================================================
// HTML-escape all interpolated text (data is scraped from GitHub, so
// descriptions can contain arbitrary characters).
function esc(str) {
return String(str ?? '')
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
// Only accept a fully-validated CSS color before injecting it into a style
// attribute (prevents any breakout via languageColor).
function isSafeColor(c) {
if (typeof c !== 'string') return false;
const s = c.trim();
return /^#[0-9a-fA-F]{3,8}$/.test(s) ||
/^rgba?\([\d\s.,%]+\)$/.test(s) ||
/^hsla?\([\d\s.,%]+\)$/.test(s);
}
// 12345 -> "12.3k", 1200000 -> "1.2M"
function formatCount(n) {
const num = Number(n);
if (!isFinite(num)) return '0';
if (num >= 1e6) return (num / 1e6).toFixed(1).replace(/\.0$/, '') + 'M';
if (num >= 1e3) return (num / 1e3).toFixed(1).replace(/\.0$/, '') + 'k';
return String(num);
}
// ============================================================
// Card rendering (template literal + one innerHTML)
// ============================================================
function repoCardHtml(repo) {
const avatarUrl = `${repo.avatar}?s=600`;
const bg = `background-image:url('${esc(avatarUrl)}')`;
const langDot = isSafeColor(repo.languageColor)
? `<span class="lang-dot" style="background-color:${repo.languageColor}"></span>`
: '';
const langPart = repo.language ? `语言: ${langDot}${esc(repo.language)} | ` : '';
const stats = `${langPart}⭐ ${formatCount(repo.stars)} | Forks: ${formatCount(repo.forks)}`;
return `
<div class="blurred-background" style="${bg}"></div>
<a class="content-image" style="${bg}"
href="${esc(repo.url)}" target="_blank" rel="noopener noreferrer"
title="点击查看 ${esc(repo.name)} 项目"
aria-label="打开 ${esc(repo.name)} 的 GitHub 仓库"></a>
<div class="info-left">
<h2>${esc(repo.name)}</h2>
<p class="info-author">作者: ${esc(repo.author)}</p>
<p class="info-stats">${stats}</p>
<div class="today-info-container">
<span class="today-stars">今日 Star: ${formatCount(repo.currentPeriodStars)}</span>
<button type="button" class="deepwiki-btn" data-action="deepwiki" title="在 DeepWiki 中打开">
<img src="deepwiki.png" alt=""> DeepWiki
</button>
<button type="button" class="zread-btn" data-action="zread" title="在 Zread 中打开">
<img src="zread.png" alt=""> Zread
</button>
</div>
</div>
<div class="info-right">
<p class="repo-description">${esc(repo.description) || '暂无描述'}</p>
<div class="ai-summary"><p><i>AI 总结加载中...</i></p></div>
</div>
<button type="button" class="share-button" data-action="share"
title="分享 GitTok 项目" aria-label="分享 GitTok">${SHARE_ICON}</button>
`;
}
function createRepoElement(repo) {
const item = document.createElement('div');
item.className = 'gittok-item';
item.dataset.author = repo.author;
item.dataset.repo = repo.name;
item.dataset.url = repo.url;
item.innerHTML = repoCardHtml(repo);
return item;
}
// ============================================================
// Feed states: skeleton / repos / empty / error
// ============================================================
function showSkeleton() {
teardownObservers();
updateProgress(0, 0);
feedContainer.innerHTML = `
<div class="gittok-item skeleton">
<div class="skeleton-box skeleton-image"></div>
<div class="skeleton-lines">
<div class="skeleton-line medium"></div>
<div class="skeleton-line short"></div>
<div class="skeleton-line medium"></div>
</div>
</div>`;
}
function showError(error) {
teardownObservers();
updateProgress(0, 0);
feedContainer.innerHTML = `
<div class="gittok-item error-message">
<div style="text-align:center;padding:0 20px;">
<p>加载 GitHub Trending 数据失败:${esc(error.message)}</p>
<p>请检查网络连接或 API 状态。</p>
<button type="button" class="time-range-btn active" data-retry="1" style="margin-top:12px;">重试</button>
</div>
</div>`;
}
function renderRepos(repos) {
teardownObservers();
feedContainer.innerHTML = '';
if (!repos || repos.length === 0) {
feedContainer.innerHTML = '<div class="gittok-item"><p>未能加载 Trending 项目,或者今天没有项目。</p></div>';
updateProgress(0, 0);
return;
}
const frag = document.createDocumentFragment();
repos.forEach((repo, i) => {
const el = createRepoElement(repo);
el.dataset.index = i;
frag.appendChild(el);
});
feedContainer.appendChild(frag);
itemCount = repos.length;
currentIndex = 0;
setupObservers();
updateProgress(1, itemCount);
}
// ============================================================
// Data fetching (client cache + cancel in-flight)
// ============================================================
async function fetchTrendingRepos(since = 'daily') {
// Cancel any in-flight request so a stale response can't overwrite the new view.
if (inFlightController) {
inFlightController.abort();
inFlightController = null;
}
// Cache hit -> render instantly.
if (trendingCache.has(since)) {
renderRepos(trendingCache.get(since));
return;
}
const controller = new AbortController();
inFlightController = controller;
const { signal } = controller;
showSkeleton();
try {
const response = await fetch(`${baseApiUrl}?since=${since}`, { signal });
if (!response.ok) throw new Error(`HTTP 错误! 状态: ${response.status}`);
const repos = await response.json();
if (signal.aborted) return; // superseded by a newer request
trendingCache.set(since, repos);
renderRepos(repos);
} catch (error) {
if (error.name === 'AbortError') return; // intentionally cancelled
console.error('获取 GitHub Trending 数据时出错:', error);
showError(error);
} finally {
if (inFlightController === controller) inFlightController = null;
}
}
// ============================================================
// Observers: lazy summaries + current-card tracking
// ============================================================
function setupObservers() {
summaryObserver = new IntersectionObserver(handleSummaryIntersect, {
root: feedContainer,
rootMargin: '0px 0px 200px 0px', // start loading ~200px before the card enters
threshold: 0.01
});
positionObserver = new IntersectionObserver(handlePositionIntersect, {
root: feedContainer,
threshold: 0.6 // the card that occupies most of the viewport
});
feedContainer.querySelectorAll('.gittok-item').forEach(item => {
summaryObserver.observe(item);
positionObserver.observe(item);
});
}
function teardownObservers() {
if (summaryObserver) { summaryObserver.disconnect(); summaryObserver = null; }
if (positionObserver) { positionObserver.disconnect(); positionObserver = null; }
}
function handlePositionIntersect(entries) {
entries.forEach(entry => {
if (entry.isIntersecting) {
currentIndex = Number(entry.target.dataset.index) || 0;
updateProgress(currentIndex + 1, itemCount);
}
});
}
function handleSummaryIntersect(entries, observer) {
entries.forEach(entry => {
if (!entry.isIntersecting) return;
const item = entry.target;
if (item.classList.contains('summary-loading') || item.classList.contains('summary-loaded')) return;
const { author, repo } = item.dataset;
if (author && repo) {
item.classList.add('summary-loading');
fetchAndDisplaySummary(item, author, repo);
}
observer.unobserve(item);
});
}
async function fetchAndDisplaySummary(itemElement, author, repo) {
const summaryPlaceholder = itemElement.querySelector('.ai-summary');
const summarizeApiUrl = `/api/summarize?author=${encodeURIComponent(author)}&repo=${encodeURIComponent(repo)}`;
try {
const response = await fetch(summarizeApiUrl);
itemElement.classList.remove('summary-loading');
if (!response.ok) throw new Error(`API Error: ${response.status}`);
const data = await response.json();
const failures = [
'Failed to generate summary or summary was empty.',
'README is empty or could not be fetched.',
'LongCat API key not configured.'
];
if (data.summary && !failures.includes(data.summary)) {
summaryPlaceholder.innerHTML = `<p><strong>AI 总结:</strong> ${esc(data.summary)}</p>`;
itemElement.classList.add('summary-loaded');
} else {
summaryPlaceholder.innerHTML = `<p><i>未能生成 AI 总结。 (${esc(data.summary || '原因未知')})</i></p>`;
}
} catch (error) {
console.error(`获取 AI 总结失败 (${author}/${repo}):`, error);
summaryPlaceholder.innerHTML = `<p><i>加载 AI 总结出错。 (${esc(error.message)})</i></p>`;
itemElement.classList.remove('summary-loading');
}
}
// ============================================================
// Progress pill
// ============================================================
function updateProgress(current, total) {
if (!progressEl) return;
if (!total) {
progressEl.classList.remove('visible');
progressEl.textContent = '';
return;
}
progressEl.textContent = `${current} / ${total}`;
progressEl.classList.add('visible');
}
// ============================================================
// Keyboard navigation (↑/↓ and k/j)
// ============================================================
function goToIndex(idx) {
const items = feedContainer.querySelectorAll('.gittok-item');
if (idx < 0 || idx >= items.length) return;
currentIndex = idx; // optimistic: keeps rapid presses in sync
updateProgress(idx + 1, items.length);
items[idx].scrollIntoView({ behavior: 'smooth', block: 'start' });
}
document.addEventListener('keydown', (e) => {
const tag = (e.target.tagName || '').toLowerCase();
if (tag === 'input' || tag === 'textarea') return;
if (e.key === 'ArrowDown' || e.key === 'j') {
e.preventDefault();
goToIndex(currentIndex + 1);
} else if (e.key === 'ArrowUp' || e.key === 'k') {
e.preventDefault();
goToIndex(currentIndex - 1);
}
});
// ============================================================
// Delegated clicks (DeepWiki / Zread / share / retry)
// ============================================================
feedContainer.addEventListener('click', (e) => {
const retry = e.target.closest('[data-retry]');
if (retry) {
fetchTrendingRepos(currentSince);
return;
}
const btn = e.target.closest('[data-action]');
if (!btn) return;
const item = btn.closest('.gittok-item');
if (!item) return;
const { author, repo, url } = item.dataset;
switch (btn.dataset.action) {
case 'deepwiki': openDeepWiki(url, repo); break;
case 'zread': openZread(author, repo); break;
case 'share': shareGitTok(btn); break;
}
});
function openDeepWiki(url, repoName) {
let deepWikiUrl = url;
if (deepWikiUrl && deepWikiUrl.includes('github.com')) {
deepWikiUrl = deepWikiUrl.replace('github.com', 'deepwiki.com');
} else {
const q = encodeURIComponent((repoName || '').split('/').pop());
deepWikiUrl = `https://deepwiki.com/search?q=${q}`;
}
window.open(deepWikiUrl, '_blank', 'noopener');
}
function openZread(author, repoName) {
const zreadUrl = `https://zread.ai/${author}/${(repoName || '').split('/').pop()}`;
window.open(zreadUrl, '_blank', 'noopener');
}
async function shareGitTok(button) {
const shareUrl = 'https://github.com/LeaderOnePro/GitTok';
const shareTitle = 'GitTok - 像刷 TikTok 一样刷 GitHub Trending';
const shareText = `快来看看这个项目 GitTok,用 TikTok 的方式浏览 GitHub Trending! ${shareUrl}`;
if (navigator.share) {
try {
await navigator.share({ title: shareTitle, text: shareText, url: shareUrl });
} catch (err) {
if (err.name !== 'AbortError') console.error('分享时出错:', err);
}
} else {
try {
await navigator.clipboard.writeText(shareUrl);
const original = button.innerHTML;
button.innerHTML = CHECK_ICON;
setTimeout(() => { button.innerHTML = original; }, 1500);
} catch (err) {
console.error('无法复制链接:', err);
alert('复制链接失败,请手动复制:\n' + shareUrl);
}
}
}
// ============================================================
// Time-range switching + initial load
// ============================================================
timeRangeButtons.forEach(button => {
button.addEventListener('click', () => {
if (button.classList.contains('active')) return; // already showing this range
timeRangeButtons.forEach(btn => btn.classList.remove('active'));
button.classList.add('active');
currentSince = button.dataset.since;
fetchTrendingRepos(currentSince);
});
});
fetchTrendingRepos(currentSince);
});