-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
297 lines (253 loc) · 10.2 KB
/
script.js
File metadata and controls
297 lines (253 loc) · 10.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
const GITHUB_USERNAME = "weisonx";
const MAX_REPOS = 6;
/* ===============================
1. 主题切换
================================ */
const htmlEl = document.documentElement;
const themeIcon = document.getElementById('theme-icon');
function setTheme(theme) {
htmlEl.setAttribute('data-theme', theme);
localStorage.setItem('theme', theme);
themeIcon.className = theme === 'light' ? 'fas fa-moon' : 'fas fa-sun';
}
const initialTheme =
localStorage.getItem('theme') ||
(window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light');
setTheme(initialTheme);
document.getElementById('theme-toggle').addEventListener('click', () => {
setTheme(htmlEl.getAttribute('data-theme') === 'dark' ? 'light' : 'dark');
});
/* ===============================
2. 打字机
================================ */
const phrases = ["架构师", "工程师", "开发者", "Slow is smooth, smooth is fast."];
let pIdx = 0, cIdx = 0, isDeleting = false;
function type() {
const text = phrases[pIdx];
const el = document.getElementById('typing-text');
el.textContent = text.substring(0, isDeleting ? cIdx-- : cIdx++);
if (!isDeleting && cIdx > text.length) {
isDeleting = true;
setTimeout(type, 2000);
} else if (isDeleting && cIdx < 0) {
isDeleting = false;
pIdx = (pIdx + 1) % phrases.length;
cIdx = 0;
setTimeout(type, 500);
} else {
setTimeout(type, isDeleting ? 50 : 100);
}
}
/* ===============================
3. GitHub 数据
================================ */
async function fetchGitHub() {
try {
const [uRes, rRes] = await Promise.all([
fetch(`https://api.github.com/users/${GITHUB_USERNAME}`),
fetch(`https://api.github.com/users/${GITHUB_USERNAME}/repos?sort=updated&per_page=30`)
]);
const user = await uRes.json();
const repos = await rRes.json();
document.getElementById('avatar').src = user.avatar_url;
document.getElementById('username').innerText = user.name || user.login;
document.getElementById('bio').innerText = user.bio || "Digital Craftsman";
document.getElementById('stats').innerHTML = `
<div class="stat-item"><span class="stat-num">${user.public_repos}</span><span class="stat-label">Repos</span></div>
<div class="stat-item"><span class="stat-num">${user.followers}</span><span class="stat-label">Followers</span></div>
`;
const topRepos = repos
.filter(r => !r.fork)
.sort((a, b) => b.stargazers_count - a.stargazers_count)
.slice(0, MAX_REPOS);
document.getElementById('repos-container').innerHTML = topRepos.map(r => `
<a href="${r.html_url}" target="_blank" class="card glass-card">
<div class="repo-name"><i class="fab fa-github"></i> ${r.name}</div>
<p class="repo-desc">${r.description || "No description provided."}</p>
<div class="repo-meta">
<span><i class="fas fa-code-branch"></i> ${r.language || 'Mixed'}</span>
<span>★ ${r.stargazers_count}</span>
</div>
</a>
`).join('');
initHomeShow();
} catch (e) {
console.error(e);
document.getElementById('bio').innerText =
"API rate limit reached. Please check back later.";
}
}
/* ===============================
4. Home Show(懒加载核心)
================================ */
const FILES_PER_BATCH = 30;
let filesCache = [];
let renderIndex = 0;
let batchObserver = null;
let previewObserver = null;
async function initHomeShow() {
const btn = document.getElementById('generate-cards');
const container = document.getElementById('file-cards-container');
async function loadFiles() {
btn.disabled = true;
btn.querySelector('i').classList.add('fa-spin');
container.innerHTML = "";
filesCache = [];
renderIndex = 0;
try {
const treeRes = await fetch(
`https://api.github.com/repos/${GITHUB_USERNAME}/weisonx.github.io/git/trees/main?recursive=1`
);
const treeData = await treeRes.json();
filesCache = treeData.tree
.filter(i =>
i.type === 'blob' &&
!i.path.startsWith('.') &&
!i.path.includes('node_modules/') &&
!i.path.includes('dist/') &&
!i.path.includes('vendor/')
)
.map(f => ({
...f,
repoName: "weisonx.github.io",
previewLoaded: false
}));
renderNextBatch(); // 渲染第一批
setupBatchObserver(); // 滚动批次懒加载
setupPreviewObserver(); // 给当前已有卡片加 preview 观察
} catch (err) {
console.error(err);
container.innerHTML =
`<p style="grid-column:1/-1;text-align:center;opacity:.5">无法加载文件</p>`;
} finally {
btn.disabled = false;
btn.querySelector('i').classList.remove('fa-spin');
}
}
btn.onclick = loadFiles;
loadFiles();
}
/* ===============================
5. 分批渲染卡片(修复点:渲染后给新卡片加 previewObserver)
================================ */
function renderNextBatch() {
const container = document.getElementById('file-cards-container');
const slice = filesCache.slice(renderIndex, renderIndex + FILES_PER_BATCH);
slice.forEach(f => {
container.insertAdjacentHTML('beforeend', createFileCardHTML(f));
});
renderIndex += FILES_PER_BATCH;
// 新增:只对刚刚渲染的这批卡片添加预览观察
if (previewObserver) {
const newCards = container.querySelectorAll(
`.file-card:nth-last-child(-n+${slice.length})`
);
newCards.forEach(c => previewObserver.observe(c));
}
}
/* ===============================
6. 卡片 HTML
================================ */
function createFileCardHTML(f) {
const ext = f.path.split('.').pop().toLowerCase();
const isCode = ["js","ts","py","html","css","md","json","yml","c","cpp","go","rs","sql"].includes(ext);
const fileName = f.path.split('/').pop();
return `
<div class="file-card glass-card"
data-path="${f.path}"
onclick="window.open('https://github.com/${GITHUB_USERNAME}/${f.repoName}/blob/main/${f.path}', '_blank')">
<div class="file-card-size">${(f.size/1024).toFixed(1)} KB</div>
<div class="file-card-icon ${isCode ? 'code' : 'binary'}">
<i class="fas ${isCode ? 'fa-code' : 'fa-file-alt'}"></i>
</div>
<div class="file-card-name">${fileName}</div>
<div class="file-card-path">${f.path}</div>
<div class="file-card-content">
<span style="opacity:0.4;font-style:italic;">预览加载中...</span>
</div>
</div>
`;
}
/* ===============================
7. 批次懒加载(滚动)
================================ */
function setupBatchObserver() {
if (batchObserver) batchObserver.disconnect();
batchObserver = new IntersectionObserver(entries => {
if (entries[0].isIntersecting && renderIndex < filesCache.length) {
renderNextBatch();
}
}, { rootMargin: '300px' });
batchObserver.observe(document.querySelector('.glass-footer'));
}
/* ===============================
8. Preview 懒加载
================================ */
function setupPreviewObserver() {
if (previewObserver) previewObserver.disconnect();
previewObserver = new IntersectionObserver(entries => {
entries.forEach(e => {
if (!e.isIntersecting) return;
const card = e.target;
const path = card.dataset.path;
const file = filesCache.find(f => f.path === path);
if (!file || file.previewLoaded) return;
loadPreview(card, file);
previewObserver.unobserve(card);
});
}, { rootMargin: '200px' });
// 给当前页面已存在的所有 file-card 添加观察
document.querySelectorAll('.file-card').forEach(c => previewObserver.observe(c));
}
async function loadPreview(card, file) {
const isPreviewable = /\.(js|ts|py|html|css|md|txt|json|yml|c|cpp|go|rs)$/.test(file.path);
if (!isPreviewable || file.size > 50000) {
file.previewLoaded = true; // 标记为已处理
card.querySelector('.file-card-content').innerHTML =
'<span style="opacity:.4;font-style:italic;">无法预览该文件</span>';
return;
}
try {
const res = await fetch(
`https://raw.githubusercontent.com/${GITHUB_USERNAME}/${file.repoName}/main/${file.path}`
);
if (res.ok) {
const text = await res.text();
file.previewLoaded = true;
card.querySelector('.file-card-content').innerText =
text.substring(0, 120);
} else {
file.previewLoaded = true;
card.querySelector('.file-card-content').innerHTML =
'<span style="opacity:.4;font-style:italic;">预览加载失败</span>';
}
} catch {
file.previewLoaded = true;
card.querySelector('.file-card-content').innerHTML =
'<span style="opacity:.4;font-style:italic;">预览加载失败</span>';
}
}
/* ===============================
9. 搜索
================================ */
document.getElementById('file-search').addEventListener('input', e => {
const term = e.target.value.toLowerCase();
const container = document.getElementById('file-cards-container');
container.innerHTML = "";
renderIndex = 0;
const filtered = filesCache.filter(f =>
f.path.toLowerCase().includes(term)
);
filtered.forEach(f => {
container.insertAdjacentHTML('beforeend', createFileCardHTML(f));
});
// 搜索后重新绑定预览观察
setupPreviewObserver();
});
/* ===============================
启动
================================ */
document.addEventListener('DOMContentLoaded', () => {
type();
fetchGitHub();
});