docs/.vitepress/theme/announcements.data.ts
69 lines · 1910 bytes
9 symbols in this file
1import { readdirSync, readFileSync } from 'node:fs'
2import { dirname, join } from 'node:path'
3import { fileURLToPath } from 'node:url'
4import matter from 'gray-matter'
5import MarkdownIt from 'markdown-it'
6
7export type AnnouncementType = 'section' | 'component' | 'improvement'
8
9export interface Announcement {
10 id: string
11 type: AnnouncementType
12 title: string
13 html: string
14 link?: string // section type only
15}
16
17const THEME_DIR = dirname(fileURLToPath(import.meta.url))
18const POST_DIR = join(THEME_DIR, '../post')
19
20const VALID_TYPES: AnnouncementType[] = ['section', 'component', 'improvement']
21
22const md = MarkdownIt({ html: true, linkify: true, breaks: false })
23
24function orderOf(id: string): number {
25 const m = id.match(/^(\d+)/)
26 return m ? parseInt(m[1], 10) : 0
27}
28
29function normalizeType(raw: unknown): AnnouncementType {
30 const value = String(raw ?? '').toLowerCase()
31 return (VALID_TYPES as string[]).includes(value)
32 ? (value as AnnouncementType)
33 : 'improvement'
34}
35
36function loadAnnouncements(): Announcement[] {
37 let files: string[] = []
38 try {
39 files = readdirSync(POST_DIR).filter((f) => f.endsWith('.md'))
40 } catch {
41 return []
42 }
43
44 // highest number first (files numbered "1. name.md" with 1 = oldest)
45 files.sort((a, b) => orderOf(b) - orderOf(a))
46
47 return files.map((file) => {
48 const raw = readFileSync(join(POST_DIR, file), 'utf-8')
49 const { data, content } = matter(raw)
50 // strip the "N. " prefix so read-state survives renumbering
51 const id = file.replace(/\.md$/, '').replace(/^\d+\.\s*/, '')
52 return {
53 id,
54 type: normalizeType(data.type),
55 title: String(data.title ?? id),
56 html: md.render(content),
57 link: data.link ? String(data.link) : undefined
58 }
59 })
60}
61
62export declare const data: Announcement[]
63
64export default {
65 watch: ['../post/*.md'],
66 load(): Announcement[] {
67 return loadAnnouncements()
68 }
69}