const SORT_MODE_LABELS = {
newest: '最新發布在前',
oldest: '最舊發布在前',
manual: '教師手動排序',
};
export const SORT_MODES = Object.keys(SORT_MODE_LABELS);
export function getSortModeLabel(mode) {
return SORT_MODE_LABELS[mode] || SORT_MODE_LABELS.newest;
}
function timeValue(post) {
const value = post.publish_at || post.published_at || post.updated_at || post.created_at;
const time = value ? new Date(value).getTime() : 0;
return Number.isNaN(time) ? 0 : time;
}
export function sortPosts(posts, mode = 'newest') {
return [...posts].sort((a, b) => {
const priorityDifference = Number(Boolean(b.pinned || b.locked)) - Number(Boolean(a.pinned || a.locked));
if (priorityDifference !== 0) return priorityDifference;
if (mode === 'manual') {
return (a.sort_order || 0) - (b.sort_order || 0) || timeValue(b) - timeValue(a);
}
const timeDifference = timeValue(b) - timeValue(a);
if (timeDifference !== 0) return mode === 'oldest' ? -timeDifference : timeDifference;
return (a.sort_order || 0) - (b.sort_order || 0);
});
}
1const SORT_MODE_LABELS = {
2 newest: '最新發布在前',
3 oldest: '最舊發布在前',
4 manual: '教師手動排序',
5};
7export const SORT_MODES = Object.keys(SORT_MODE_LABELS);
9export function getSortModeLabel(mode) {
10 return SORT_MODE_LABELS[mode] || SORT_MODE_LABELS.newest;
11}
13function timeValue(post) {
14 const value = post.publish_at || post.published_at || post.updated_at || post.created_at;
15 const time = value ? new Date(value).getTime() : 0;
16 return Number.isNaN(time) ? 0 : time;
17}
19export function sortPosts(posts, mode = 'newest') {
20 return [...posts].sort((a, b) => {
21 const priorityDifference = Number(Boolean(b.pinned || b.locked)) - Number(Boolean(a.pinned || a.locked));
22 if (priorityDifference !== 0) return priorityDifference;
24 if (mode === 'manual') {
25 return (a.sort_order || 0) - (b.sort_order || 0) || timeValue(b) - timeValue(a);
26 }
28 const timeDifference = timeValue(b) - timeValue(a);
29 if (timeDifference !== 0) return mode === 'oldest' ? -timeDifference : timeDifference;
30 return (a.sort_order || 0) - (b.sort_order || 0);
31 });
32}