-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1410 lines (1172 loc) · 40.3 KB
/
script.js
File metadata and controls
1410 lines (1172 loc) · 40.3 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
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const THEME_KEY = "pi-blog-demo-theme";
const DATA_URL = "./articles.json?v=20260311-2";
const HOME_PAGE_SIZE = 4;
const themeToggle = document.getElementById("theme-toggle");
const body = document.body;
const pageType = body?.dataset?.page || "home";
let cachedSite = null;
let cachedPosts = [];
let hasLoadedBlog = false;
function getStoredTheme() {
try {
const theme = window.localStorage.getItem(THEME_KEY);
return theme === "dark" || theme === "light" ? theme : null;
} catch {
return null;
}
}
function storeTheme(theme) {
try {
window.localStorage.setItem(THEME_KEY, theme);
} catch {
// Ignore storage failures.
}
}
function getPreferredTheme() {
return window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches
? "dark"
: "light";
}
function applyTheme(theme) {
const nextTheme = theme === "dark" ? "dark" : "light";
document.documentElement.dataset.theme = nextTheme;
if (body) {
body.dataset.theme = nextTheme;
}
if (themeToggle) {
const switchTo = nextTheme === "dark" ? "light" : "dark";
themeToggle.textContent = switchTo === "dark" ? "Dark mode" : "Light mode";
themeToggle.setAttribute("aria-label", `Switch to ${switchTo} theme`);
themeToggle.setAttribute("aria-pressed", String(nextTheme === "dark"));
}
}
function initThemeToggle() {
applyTheme(getStoredTheme() || getPreferredTheme());
if (!themeToggle) {
return;
}
themeToggle.addEventListener("click", () => {
const currentTheme = document.documentElement.dataset.theme === "dark" ? "dark" : "light";
const nextTheme = currentTheme === "dark" ? "light" : "dark";
applyTheme(nextTheme);
storeTheme(nextTheme);
});
}
function initMobileHeaderBehavior() {
const header = document.querySelector(".site-header");
if (!header) {
return;
}
const mediaQuery = window.matchMedia("(max-width: 760px)");
let lastY = window.scrollY;
let ticking = false;
function syncHeaderState() {
const currentY = window.scrollY;
const delta = currentY - lastY;
if (!mediaQuery.matches) {
header.classList.remove("is-mobile-hidden");
lastY = currentY;
ticking = false;
return;
}
if (currentY <= 8) {
header.classList.remove("is-mobile-hidden");
} else if (delta > 10) {
header.classList.add("is-mobile-hidden");
} else if (delta < -10) {
header.classList.remove("is-mobile-hidden");
}
lastY = currentY;
ticking = false;
}
function onScroll() {
if (ticking) {
return;
}
ticking = true;
window.requestAnimationFrame(syncHeaderState);
}
window.addEventListener("scroll", onScroll, { passive: true });
mediaQuery.addEventListener("change", syncHeaderState);
syncHeaderState();
}
function qs(id) {
return document.getElementById(id);
}
function clear(node) {
if (node) {
node.replaceChildren();
}
}
function createElement(tag, className, text) {
const element = document.createElement(tag);
if (className) {
element.className = className;
}
if (typeof text === "string") {
element.textContent = text;
}
return element;
}
function setText(id, text) {
const node = qs(id);
if (node && typeof text === "string") {
node.textContent = text;
}
}
function renderMarkdownNodes(markdown, options = {}) {
const nodes = [];
if (typeof markdown !== "string" || !markdown.trim()) {
return nodes;
}
const { skipH1 = false } = options;
const lines = markdown.split(/\r?\n/);
let buffer = [];
function flushParagraph() {
if (!buffer.length) {
return;
}
const text = buffer.join(" ").trim();
if (text) {
nodes.push(createElement("p", "", text));
}
buffer = [];
}
lines.forEach((raw) => {
const line = raw.trim();
if (!line) {
flushParagraph();
return;
}
if (line.startsWith("### ")) {
flushParagraph();
nodes.push(createElement("h3", "", line.slice(4).trim()));
return;
}
if (line.startsWith("## ")) {
flushParagraph();
nodes.push(createElement("h2", "", line.slice(3).trim()));
return;
}
if (line.startsWith("# ")) {
flushParagraph();
if (!skipH1) {
nodes.push(createElement("h1", "", line.slice(2).trim()));
}
return;
}
buffer.push(line);
});
flushParagraph();
return nodes;
}
function extractMarkdownTitle(markdown) {
if (typeof markdown !== "string") {
return "";
}
const lines = markdown.split(/\r?\n/);
for (const raw of lines) {
const line = raw.trim();
if (line.startsWith("# ")) {
return line.slice(2).trim();
}
}
return "";
}
function applyExcerptTitleToPosts(posts) {
if (!Array.isArray(posts)) {
return posts;
}
posts.forEach((post) => {
const excerptTitle = extractMarkdownTitle(post?.excerpt || "");
if (excerptTitle) {
post.title = excerptTitle;
}
});
return posts;
}
function renderMarkdownInto(target, markdown, options) {
if (!target) {
return;
}
const nodes = renderMarkdownNodes(markdown, options || {});
if (!nodes.length) {
return;
}
nodes.forEach((node) => target.appendChild(node));
}
function setMarkdown(id, markdown, options) {
const node = qs(id);
if (!node) {
return;
}
clear(node);
renderMarkdownInto(node, markdown, options || {});
}
function setHref(id, href) {
const node = qs(id);
if (node && typeof href === "string") {
node.href = href;
}
}
function formatDate(value) {
if (typeof value !== "string" || !value.trim()) {
return "";
}
const date = new Date(value);
if (Number.isNaN(date.getTime())) {
return value;
}
return new Intl.DateTimeFormat(undefined, { dateStyle: "medium" }).format(date);
}
function getInitials(name) {
if (typeof name !== "string" || !name.trim()) {
return "AI";
}
const parts = name.trim().split(/\s+/).slice(0, 2);
return parts.map((part) => part[0]?.toUpperCase() || "").join("") || "AI";
}
function createTag(tagText) {
const link = createElement("a", "tag", tagText);
link.href = buildTagHref(tagText);
link.title = `查看标签「${tagText}」归档`;
return link;
}
function createTagRow(tags) {
if (!Array.isArray(tags) || !tags.length) {
return null;
}
const row = createElement("div", "tag-row");
tags
.filter((tag) => typeof tag === "string" && tag.trim())
.forEach((tag) => row.appendChild(createTag(tag.trim())));
return row.childNodes.length ? row : null;
}
function renderTags(id, tags) {
const container = qs(id);
if (!container) {
return;
}
clear(container);
const row = createTagRow(tags);
if (row) {
container.appendChild(row);
}
}
function normalizeTag(tag) {
return typeof tag === "string" ? tag.trim().toLowerCase() : "";
}
function collectTags(posts) {
const map = new Map();
posts.forEach((post) => {
if (!Array.isArray(post.tags)) {
return;
}
post.tags.forEach((tag) => {
if (typeof tag !== "string" || !tag.trim()) {
return;
}
const value = tag.trim();
const key = normalizeTag(value);
const current = map.get(key) || { name: value, count: 0 };
current.count += 1;
map.set(key, current);
});
});
return Array.from(map.values()).sort((a, b) => b.count - a.count || a.name.localeCompare(b.name));
}
function filterPostsByTag(posts, activeTag) {
const normalizedTag = normalizeTag(activeTag);
if (!normalizedTag) {
return posts;
}
return posts.filter((post) =>
Array.isArray(post.tags)
&& post.tags.some((tag) => normalizeTag(tag) === normalizedTag)
);
}
function createTagFilterChip(tag, href, isActive) {
const chip = createElement("a", "tag", tag);
chip.href = href;
if (tag !== "全部") {
chip.title = `在首页按「${tag}」筛选`;
}
if (isActive) {
chip.setAttribute("aria-current", "true");
chip.style.background = "var(--accent)";
chip.style.color = "#fff";
}
return chip;
}
function renderTagFilters(tags, activeTag, sort) {
const container = qs("tag-filter-list");
if (!container) {
return;
}
clear(container);
const row = createElement("div", "tag-row");
row.appendChild(createTagFilterChip("全部", buildIndexHref(1, "", sort), !normalizeTag(activeTag)));
tags.forEach((tag) => {
const isActive = normalizeTag(tag.name) === normalizeTag(activeTag);
row.appendChild(createTagFilterChip(`${tag.name} (${tag.count})`, buildIndexHref(1, tag.name, sort), isActive));
});
container.appendChild(row);
}
function buildPostHref(slug, view) {
const params = new URLSearchParams();
const resolvedView = view === "detail" ? "detail" : "summary";
params.set("slug", slug);
if (resolvedView === "detail") {
params.set("view", "detail");
}
return `./post.html?${params.toString()}`;
}
function buildAuthorHref(author) {
const params = new URLSearchParams({ author: author.trim() });
return `./author.html?${params.toString()}`;
}
function buildTagHref(tag) {
const params = new URLSearchParams({ tag: tag.trim() });
return `./tag.html?${params.toString()}`;
}
function buildIndexHref(page, tag, sort) {
const params = new URLSearchParams();
const trimmedTag = typeof tag === "string" ? tag.trim() : "";
const resolvedSort = sort === "added-asc" ? "added-asc" : "added-desc";
if (page > 1) {
params.set("page", String(page));
}
if (trimmedTag) {
params.set("tag", trimmedTag);
}
if (resolvedSort !== "added-desc") {
params.set("sort", resolvedSort);
}
const query = params.toString();
return query ? `./index.html?${query}` : "./index.html";
}
function createMetaLine(post) {
return [post.author, formatDate(post.publishedAt), post.source]
.filter((part) => typeof part === "string" && part.trim())
.join(" • ");
}
function sortPostsByAdded(posts, sort) {
const list = Array.isArray(posts) ? [...posts] : [];
return sort === "added-asc" ? [...list].reverse() : list;
}
function getPageFromQuery() {
const params = new URLSearchParams(window.location.search);
const raw = Number.parseInt(params.get("page") || "1", 10);
return Number.isFinite(raw) && raw > 0 ? raw : 1;
}
function getSlugFromQuery() {
const params = new URLSearchParams(window.location.search);
return params.get("slug") || "";
}
function getAuthorFromQuery() {
const author = new URLSearchParams(window.location.search).get("author");
return author ? author.trim() : "";
}
function getTagFromQuery() {
return new URLSearchParams(window.location.search).get("tag")?.trim() || "";
}
function getSortFromQuery() {
const raw = new URLSearchParams(window.location.search).get("sort")?.trim();
return raw === "added-asc" ? "added-asc" : "added-desc";
}
function getPostViewFromQuery() {
const raw = new URLSearchParams(window.location.search).get("view")?.trim();
return raw === "detail" ? "detail" : "summary";
}
function validatePosts(posts) {
return Array.isArray(posts)
? posts.filter((post) => post && typeof post.slug === "string" && typeof post.title === "string")
: [];
}
function isModifiedNavigation(event) {
return event.defaultPrevented
|| event.button !== 0
|| event.metaKey
|| event.ctrlKey
|| event.shiftKey
|| event.altKey;
}
function isHomePathname(pathname) {
return pathname === "/" || pathname.endsWith("/index.html");
}
async function renderCurrentHomePage(preferFresh = false) {
if (pageType !== "home") {
return;
}
if (preferFresh || !hasLoadedBlog) {
await loadBlog();
return;
}
renderHome(cachedSite || {}, Array.isArray(cachedPosts) ? cachedPosts : []);
}
function initHomeNavigation() {
if (pageType !== "home") {
return;
}
document.addEventListener("click", (event) => {
const link = event.target.closest("#pagination a, #tag-filter-list a, #sort-filter-list a");
if (!link || isModifiedNavigation(event)) {
return;
}
if (link.target && link.target !== "_self") {
return;
}
const url = new URL(link.href, window.location.href);
if (url.origin !== window.location.origin || !isHomePathname(url.pathname) || !hasLoadedBlog) {
return;
}
const nextUrl = `${url.pathname}${url.search}${url.hash}`;
const currentUrl = `${window.location.pathname}${window.location.search}${window.location.hash}`;
event.preventDefault();
if (nextUrl === currentUrl) {
return;
}
window.history.pushState({ page: "home" }, "", nextUrl);
void renderCurrentHomePage(true);
});
window.addEventListener("popstate", () => {
if (!hasLoadedBlog || !isHomePathname(window.location.pathname)) {
return;
}
void renderCurrentHomePage(true);
});
window.addEventListener("focus", () => {
if (!hasLoadedBlog || !isHomePathname(window.location.pathname)) {
return;
}
void renderCurrentHomePage(true);
});
}
function renderFeatured(site, posts, activeTag) {
const siteTitle = typeof site?.title === "string" && site.title.trim()
? site.title.trim()
: "lyfmt's Notes";
const description = typeof site?.description === "string" && site.description.trim()
? site.description.trim()
: "一个更接近真实博客的首页演示。";
const tagLabel = typeof activeTag === "string" ? activeTag.trim() : "";
setText("home-title", siteTitle);
setText("home-description", description);
setText(
"featured-supporting-copy",
tagLabel
? `当前正在按「${tagLabel}」标签浏览,可先查看这一主题的精选内容,再继续阅读作者与最新文章。`
: "在这里快速查看精选内容、作者信息与最新文章动态。"
);
const featured = Array.isArray(posts) ? posts[0] || null : null;
if (!featured) {
setText("featured-title", "暂无精选文章");
setText("featured-excerpt", "当前还没有文章可展示。请先在 articles.json 中添加内容。");
setText("featured-meta", "等待内容中");
setHref("hero-primary-link", "#latest-posts-title");
renderTags("featured-tags", []);
return;
}
setText("featured-title", featured.title);
const featuredExcerpt = featured.excerpt || "这篇文章暂无摘要。";
const excerptIsMarkdown = typeof featuredExcerpt === "string" && featuredExcerpt.trim().startsWith("# ");
setMarkdown("featured-excerpt", featuredExcerpt, { skipH1: excerptIsMarkdown });
setText("featured-meta", createMetaLine(featured));
setHref("hero-primary-link", buildPostHref(featured.slug));
renderTags("featured-tags", featured.tags);
}
function renderStats(posts) {
const authors = new Set();
const sources = new Set();
posts.forEach((post) => {
if (post.author) {
authors.add(post.author);
}
if (post.source) {
sources.add(post.source);
}
});
setText("stat-post-count", String(posts.length));
setText("stat-author-count", String(authors.size));
setText("stat-source-count", String(sources.size));
}
function collectAuthors(posts) {
const map = new Map();
posts.forEach((post) => {
const name = typeof post.author === "string" && post.author.trim() ? post.author.trim() : "Unknown";
const current = map.get(name) || {
name,
count: 0,
latest: "",
sources: new Set(),
tags: new Set()
};
current.count += 1;
if (typeof post.publishedAt === "string" && post.publishedAt > current.latest) {
current.latest = post.publishedAt;
}
if (typeof post.source === "string" && post.source.trim()) {
current.sources.add(post.source.trim());
}
if (Array.isArray(post.tags)) {
post.tags.forEach((tag) => {
if (typeof tag === "string" && tag.trim()) {
current.tags.add(tag.trim());
}
});
}
map.set(name, current);
});
return Array.from(map.values()).sort((a, b) => b.count - a.count || a.name.localeCompare(b.name));
}
function renderAuthors(posts) {
const container = qs("author-list");
if (!container) {
return;
}
clear(container);
container.setAttribute("aria-busy", "false");
const authors = collectAuthors(posts);
if (!authors.length) {
const empty = createElement("article", "empty-state empty-state--compact");
empty.appendChild(createElement("p", "", "当前没有可展示的作者信息。"));
container.appendChild(empty);
return;
}
authors.forEach((author) => {
const card = createElement("article", "author-card");
const header = createElement("div", "author-card__header");
const avatar = createElement("div", "author-card__avatar", getInitials(author.name));
const meta = createElement("div", "author-card__meta");
const nameHeading = createElement("h3", "author-card__name");
const nameLink = createElement("a", "author-card__link", author.name);
nameLink.href = buildAuthorHref(author.name);
nameHeading.appendChild(nameLink);
meta.append(
nameHeading,
createElement("p", "author-card__copy", `${author.count} 篇文章 · 最近更新 ${formatDate(author.latest)}`)
);
header.append(avatar, meta);
const sources = createElement("p", "author-card__copy", `来源:${Array.from(author.sources).join("、") || "未知"}`);
const tags = createTagRow(Array.from(author.tags).slice(0, 4));
card.appendChild(header);
card.appendChild(sources);
if (tags) {
card.appendChild(tags);
}
container.appendChild(card);
});
}
function renderSortFilters(activeSort, activeTag) {
const container = qs("sort-filter-list");
if (!container) {
return;
}
clear(container);
const row = createElement("div", "segmented-control");
row.setAttribute("role", "tablist");
row.setAttribute("aria-label", "按加入时间排序");
const options = [
["added-desc", "最新加入"],
["added-asc", "最早加入"]
];
options.forEach(([value, label]) => {
const isActive = activeSort === value;
const link = createElement("a", `segmented-control__item${isActive ? " is-active" : ""}`, label);
link.href = buildIndexHref(1, activeTag, value);
link.setAttribute("role", "tab");
link.setAttribute("aria-selected", String(isActive));
if (isActive) {
link.setAttribute("aria-current", "true");
}
row.appendChild(link);
});
container.appendChild(row);
}
function renderPagination(totalPages, currentPage, activeTag, activeSort) {
const container = qs("pagination");
if (!container) {
return;
}
clear(container);
if (totalPages <= 1) {
const only = createElement("span", "pagination__link is-current", "1");
only.setAttribute("aria-current", "page");
container.appendChild(only);
return;
}
const prev = currentPage > 1
? (() => {
const link = createElement("a", "pagination__link", "← 上一页");
link.href = buildIndexHref(currentPage - 1, activeTag, activeSort);
return link;
})()
: createElement("span", "pagination__link is-disabled", "← 上一页");
container.appendChild(prev);
for (let page = 1; page <= totalPages; page += 1) {
if (page === currentPage) {
const current = createElement("span", "pagination__link is-current", String(page));
current.setAttribute("aria-current", "page");
container.appendChild(current);
} else {
const link = createElement("a", "pagination__link", String(page));
link.href = buildIndexHref(page, activeTag, activeSort);
container.appendChild(link);
}
}
const next = currentPage < totalPages
? (() => {
const link = createElement("a", "pagination__link", "下一页 →");
link.href = buildIndexHref(currentPage + 1, activeTag, activeSort);
return link;
})()
: createElement("span", "pagination__link is-disabled", "下一页 →");
container.appendChild(next);
}
function renderHome(site, posts) {
const description = qs("home-description");
const count = qs("post-count");
const container = qs("home-posts");
if (!container) {
return;
}
const siteTitle = typeof site?.title === "string" && site.title.trim() ? site.title.trim() : "lyfmt's Notes";
const activeTag = getTagFromQuery();
const activeSort = getSortFromQuery();
const allTags = collectTags(posts);
const filteredPosts = filterPostsByTag(posts, activeTag);
const sortedPosts = sortPostsByAdded(filteredPosts, activeSort);
const featuredPosts = sortedPosts.length ? sortedPosts : sortPostsByAdded(posts, activeSort);
const requestedPage = getPageFromQuery();
const totalPages = Math.max(1, Math.ceil(sortedPosts.length / HOME_PAGE_SIZE));
const currentPage = Math.min(Math.max(1, requestedPage), totalPages);
document.title = activeTag
? `${siteTitle} — ${activeTag}`
: currentPage > 1 ? `${siteTitle} — 第 ${currentPage} 页` : siteTitle;
if (description && site?.description) {
description.textContent = site.description;
}
renderTagFilters(allTags, activeTag, activeSort);
renderSortFilters(activeSort, activeTag);
renderFeatured(site, featuredPosts, activeTag);
renderStats(posts);
renderAuthors(posts);
if (count) {
const sortLabel = activeSort === "added-asc" ? "最早加入" : "最新加入";
count.textContent = activeTag
? `标签「${activeTag}」下共 ${sortedPosts.length} 篇文章 · 按${sortLabel}`
: `第 ${currentPage} 页,共 ${totalPages} 页 · 当前共 ${sortedPosts.length} 篇文章 · 按${sortLabel}`;
}
clear(container);
container.setAttribute("aria-busy", "false");
if (!posts.length) {
const empty = createElement("article", "empty-state");
empty.append(
createElement("h3", "", "暂无文章"),
createElement("p", "", "articles.json 已加载,但 posts 数组为空。")
);
container.appendChild(empty);
renderPagination(1, 1, activeTag, activeSort);
return;
}
if (!sortedPosts.length) {
const empty = createElement("article", "empty-state");
empty.append(
createElement("h3", "", "当前标签暂无文章"),
createElement("p", "", `标签「${activeTag}」下还没有文章,稍后再来看看。`)
);
container.appendChild(empty);
renderPagination(1, 1, activeTag, activeSort);
return;
}
const start = (currentPage - 1) * HOME_PAGE_SIZE;
const pagePosts = sortedPosts.slice(start, start + HOME_PAGE_SIZE);
pagePosts.forEach((post, index) => {
const card = createElement("article", "post-card");
const badge = createElement("span", "post-card__index", String(start + index + 1).padStart(2, "0"));
const meta = createElement("p", "post-card__meta", createMetaLine(post));
const title = createElement("h3", "post-card__title");
const titleLink = createElement("a", "post-card__link", post.title);
titleLink.href = buildPostHref(post.slug);
title.appendChild(titleLink);
const excerpt = createElement("div", "post-card__excerpt");
renderMarkdownInto(excerpt, post.excerpt || "", { skipH1: true });
const footer = createElement("div", "post-card__footer");
const more = createElement("a", "post-card__more", "阅读详情 →");
more.href = buildPostHref(post.slug);
footer.appendChild(more);
const tagRow = createTagRow(post.tags);
if (tagRow) {
footer.prepend(tagRow);
}
card.append(badge, meta, title, excerpt, footer);
container.appendChild(card);
});
renderPagination(totalPages, currentPage, activeTag, activeSort);
}
function renderArchivePostCards(container, posts) {
clear(container);
container.setAttribute("aria-busy", "false");
posts.forEach((post, index) => {
const card = createElement("article", "post-card");
const badge = createElement("span", "post-card__index", String(index + 1).padStart(2, "0"));
const meta = createElement("p", "post-card__meta", createMetaLine(post));
const title = createElement("h3", "post-card__title");
const titleLink = createElement("a", "post-card__link", post.title);
titleLink.href = buildPostHref(post.slug);
title.appendChild(titleLink);
const excerpt = createElement("div", "post-card__excerpt");
renderMarkdownInto(excerpt, post.excerpt || "", { skipH1: true });
const footer = createElement("div", "post-card__footer");
const more = createElement("a", "post-card__more", "阅读详情 →");
more.href = buildPostHref(post.slug);
footer.appendChild(more);
const tagRow = createTagRow(post.tags);
if (tagRow) {
footer.prepend(tagRow);
}
card.append(badge, meta, title, excerpt, footer);
container.appendChild(card);
});
}
function renderAuthorPage(posts) {
const author = getAuthorFromQuery();
const matchedPosts = posts.filter((post) => (post.author || "").trim() === author);
const titleNode = qs("author-page-title");
const descNode = qs("author-page-description");
const statsNode = qs("author-page-stats");
const countNode = qs("author-page-post-count");
const postsNode = qs("author-page-posts");
if (!postsNode) {
return;
}
if (!author) {
document.title = "作者归档 — lyfmt's Notes";
setText("author-page-title", "未指定作者");
setText("author-page-description", "请从首页作者区进入具体作者页面。" );
clear(postsNode);
postsNode.setAttribute("aria-busy", "false");
const empty = createElement("article", "empty-state");
empty.append(
createElement("h3", "", "暂无作者信息"),
createElement("p", "", "当前页面缺少 author 参数。")
);
postsNode.appendChild(empty);
if (countNode) {
countNode.textContent = "0 篇文章";
}
return;
}
document.title = `${author} — lyfmt's Notes`;
if (titleNode) {
titleNode.textContent = author;
}
if (descNode) {
descNode.textContent = matchedPosts.length
? `这里聚合了 ${author} 的文章与更新时间。`
: `暂时还没有找到作者「${author}」的文章。`;
}
if (statsNode) {
clear(statsNode);
statsNode.setAttribute("aria-busy", "false");
const sources = new Set(matchedPosts.map((post) => post.source).filter(Boolean));
const latest = matchedPosts[0]?.publishedAt || "";
[
[String(matchedPosts.length), "Posts"],
[String(sources.size), "Sources"],
[latest ? formatDate(latest) : "—", "Updated"]
].forEach(([value, label]) => {
const card = createElement("article", "stat-card");
card.append(
createElement("span", "stat-card__value", value),
createElement("span", "stat-card__label", label)
);
statsNode.appendChild(card);
});
}
if (countNode) {
countNode.textContent = `${matchedPosts.length} 篇文章`;
}
if (!matchedPosts.length) {
clear(postsNode);
postsNode.setAttribute("aria-busy", "false");
const empty = createElement("article", "empty-state");
empty.append(
createElement("h3", "", "还没有文章"),
createElement("p", "", `作者「${author}」当前没有可展示的文章。`)
);
postsNode.appendChild(empty);
return;
}
renderArchivePostCards(postsNode, matchedPosts);
}
function renderTagPage(posts) {
const tag = getTagFromQuery();
const matchedPosts = filterPostsByTag(posts, tag);
const titleNode = qs("tag-page-title");
const descNode = qs("tag-page-description");
const countNode = qs("tag-page-post-count");
const postsNode = qs("tag-page-posts");
if (!postsNode) {
return;
}
if (!tag) {
document.title = "标签归档 — lyfmt's Notes";
setText("tag-page-title", "未指定标签");
setText("tag-page-description", "请从首页标签区进入具体标签页面。" );
clear(postsNode);
postsNode.setAttribute("aria-busy", "false");
const empty = createElement("article", "empty-state");
empty.append(
createElement("h3", "", "暂无标签信息"),
createElement("p", "", "当前页面缺少 tag 参数。")
);
postsNode.appendChild(empty);
if (countNode) {
countNode.textContent = "0 篇文章";
}
return;
}
document.title = `${tag} — lyfmt's Notes`;
if (titleNode) {
titleNode.textContent = `标签:${tag}`;
}