diff --git a/www/src/lib/dnd.ts b/www/src/lib/dnd.ts new file mode 100644 index 0000000..64e3aee --- /dev/null +++ b/www/src/lib/dnd.ts @@ -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; + 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); + + 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 }; +} diff --git a/www/src/lib/md.ts b/www/src/lib/md.ts index 9936ce7..bc0aad3 100644 --- a/www/src/lib/md.ts +++ b/www/src/lib/md.ts @@ -42,10 +42,10 @@ function sortPosts(posts: PostWithDates[], { alphabetically = false } = {}): Pos }); } -export function resolveRelatedPosts( +export function resolveRelatedPosts( 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) ?? []); }