docs/.vitepress/configs/markdown/extRepoPlugin.ts
218 lines · 6848 bytes
1import type MarkdownIt from 'markdown-it'
2
3// Types
4
5interface ParsedRepoVariant {
6 label: string
7 mangaUrl?: string
8 animeUrl?: string
9 novelUrl?: string
10}
11
12interface ParsedRepoRow {
13 name: string
14 indexUrl: string
15 note?: string
16 repoName?: string
17 repoUrl?: string
18 variants?: ParsedRepoVariant[]
19 data?: string
20}
21
22interface ParsedRepoBuild {
23 label: string
24 raw?: string
25}
26
27interface ParsedRepoEntry {
28 name: string
29 url?: string
30 src?: string
31 raw?: string
32 note?: string
33 manga?: string
34 anime?: string
35 novel?: string
36 data?: string
37 // Arbitrary named sub-entries under a `-- Label` line (e.g. several unrelated forks
38 // grouped under one row), as opposed to `manga`/`anime`/`novel` which are fixed content-
39 // type variants of a single project (see buildVariants below).
40 builds?: ParsedRepoBuild[]
41}
42
43// Parser
44
45function parseAttrs(info: string): Record<string, string> {
46 const match = info.match(/\{([^}]*)\}/)
47 if (!match) return {}
48 const attrs: Record<string, string> = {}
49 for (const pair of match[1].split(/\s+/).filter(Boolean)) {
50 const [key, value] = pair.split('=')
51 if (key && value) attrs[key] = value.replace(/^["']|["']$/g, '')
52 }
53 return attrs
54}
55
56const FIELD_KEYS = new Set(['url', 'src', 'raw', 'note', 'manga', 'anime', 'novel', 'data'])
57
58function parseEntries(bodyLines: string[]): ParsedRepoEntry[] {
59 const entries: ParsedRepoEntry[] = []
60 let current: ParsedRepoEntry | null = null
61 let currentBuild: ParsedRepoBuild | null = null
62
63 for (const rawLine of bodyLines) {
64 const line = rawLine.trim()
65 if (!line) continue
66
67 const headingMatch = line.match(/^==\s+(.+)$/)
68 if (headingMatch) {
69 if (current) entries.push(current)
70 current = { name: headingMatch[1].trim() }
71 currentBuild = null
72 continue
73 }
74
75 const buildMatch = line.match(/^--\s+(.+)$/)
76 if (buildMatch && current) {
77 currentBuild = { label: buildMatch[1].trim() }
78 current.builds ??= []
79 current.builds.push(currentBuild)
80 continue
81 }
82
83 const fieldMatch = line.match(/^-\s*([a-zA-Z]+)\s*:\s*(.+)$/)
84 if (fieldMatch && current) {
85 const key = fieldMatch[1].toLowerCase()
86 const value = fieldMatch[2].trim()
87 if (currentBuild) {
88 if (key === 'raw') currentBuild.raw = value
89 continue
90 }
91 if (FIELD_KEYS.has(key)) current[key as 'url' | 'src' | 'raw' | 'note' | 'manga' | 'anime' | 'novel' | 'data'] = value
92 }
93 }
94 if (current) entries.push(current)
95
96 return entries
97}
98
99function nameMarkdown(entry: ParsedRepoEntry): string {
100 const label = entry.url ? `[${entry.name}](${entry.url})` : entry.name
101 return entry.src ? `${label} [:src:](${entry.src})` : label
102}
103
104function buildVariants(entry: ParsedRepoEntry): ParsedRepoVariant[] | undefined {
105 const typeCount = [entry.manga, entry.anime, entry.novel].filter(Boolean).length
106 if (typeCount === 0) return undefined
107
108 const variants: ParsedRepoVariant[] = []
109 if (typeCount > 1) {
110 variants.push({ label: 'All-in-One', mangaUrl: entry.manga, animeUrl: entry.anime, novelUrl: entry.novel })
111 }
112 if (entry.manga) variants.push({ label: 'Manga', mangaUrl: entry.manga })
113 if (entry.anime) variants.push({ label: 'Anime', animeUrl: entry.anime })
114 if (entry.novel) variants.push({ label: 'Novel', novelUrl: entry.novel })
115 return variants
116}
117
118// Plugin
119
120export function extRepoPlugin(md: MarkdownIt): void {
121 const MARKER = ':'
122 const MIN_MARKERS = 3
123 const NAME = 'extrepo'
124
125 md.block.ruler.before(
126 'fence',
127 'ext_repo',
128 (state, startLine, endLine, silent) => {
129 let pos = state.bMarks[startLine] + state.tShift[startLine]
130 let max = state.eMarks[startLine]
131
132 let markerCount = 0
133 while (pos < max && state.src[pos] === MARKER) {
134 pos++
135 markerCount++
136 }
137 if (markerCount < MIN_MARKERS) return false
138
139 const params = state.src.slice(pos, max).trim()
140 if (!params.toLowerCase().startsWith(NAME)) return false
141
142 if (silent) return true
143
144 let nextLine = startLine + 1
145 let found = false
146 while (nextLine < endLine) {
147 let p = state.bMarks[nextLine] + state.tShift[nextLine]
148 const m = state.eMarks[nextLine]
149 if (p < m && state.sCount[nextLine] < state.blkIndent) break
150
151 let cnt = 0
152 while (p < m && state.src[p] === MARKER) { p++; cnt++ }
153 if (cnt >= markerCount && state.src.slice(p, m).trim() === '') {
154 found = true
155 break
156 }
157 nextLine++
158 }
159
160 const bodyLines: string[] = []
161 for (let i = startLine + 1; i < nextLine; i++) {
162 bodyLines.push(state.src.slice(state.bMarks[i], state.eMarks[i]))
163 }
164
165 const attrs = parseAttrs(params)
166 const scheme = attrs.scheme || 'mihon'
167
168 const rows: ParsedRepoRow[] = []
169 for (const entry of parseEntries(bodyLines)) {
170 const name = md.renderInline(nameMarkdown(entry), state.env)
171 const note = entry.note ? md.render(entry.note) : undefined
172
173 // Grouped entries (e.g. several unrelated Kotatsu forks bundled under one row)
174 // carry a list of arbitrary-labeled `-- Label` / `raw:` sub-entries. Reuses the
175 // variant rendering (nested, independently collapsible rows) but with no
176 // combined/"All-in-One" header, since these builds have nothing in common to combine.
177 if (entry.builds?.length) {
178 const groupVariants: ParsedRepoVariant[] = entry.builds
179 .filter((b): b is Required<ParsedRepoBuild> => Boolean(b.raw))
180 .map(b => ({ label: b.label, mangaUrl: b.raw }))
181 if (groupVariants.length) {
182 rows.push({ name, indexUrl: groupVariants[0].mangaUrl!, note, data: entry.data, variants: groupVariants })
183 }
184 continue
185 }
186
187 // Multi-json entries (e.g. mangayomi) carry manga/anime/novel index urls instead
188 // of a single `raw` field — they render as a nested list of install variants.
189 const variants = buildVariants(entry)
190 if (variants) {
191 rows.push({
192 name,
193 indexUrl: entry.manga ?? entry.anime ?? entry.novel ?? '',
194 note,
195 repoName: entry.name,
196 repoUrl: entry.url,
197 variants,
198 data: entry.data
199 })
200 continue
201 }
202
203 if (!entry.raw) continue
204 rows.push({ name, indexUrl: entry.raw, note, data: entry.data })
205 }
206
207 const reposJson = JSON.stringify(rows).replace(/'/g, ''')
208
209 const token = state.push('html_block', '', 0)
210 token.map = [startLine, nextLine]
211 token.content = `<ExtensionRepos scheme="${scheme}" :repos='${reposJson}' />\n`
212
213 state.line = found ? nextLine + 1 : nextLine
214 return true
215 },
216 { alt: ['paragraph', 'reference', 'blockquote', 'list'] }
217 )
218}