feat: add dnd.ts helper, make resolveRelatedPosts generic in md.ts

This commit is contained in:
Lewis Wynne 2026-02-08 17:15:19 +00:00
parent d25343aa85
commit e2161341d7
2 changed files with 37 additions and 3 deletions

34
www/src/lib/dnd.ts Normal file
View 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 };
}

View file

@ -42,10 +42,10 @@ function sortPosts(posts: PostWithDates[], { alphabetically = false } = {}): Pos
}); });
} }
export function resolveRelatedPosts( export function resolveRelatedPosts<T extends { id: string }>(
slugs: string[], slugs: string[],
allPosts: PostWithDates[], allPosts: T[],
): PostWithDates[] { ): T[] {
const bySlug = new Map(allPosts.map(p => [getSlug(p.id), p])); const bySlug = new Map(allPosts.map(p => [getSlug(p.id), p]));
return slugs.flatMap(s => bySlug.get(s) ?? []); return slugs.flatMap(s => bySlug.get(s) ?? []);
} }