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