docs/.vitepress/configs/markdown/extRepoPlugin.ts
257 lines · 7287 bytes
10 symbols in this file
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
43import { parseExtRepoAttrs } from '../../../ext/extensionRepos/attrs'
44
45// Parser
46
47function isManualOrder(attrs: Record<string, string>): boolean {
48 if (attrs.order !== undefined) return attrs.order === 'manual'
49 const manual = attrs.manual?.toLowerCase()
50 return manual === 'true' || manual === '1'
51}
52
53const FIELD_KEYS = new Set([
54 'url',
55 'src',
56 'raw',
57 'note',
58 'manga',
59 'anime',
60 'novel',
61 'data'
62])
63
64function parseEntries(bodyLines: string[]): ParsedRepoEntry[] {
65 const entries: ParsedRepoEntry[] = []
66 let current: ParsedRepoEntry | null = null
67 let currentBuild: ParsedRepoBuild | null = null
68
69 for (const rawLine of bodyLines) {
70 const line = rawLine.trim()
71 if (!line) continue
72
73 const headingMatch = line.match(/^==\s+(.+)$/)
74 if (headingMatch) {
75 if (current) entries.push(current)
76 current = { name: headingMatch[1].trim() }
77 currentBuild = null
78 continue
79 }
80
81 const buildMatch = line.match(/^--\s+(.+)$/)
82 if (buildMatch && current) {
83 currentBuild = { label: buildMatch[1].trim() }
84 current.builds ??= []
85 current.builds.push(currentBuild)
86 continue
87 }
88
89 const fieldMatch = line.match(/^-\s*([a-zA-Z]+)\s*:\s*(.+)$/)
90 if (fieldMatch && current) {
91 const key = fieldMatch[1].toLowerCase()
92 const value = fieldMatch[2].trim()
93 if (currentBuild) {
94 if (key === 'raw') currentBuild.raw = value
95 continue
96 }
97 if (FIELD_KEYS.has(key)) {
98 current[
99 key as
100 | 'url'
101 | 'src'
102 | 'raw'
103 | 'note'
104 | 'manga'
105 | 'anime'
106 | 'novel'
107 | 'data'
108 ] = value
109 }
110 }
111 }
112 if (current) entries.push(current)
113
114 return entries
115}
116
117function nameMarkdown(entry: ParsedRepoEntry): string {
118 const label = entry.url ? `[${entry.name}](${entry.url})` : entry.name
119 return entry.src ? `${label} [:src:](${entry.src})` : label
120}
121
122function buildVariants(
123 entry: ParsedRepoEntry
124): ParsedRepoVariant[] | undefined {
125 const typeCount =
126 [entry.manga, entry.anime, entry.novel].filter(Boolean).length
127 if (typeCount === 0) return undefined
128
129 const variants: ParsedRepoVariant[] = []
130 if (typeCount > 1) {
131 variants.push({
132 label: 'All-in-One',
133 mangaUrl: entry.manga,
134 animeUrl: entry.anime,
135 novelUrl: entry.novel
136 })
137 }
138 if (entry.manga) variants.push({ label: 'Manga', mangaUrl: entry.manga })
139 if (entry.anime) variants.push({ label: 'Anime', animeUrl: entry.anime })
140 if (entry.novel) variants.push({ label: 'Novel', novelUrl: entry.novel })
141 return variants
142}
143
144// Plugin
145
146export function extRepoPlugin(md: MarkdownIt): void {
147 const MARKER = ':'
148 const MIN_MARKERS = 3
149 const NAME = 'extrepo'
150
151 md.block.ruler.before(
152 'fence',
153 'ext_repo',
154 (state, startLine, endLine, silent) => {
155 let pos = state.bMarks[startLine] + state.tShift[startLine]
156 let max = state.eMarks[startLine]
157
158 let markerCount = 0
159 while (pos < max && state.src[pos] === MARKER) {
160 pos++
161 markerCount++
162 }
163 if (markerCount < MIN_MARKERS) return false
164
165 const params = state.src.slice(pos, max).trim()
166 if (!params.toLowerCase().startsWith(NAME)) return false
167
168 if (silent) return true
169
170 let nextLine = startLine + 1
171 let found = false
172 while (nextLine < endLine) {
173 let p = state.bMarks[nextLine] + state.tShift[nextLine]
174 const m = state.eMarks[nextLine]
175 if (p < m && state.sCount[nextLine] < state.blkIndent) break
176
177 let cnt = 0
178 while (p < m && state.src[p] === MARKER) {
179 p++
180 cnt++
181 }
182 if (cnt >= markerCount && state.src.slice(p, m).trim() === '') {
183 found = true
184 break
185 }
186 nextLine++
187 }
188
189 const bodyLines: string[] = []
190 for (let i = startLine + 1; i < nextLine; i++) {
191 bodyLines.push(state.src.slice(state.bMarks[i], state.eMarks[i]))
192 }
193
194 const attrs = parseExtRepoAttrs(params)
195 const scheme = attrs.scheme || 'mihon'
196 const from = attrs.from
197 const manualAttr = isManualOrder(attrs) ? ' manual' : ''
198
199 const rows: ParsedRepoRow[] = []
200 for (const entry of parseEntries(bodyLines)) {
201 const name = md.renderInline(nameMarkdown(entry), state.env)
202 const note = entry.note ? md.render(entry.note) : undefined
203
204 // Grouped entries (e.g. several unrelated Kotatsu forks bundled under one row)
205 // carry a list of arbitrary-labeled `-- Label` / `raw:` sub-entries. Reuses the
206 // variant rendering (nested, independently collapsible rows) but with no
207 // combined/"All-in-One" header, since these builds have nothing in common to combine.
208 if (entry.builds?.length) {
209 const groupVariants: ParsedRepoVariant[] = entry.builds
210 .filter((b): b is Required<ParsedRepoBuild> => Boolean(b.raw))
211 .map(b => ({ label: b.label, mangaUrl: b.raw }))
212 if (groupVariants.length) {
213 rows.push({
214 name,
215 indexUrl: groupVariants[0].mangaUrl!,
216 note,
217 data: entry.data,
218 variants: groupVariants
219 })
220 }
221 continue
222 }
223
224 // Multi-json entries (e.g. mangayomi) carry manga/anime/novel index urls instead
225 // of a single `raw` field — they render as a nested list of install variants.
226 const variants = buildVariants(entry)
227 if (variants) {
228 rows.push({
229 name,
230 indexUrl: entry.manga ?? entry.anime ?? entry.novel ?? '',
231 note,
232 repoName: entry.name,
233 repoUrl: entry.url,
234 variants,
235 data: entry.data
236 })
237 continue
238 }
239
240 if (!entry.raw) continue
241 rows.push({ name, indexUrl: entry.raw, note, data: entry.data })
242 }
243
244 const reposJson = JSON.stringify(rows).replace(/'/g, ''')
245 const fromAttr = from ? ` from="${from.replace(/"/g, '"')}"` : ''
246
247 const token = state.push('html_block', '', 0)
248 token.map = [startLine, nextLine]
249 token.content =
250 `<ExtensionRepos scheme="${scheme}"${fromAttr}${manualAttr} :repos='${reposJson}' />\n`
251
252 state.line = found ? nextLine + 1 : nextLine
253 return true
254 },
255 { alt: ['paragraph', 'reference', 'blockquote', 'list'] }
256 )
257}