feat: add dnd.ts helper, make resolveRelatedPosts generic in md.ts
This commit is contained in:
parent
d25343aa85
commit
e2161341d7
2 changed files with 37 additions and 3 deletions
34
www/src/lib/dnd.ts
Normal file
34
www/src/lib/dnd.ts
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
import type { CollectionEntry } from 'astro:content';
|
||||
import { getSlug, resolveRelatedPosts } from './md';
|
||||
|
||||
type DndPost = CollectionEntry<'dnd'>;
|
||||
|
||||
export { getSlug, resolveRelatedPosts };
|
||||
|
||||
export function organizePostsByCategory(posts: DndPost[]): {
|
||||
grouped: Record<string, DndPost[]>;
|
||||
categories: string[];
|
||||
} {
|
||||
const grouped = posts.reduce((acc, post) => {
|
||||
const category = post.data.category ?? 'dnd';
|
||||
if (!acc[category]) acc[category] = [];
|
||||
acc[category].push(post);
|
||||
return acc;
|
||||
}, {} as Record<string, DndPost[]>);
|
||||
|
||||
const categories = Object.keys(grouped).sort((a, b) => {
|
||||
if (a === 'dnd') return -1;
|
||||
if (b === 'dnd') return 1;
|
||||
return a.localeCompare(b);
|
||||
});
|
||||
|
||||
for (const category of categories) {
|
||||
grouped[category] = grouped[category].slice().sort((a, b) => {
|
||||
if (a.data.pinned && !b.data.pinned) return -1;
|
||||
if (!a.data.pinned && b.data.pinned) return 1;
|
||||
return a.data.title.localeCompare(b.data.title);
|
||||
});
|
||||
}
|
||||
|
||||
return { grouped, categories };
|
||||
}
|
||||
|
|
@ -42,10 +42,10 @@ function sortPosts(posts: PostWithDates[], { alphabetically = false } = {}): Pos
|
|||
});
|
||||
}
|
||||
|
||||
export function resolveRelatedPosts(
|
||||
export function resolveRelatedPosts<T extends { id: string }>(
|
||||
slugs: string[],
|
||||
allPosts: PostWithDates[],
|
||||
): PostWithDates[] {
|
||||
allPosts: T[],
|
||||
): T[] {
|
||||
const bySlug = new Map(allPosts.map(p => [getSlug(p.id), p]));
|
||||
return slugs.flatMap(s => bySlug.get(s) ?? []);
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue