Commit e1e52c333f

e1e52c333f1b7f88f53ba77c864bc8ef20e8e047

parent: 5330410431

Unsigned

Duck <57977673+woducku@users.noreply.github.com> · 2026-06-03 04:16 UTC

chore

Layout: unified · split

docs/.vitepress/configs/index.ts +6 −9
@@ -17,12 +17,11 @@ import { hostname, sidebar, siteConfig } from './constants'
17import { generateImages, generateMeta } from './hooks' 17import { generateImages, generateMeta } from './hooks'
18import { configureMarkdown } from './markdown' 18import { configureMarkdown } from './markdown'
19import { aliases, defs, movePlugin } from './markdown/emoji' 19import { aliases, defs, movePlugin } from './markdown/emoji'
20import { collectPageLinks, writeUrlSearchIndex } from '../plugins/urlSearchPlugin'
20 21
21const GIT_COMMIT = process.env.NODE_ENV === 'development' 22const GIT_COMMIT = process.env.NODE_ENV === 'development'
22 ? 'dev' 23 ? 'dev'
23 /** Github actions commit hash */
24 : (process.env.GITHUB_SHA ?? 24 : (process.env.GITHUB_SHA ??
25 /** Commit hash from git */
26 (await (await import('tinyexec')) 25 (await (await import('tinyexec'))
27 .x('git', ['rev-parse', 'HEAD']) 26 .x('git', ['rev-parse', 'HEAD'])
28 .then((result) => result.stdout.trim())) ?? 27 .then((result) => result.stdout.trim())) ??
@@ -31,7 +30,11 @@ const GIT_COMMIT = process.env.NODE_ENV === 'development'
31export const shared: UserConfig<DefaultTheme.Config> = { 30export const shared: UserConfig<DefaultTheme.Config> = {
32 ...siteConfig, 31 ...siteConfig,
33 transformHead: async (context) => generateMeta(context, hostname), 32 transformHead: async (context) => generateMeta(context, hostname),
33 transformHtml: async (html, _id, ctx) => {
34 collectPageLinks(html, ctx.page)
35 },
34 buildEnd: async (context) => { 36 buildEnd: async (context) => {
37 writeUrlSearchIndex(context.outDir)
35 if (process.env.CI) { 38 if (process.env.CI) {
36 await generateImages(context) 39 await generateImages(context)
37 } 40 }
@@ -58,12 +61,10 @@ export const shared: UserConfig<DefaultTheme.Config> = {
58 const titles = (storedFields?.titles as string[]) 61 const titles = (storedFields?.titles as string[])
59 .filter((t) => Boolean(t)) 62 .filter((t) => Boolean(t))
60 .map((t) => t.toLowerCase()) 63 .map((t) => t.toLowerCase())
61 // Uprate if term appears in titles. Add bonus for higher levels (i.e. lower index)
62 const titleIndex = titles 64 const titleIndex = titles
63 .map((t, i) => (t?.includes(term) ? i : -1)) 65 .map((t, i) => (t?.includes(term) ? i : -1))
64 .find((i) => i >= 0) ?? -1 66 .find((i) => i >= 0) ?? -1
65 if (titleIndex >= 0) return 10000 - titleIndex 67 if (titleIndex >= 0) return 10000 - titleIndex
66
67 return 1 68 return 1
68 } 69 }
69 } 70 }
@@ -74,7 +75,6 @@ export const shared: UserConfig<DefaultTheme.Config> = {
74 }, 75 },
75 logo: { src: '/asset/fav.svg' }, 76 logo: { src: '/asset/fav.svg' },
76 sidebar, 77 sidebar,
77 // nav,
78 socialLinks: [ 78 socialLinks: [
79 { icon: 'github', link: 'https://github.com/wotakumoe/Wotaku' }, 79 { icon: 'github', link: 'https://github.com/wotakumoe/Wotaku' },
80 { icon: 'discord', link: 'https://discord.gg/vShRGx8ZBC' } 80 { icon: 'discord', link: 'https://discord.gg/vShRGx8ZBC' }
@@ -82,10 +82,7 @@ export const shared: UserConfig<DefaultTheme.Config> = {
82 footer: { 82 footer: {
83 message: 83 message:
84 `<a href="https://github.com/wotakumoe">The Wotaku Team</a> <span class="divider">|</span> <a href="https://github.com/wotakumoe/Wotaku/commit/${GIT_COMMIT}">${ 84 `<a href="https://github.com/wotakumoe">The Wotaku Team</a> <span class="divider">|</span> <a href="https://github.com/wotakumoe/Wotaku/commit/${GIT_COMMIT}">${
85 GIT_COMMIT.slice( 85 GIT_COMMIT.slice(0, 7)
86 0,
87 7
88 )
89 }</a>`, 86 }</a>`,
90 copyright: 'made with love and eepy energy' 87 copyright: 'made with love and eepy energy'
91 } 88 }
docs/.vitepress/plugins/urlSearchPlugin.ts added +93
@@ -0,0 +1,93 @@
1import { writeFileSync } from 'node:fs'
2import { join } from 'node:path'
3
4export interface PageLink {
5 href: string
6 linkText: string
7 pageId: string
8 anchor: string
9 titles: string[]
10}
11
12function stripTags(html: string): string {
13 return html.replace(/<[^>]*>/g, ' ').replace(/\s+/g, ' ').trim()
14}
15
16function decodeEntities(s: string): string {
17 return s
18 .replace(/&amp;/g, '&')
19 .replace(/&lt;/g, '<')
20 .replace(/&gt;/g, '>')
21 .replace(/&quot;/g, '"')
22 .replace(/&#39;/g, "'")
23}
24
25function extractLinks(html: string, pageId: string): PageLink[] {
26 const results: PageLink[] = []
27 const seen = new Set<string>()
28 const headingStack: string[] = []
29 let currentAnchor = ''
30
31 const tagRE = /<(h[1-6]|a)\b([^>]*)>([^<]*)/gi
32 let m: RegExpExecArray | null
33
34 while ((m = tagRE.exec(html)) !== null) {
35 const [, tag, attrs, text] = m
36 const tagLower = tag.toLowerCase()
37
38 if (/^h[1-6]$/.test(tagLower)) {
39 const level = parseInt(tagLower[1]) - 1
40 const idMatch = attrs.match(/\bid=["']([^"']*)["']/)
41 if (idMatch) currentAnchor = idMatch[1]
42 const rest = html.slice(tagRE.lastIndex)
43 const closeIdx = rest.search(new RegExp(`</${tagLower}>`, 'i'))
44 const headingHtml = text + (closeIdx >= 0 ? rest.slice(0, closeIdx) : '')
45 headingStack[level] = decodeEntities(stripTags(headingHtml))
46 headingStack.length = level + 1
47 continue
48 }
49
50 if (tagLower === 'a') {
51 const hrefMatch = attrs.match(/\bhref=["']([^"']*)["']/)
52 if (!hrefMatch) continue
53 const href = decodeEntities(hrefMatch[1])
54 if (!/^https?:\/\//i.test(href)) continue
55 const key = href + '\x00' + currentAnchor
56 if (seen.has(key)) continue
57 seen.add(key)
58 const rest = html.slice(tagRE.lastIndex)
59 const closeIdx = rest.search(/<\/a>/i)
60 const linkHtml = text + (closeIdx >= 0 ? rest.slice(0, closeIdx) : '')
61 results.push({
62 href,
63 linkText: decodeEntities(stripTags(linkHtml)),
64 pageId,
65 anchor: currentAnchor,
66 titles: headingStack.filter(Boolean)
67 })
68 }
69 }
70
71 return results
72}
73
74const collected: PageLink[] = []
75
76export function collectPageLinks(html: string, page: string) {
77 // page is like "anime/watching.md" (relative to srcDir)
78 const pageId = '/' + page.replace(/\.md$/, '').replace(/\/index$/, '/')
79 collected.push(...extractLinks(html, pageId))
80}
81
82export function writeUrlSearchIndex(outDir: string) {
83 const seen = new Set<string>()
84 const deduped = collected.filter((l) => {
85 const key = l.href + '\x00' + l.pageId + '\x00' + l.anchor
86 if (seen.has(key)) return false
87 seen.add(key)
88 return true
89 })
90 const outPath = join(outDir, 'url-search-index.json')
91 writeFileSync(outPath, JSON.stringify(deduped), 'utf-8')
92 console.log(`[url-search] wrote ${deduped.length} links → ${outPath}`)
93}\ No newline at end of file
docs/.vitepress/theme/components/Search.vue +18 −151
@@ -1,9 +1,8 @@
1<script lang="ts" setup> 1<script lang="ts" setup>
2import MiniSearch, { type SearchResult } from 'minisearch' 2import MiniSearch, { type SearchResult } from 'minisearch'
3import { type DefaultTheme, dataSymbol, inBrowser, useRouter } from 'vitepress' 3import { type DefaultTheme, inBrowser, useRouter } from 'vitepress'
4import { 4import {
5 computed, 5 computed,
6 createApp,
7 markRaw, 6 markRaw,
8 nextTick, 7 nextTick,
9 onBeforeUnmount, 8 onBeforeUnmount,
@@ -51,6 +50,7 @@ import {
51import Mark from 'mark.js/dist/mark.es6.js' 50import Mark from 'mark.js/dist/mark.es6.js'
52import { enhanceAppWithTabs } from 'vitepress-plugin-tabs/client' 51import { enhanceAppWithTabs } from 'vitepress-plugin-tabs/client'
53import { LRUCache } from '../composables/search/lru-cache' 52import { LRUCache } from '../composables/search/lru-cache'
53import type { PageLink } from '../../plugins/urlSearchPlugin'
54import { createSearchTranslate } from '../composables/search/translation' 54import { createSearchTranslate } from '../composables/search/translation'
55import { useData } from '../composables/search/use-data' 55import { useData } from '../composables/search/use-data'
56import { sidebar } from '../../configs/constants' 56import { sidebar } from '../../configs/constants'
@@ -163,162 +163,29 @@ function cycleSearchMode() {
163const matchExact = computed(() => searchMode.value === 'exact') 163const matchExact = computed(() => searchMode.value === 'exact')
164const urlSearchMode = computed(() => searchMode.value === 'url') 164const urlSearchMode = computed(() => searchMode.value === 'url')
165 165
166interface PageLink {
167 href: string
168 linkText: string
169 pageId: string
170 anchor: string
171 titles: string[] // heading breadcrumb e.g. ["Manga", "Online"]
172}
173
174// allLinks is built lazily the first time URL mode is activated, then cached.
175// We store the result in a module-level variable so it survives across reactive
176// re-runs (searchIndex changes are rare; a full rebuild would remount every page).
177let allLinksCache: PageLink[] | null = null
178let allLinksBuildPromise: Promise<PageLink[]> | null = null
179
180async function buildAllLinks(index: any, vitePressData: any): Promise<PageLink[]> {
181 // Collect unique page-level doc ids (strip anchors)
182 const pageIds = new Set<string>()
183 const docIds = index._documentIds
184 if (docIds instanceof Map) {
185 for (const id of docIds.values()) pageIds.add(String(id).split('#')[0])
186 } else if (docIds && typeof docIds === 'object') {
187 for (const k of Object.keys(docIds)) pageIds.add(String((docIds as any)[k]).split('#')[0])
188 }
189
190 const collected: PageLink[] = []
191
192 for (const pageId of pageIds) {
193 try {
194 const file = pathToFile(pageId)
195 if (!file) continue
196 const mod = await import(/*@vite-ignore*/ file)
197 const comp = (mod as any).default ?? mod
198 if (!(comp?.render || comp?.setup)) continue
199
200 const app = createApp(comp)
201 app.config.warnHandler = () => {}
202 enhanceAppWithTabs(app)
203 app.provide(dataSymbol, vitePressData)
204 Object.defineProperties(app.config.globalProperties, {
205 $frontmatter: { get() { return vitePressData.frontmatter.value } },
206 $params: { get() { return vitePressData.page.value.params } }
207 })
208 const div = document.createElement('div')
209 const seenOnPage = new Set<string>()
210
211 // Collect links visible right now in the DOM
212 // heading stack: index = heading level - 1, value = heading text
213 const headingStack: string[] = []
214 const currentAnchor = { v: '' }
215
216 const scrapeLinks = () => {
217 const walker = document.createTreeWalker(div, NodeFilter.SHOW_ELEMENT)
218 let node: Element | null = div
219 while ((node = walker.nextNode() as Element | null)) {
220 const m = node.tagName.match(/^h([1-6])$/i)
221 if (m) {
222 const level = parseInt(m[1]) - 1
223 // Strip icon HTML, keep text only
224 const text = (node as HTMLElement).innerText?.trim()
225 ?? node.textContent?.trim() ?? ''
226 headingStack[level] = text
227 // Clear deeper levels
228 headingStack.length = level + 1
229 const ha = node.querySelector('a[href^="#"]')
230 if (ha) { const h = ha.getAttribute('href')!.slice(1); if (h) currentAnchor.v = h }
231 } else if (node.tagName === 'A') {
232 const href = node.getAttribute('href') ?? ''
233 if (/^https?:\/\//i.test(href)) {
234 const key = href + '\x00' + currentAnchor.v
235 if (!seenOnPage.has(key)) {
236 seenOnPage.add(key)
237 // titles = all heading levels above the link, filtering empty slots
238 const titles = headingStack.filter(Boolean)
239 collected.push({ href, linkText: node.textContent?.trim() ?? '', pageId, anchor: currentAnchor.v, titles })
240 }
241 }
242 }
243 }
244 }
245
246 try {
247 app.mount(div)
248 div.querySelectorAll('details').forEach((d) => { d.open = true })
249 div.querySelectorAll<HTMLElement>('[style*="display: none"],[style*="display:none"]')
250 .forEach((el) => { el.style.display = '' })
251
252 const raf = () => new Promise<void>(r => requestAnimationFrame(() => r()))
253 const tabGroups = div.querySelectorAll<HTMLElement>('.plugin-tabs')
254
255 if (tabGroups.length === 0) {
256 scrapeLinks()
257 } else {
258 // First pass: scrape non-tab content (anchors from headings outside tabs)
259 scrapeLinks()
260 // Then expose every tab panel
261 for (const tabGroup of Array.from(tabGroups)) {
262 const buttons = tabGroup.querySelectorAll<HTMLButtonElement>('.plugin-tabs--tab[role="tab"]')
263 for (const button of Array.from(buttons)) {
264 button.click()
265 await nextTick()
266 await raf()
267 scrapeLinks(anchor)
268 }
269 }
270 }
271 } finally {
272 try { app.unmount() } catch { /* ignore */ }
273 }
274 } catch { /* skip unrenderable pages */ }
275 }
276
277 // Sort by sidebar page order once so urlResults doesn't need to re-sort on every keypress
278 collected.sort((a, b) => {
279 const pa = pageMeta.get(a.pageId)?.order ?? Number.MAX_SAFE_INTEGER
280 const pb = pageMeta.get(b.pageId)?.order ?? Number.MAX_SAFE_INTEGER
281 return pa - pb
282 })
283 return collected
284}
285
286// Lazy ref — null until URL mode is first used
287const allLinks = shallowRef<PageLink[]>([]) 166const allLinks = shallowRef<PageLink[]>([])
288let allLinksIndexVersion: any = null // track which index version we built for 167let allLinksFetchPromise: Promise<void> | null = null
289 168
290async function ensureAllLinks() { 169async function ensureAllLinks() {
291 const index = searchIndex.value as any 170 if (allLinks.value.length > 0) return
292 if (!index) return 171 if (allLinksFetchPromise) { await allLinksFetchPromise; return }
293 // Rebuild if the index changed (e.g. HMR) 172 allLinksFetchPromise = fetch('/url-search-index.json')
294 if (allLinksCache && allLinksIndexVersion === index) { 173 .then((r) => r.json())
295 allLinks.value = allLinksCache 174 .then((data: PageLink[]) => {
296 return 175 data.sort((a, b) => {
297 } 176 const pa = pageMeta.get(a.pageId)?.order ?? Number.MAX_SAFE_INTEGER
298 if (allLinksBuildPromise) { 177 const pb = pageMeta.get(b.pageId)?.order ?? Number.MAX_SAFE_INTEGER
299 allLinks.value = await allLinksBuildPromise 178 return pa - pb
300 return 179 })
301 } 180 allLinks.value = data
302 allLinksBuildPromise = buildAllLinks(index, vitePressData) 181 })
303 const result = await allLinksBuildPromise 182 .catch(() => { allLinks.value = [] })
304 allLinksCache = result 183 .finally(() => { allLinksFetchPromise = null })
305 allLinksIndexVersion = index 184 await allLinksFetchPromise
306 allLinksBuildPromise = null
307 allLinks.value = result
308} 185}
309 186
310// Kick off link scraping the moment URL mode is activated (lazy, once)
311watch(urlSearchMode, (active) => { if (active) ensureAllLinks() }, { immediate: true }) 187watch(urlSearchMode, (active) => { if (active) ensureAllLinks() }, { immediate: true })
312 188
313// If the search index changes (HMR rebuild), invalidate the link cache
314watch(searchIndex, () => {
315 allLinksCache = null
316 allLinksBuildPromise = null
317 allLinksIndexVersion = null
318 allLinks.value = []
319 if (urlSearchMode.value) ensureAllLinks()
320})
321
322interface UrlResult { 189interface UrlResult {
323 href: string 190 href: string
324 linkText: string 191 linkText: string