-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
62 lines (53 loc) · 1.87 KB
/
Copy pathscript.js
File metadata and controls
62 lines (53 loc) · 1.87 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
const postsContainer = document.querySelector("#posts");
const emptyState = document.querySelector("#empty-state");
const postCount = document.querySelector("#post-count");
const formatter = new Intl.DateTimeFormat("zh-CN", {
year: "numeric",
month: "long",
day: "numeric"
});
function formatDate(value) {
return formatter.format(new Date(value));
}
function escapeHtml(value) {
return String(value)
.replaceAll("&", "&")
.replaceAll("<", "<")
.replaceAll(">", ">")
.replaceAll('"', """)
.replaceAll("'", "'");
}
function renderPosts(items) {
postsContainer.innerHTML = items.map((post, index) => {
const tags = post.tags.map((tag) => `<span class="tag">${escapeHtml(tag)}</span>`).join("");
const href = post.url || "#";
const featured = index === 0 ? " featured" : "";
return `
<article class="post-item${featured}">
<time class="post-date" datetime="${escapeHtml(post.date)}">${formatDate(post.date)}</time>
<div class="post-body">
<a class="post-title" href="${escapeHtml(href)}">${escapeHtml(post.title)}</a>
<p class="post-summary">${escapeHtml(post.summary)}</p>
<div class="tags">${tags}</div>
</div>
</article>
`;
}).join("");
emptyState.hidden = items.length > 0;
postCount.textContent = `${items.length} 篇文章`;
}
async function loadPosts() {
try {
const response = await fetch("posts.json?v=2026080404");
if (!response.ok) throw new Error("posts.json not found");
const posts = await response.json();
posts.sort((a, b) => new Date(b.date) - new Date(a.date));
renderPosts(posts);
} catch (error) {
postsContainer.innerHTML = "";
emptyState.hidden = false;
emptyState.textContent = "文章加载失败,请检查 posts.json 是否已经上传。";
postCount.textContent = "加载失败";
}
}
loadPosts();