Fix article sort problem in non-zh environment.

This commit is contained in:
2024-06-10 12:43:46 +08:00
parent 83d584c529
commit 6127d5f7ed
3 changed files with 54 additions and 21 deletions

View File

@@ -1,8 +1,10 @@
---
import type { CollectionEntry } from "astro:content";
import type { CollectionEntry, ContentEntryMap } from "astro:content";
import { getCollection, type CollectionKey } from "astro:content";
import CategorySummary from "./CategorySummary.astro";
import * as pinyinpro from "pinyin-pro";
interface Props {
collectionName: CollectionKey;
sortedByTimeline: boolean;
@@ -27,26 +29,50 @@ const allCategories: Array<string> = Array.from(
const categoriedPostList: Array<CategoriedPosts> = allCategories.map((key) => {
let object: CategoriedPosts = {};
object[key] = allPosts.filter((post) => post.data.category === key);
sortedByTimeline
? object[key].sort(
(
postA: CollectionEntry<CollectionKey>,
postB: CollectionEntry<CollectionKey>
) => {
if (postA.data.lastUpdate !== postB.data.lastUpdate) {
return postA.data.lastUpdate < postB.data.lastUpdate ? 1 : -1;
}
return postA.id.localeCompare(postB.id);
}
)
: object[key].sort(
(
postA: CollectionEntry<CollectionKey>,
postB: CollectionEntry<CollectionKey>
) => {
return postA.id.localeCompare(postB.id);
}
);
// article sort function by article title
function sortPostByTitlePinyin(
postA: CollectionEntry<CollectionKey>,
postB: CollectionEntry<CollectionKey>
): number {
let postATitle = pinyinpro.convert(pinyinpro.pinyin(postA.data.title), {
format: "symbolToNum",
});
let postBTitle = pinyinpro.convert(pinyinpro.pinyin(postB.data.title), {
format: "symbolToNum",
});
return postATitle.localeCompare(postBTitle, "en");
}
if (sortedByTimeline) {
// sort article by update date
object[key].sort((postA, postB) => {
// if two articles is updated on the same day, sort them by title
if (postA.data.lastUpdate !== postB.data.lastUpdate) {
return postA.data.lastUpdate < postB.data.lastUpdate ? 1 : -1;
}
return sortPostByTitlePinyin(postA, postB);
});
} else {
// sort article by title
// get articles with titles started in Chinese or the alphabet
let postWithAlphabetStartedTitle: CollectionEntry<keyof ContentEntryMap>[] =
object[key].filter((post) => /^[a-zA-Z]/.test(post.data.title));
let postWithChineseStartedTitle: CollectionEntry<keyof ContentEntryMap>[] =
object[key].filter((post) => /^[^a-zA-Z]/.test(post.data.title));
// sort two Array by article title
postWithAlphabetStartedTitle.sort((postA, postB) =>
sortPostByTitlePinyin(postA, postB)
);
postWithChineseStartedTitle.sort((postA, postB) =>
sortPostByTitlePinyin(postA, postB)
);
// articles that have title start with Chinese prior to
// those which have titles start with the alphabet
object[key] = postWithChineseStartedTitle.concat(
postWithAlphabetStartedTitle
);
}
return object;
});