Commit b22f63de58

b22f63de58056b7a560d69f782a7354c33175c93

parent: 9fb795e3cb

Unsigned

Duck <57977673+woducku@users.noreply.github.com> · 2026-05-31 17:14 UTC

Update Search.vue

Layout: unified · split

docs/.vitepress/theme/components/Search.vue +167 −94
@@ -365,7 +365,82 @@ const mark = computedAsync(async () => {
365365 return markRaw(new Mark(resultsEl.value))
366366}, null)
367367
368const cache = new LRUCache<string, Map<string, string>>(16) // 16 files
368const cache = new LRUCache<string, Map<string, string>>(120)
369
370const inFlightExcerpts = new Map<string, Promise<void>>()
371
372const EAGER_EXCERPTS = 15
373
374function buildDocExcerpt(
375 docId: string,
376 filterTextValue: string
377): Promise<void> {
378 const cacheId = `${docId}\n${filterTextValue}`
379 if (cache.get(cacheId)) return Promise.resolve()
380 const pending = inFlightExcerpts.get(cacheId)
381 if (pending) return pending
382
383 const job = (async () => {
384 const { mod } = await fetchExcerpt(docId)
385 if (cache.get(cacheId)) return
386
387 const comp = (mod as any).default ?? mod
388 if (!(comp?.render || comp?.setup)) return // nothing renderable; don't cache
389
390 const map = new Map<string, string>()
391 const app = createApp(comp)
392 app.config.warnHandler = () => {}
393 enhanceAppWithTabs(app)
394 app.provide(dataSymbol, vitePressData)
395 Object.defineProperties(app.config.globalProperties, {
396 $frontmatter: {
397 get() {
398 return vitePressData.frontmatter.value
399 }
400 },
401 $params: {
402 get() {
403 return vitePressData.page.value.params
404 }
405 }
406 })
407 const div = document.createElement('div')
408 try {
409 app.mount(div)
410 await selectExcerptTabs(div, filterTextValue)
411 const headings = div.querySelectorAll('h1, h2, h3, h4, h5, h6')
412 headings.forEach((heading) => {
413 const href = heading.querySelector('a')?.getAttribute('href')
414 const anchor = href?.startsWith('#') && href.slice(1)
415 if (!anchor) return
416 let html = ''
417 let node = heading as Element
418 while (
419 (node = node.nextElementSibling!) &&
420 !/^h[1-6]$/i.test(node.tagName)
421 ) {
422 html += (node as HTMLElement).outerHTML
423 }
424 map.set(anchor, html)
425 })
426 } catch (e) {
427 console.error('[search] excerpt render failed for', docId, e)
428 } finally {
429 try {
430 app.unmount()
431 } catch {
432 /* ignore */
433 }
434 }
435 cache.set(cacheId, map)
436 })()
437
438 inFlightExcerpts.set(cacheId, job)
439 job.finally(() => {
440 if (inFlightExcerpts.get(cacheId) === job) inFlightExcerpts.delete(cacheId)
441 })
442 return job
443}
369444
370445watchDebounced(
371446 () => [searchIndex.value, filterText.value, showDetailedList.value, matchExact.value] as const,
@@ -384,119 +459,90 @@ watchDebounced(
384459
385460 // Dynamic search options based on matchExact toggle
386461 const dynamicSearchOptions = {
387 fuzzy: matchExactValue ? false : (0.07 as number | false),
462 fuzzy: matchExactValue ? false : (0.3 as number | false),
388463 prefix: matchExactValue ? false : (term: string) => term.length > 3,
389464 maxFuzzy: matchExactValue ? 0 : 1,
465 boost: { title: 10, titles: 4, text: 1 },
390466 }
391467
392468 // Search
393469 const ranked = index.search(filterTextValue, dynamicSearchOptions) as (SearchResult & Result)[]
394470
395 // Guaranteed heading matches: any section whose own heading (title)
396 // contains the term should always show, regardless of score or cap.
397 const titleHits = index.search(filterTextValue, {
398 ...dynamicSearchOptions,
399 fields: ['title']
400 }) as (SearchResult & Result)[]
401
402471 const top = ranked.slice(0, 50)
403472 const seen = new Set(top.map((r) => r.id))
404 const _result = [
405 ...top,
406 ...titleHits.filter((r) => !seen.has(r.id))
407 ] as (SearchResult & Result)[]
473 const titleHits = ranked.filter(
474 (r) => !seen.has(r.id) && r.match && Object.keys(r.match).length > 0
475 )
476 const _result = [...top, ...titleHits] as (SearchResult & Result)[]
408477 enableNoResults.value = true
409478
410 if (!_result) {
479 if (!_result.length) {
411480 results.value = []
412481 return
413482 }
414483
415 // Highlighting
416 const mods = showDetailedListValue
417 ? await Promise.all(_result.map((r) => fetchExcerpt(r.id)))
418 : []
419 if (canceled) return
420 for (const { id, mod } of mods) {
421 const mapId = id.slice(0, id.indexOf('#'))
422 const cacheId = `${mapId}\n${filterTextValue}`
423 let map = cache.get(cacheId)
424 if (map) continue
425 map = new Map()
426 cache.set(cacheId, map)
427 const comp = mod.default ?? mod
428 if (comp?.render || comp?.setup) {
429 const app = createApp(comp)
430 // Silence warnings about missing components
431 app.config.warnHandler = () => {}
432 enhanceAppWithTabs(app)
433 app.provide(dataSymbol, vitePressData)
434 Object.defineProperties(app.config.globalProperties, {
435 $frontmatter: {
436 get() {
437 return vitePressData.frontmatter.value
438 }
439 },
440 $params: {
441 get() {
442 return vitePressData.page.value.params
443 }
444 }
484 // Collect highlight terms up front (cheap — no rendering needed).
485 const terms = new Set<string>()
486 for (const r of _result) {
487 for (const term in r.match) terms.add(term)
488 }
489 currentTerms.value = terms
490
491 const toRows = (list: (SearchResult & Result)[]) =>
492 list
493 .map((r) => {
494 const [id, anchor] = r.id.split('#')
495 const map = cache.get(`${id}\n${filterTextValue}`)
496 return { ...r, text: map?.get(anchor) ?? '' }
497 })
498 .sort((a, b) => {
499 const pageDiff =
500 getPageOrder(getPageKey(a.id)) - getPageOrder(getPageKey(b.id))
501 if (pageDiff !== 0) return pageDiff
502 return getDocOrder(a.id) - getDocOrder(b.id)
445503 })
446 const div = document.createElement('div')
447 app.mount(div)
448 await selectExcerptTabs(div, filterTextValue)
449 const headings = div.querySelectorAll('h1, h2, h3, h4, h5, h6')
450 headings.forEach((el) => {
451 const href = el.querySelector('a')?.getAttribute('href')
452 const anchor = href?.startsWith('#') && href.slice(1)
453 if (!anchor) return
454 let html = ''
455 while (
456 (el = el.nextElementSibling!) &&
457 !/^h[1-6]$/i.test(el.tagName)
458 ) {
459 html += el.outerHTML
504
505 const highlight = () =>
506 new Promise<void>((resolve) => {
507 if (!terms.size || !mark.value) {
508 resolve()
509 return
510 }
511 mark.value.unmark({
512 done: () => {
513 mark.value?.markRegExp(formMarkRegex(terms), {
514 done: () => resolve()
515 })
460516 }
461 map!.set(anchor, html)
462517 })
463 app.unmount()
518 })
519
520 const docOrderList: string[] = []
521 const seenDocs = new Set<string>()
522 for (const r of _result) {
523 const docId = r.id.slice(0, r.id.indexOf('#'))
524 if (!seenDocs.has(docId)) {
525 seenDocs.add(docId)
526 docOrderList.push(docId)
464527 }
465 if (canceled) return
466528 }
467529
468 const terms = new Set<string>()
469
470 results.value = _result
471 .map((r) => {
472 const [id, anchor] = r.id.split('#')
473 const map = cache.get(`${id}\n${filterTextValue}`)
474 const text = map?.get(anchor) ?? ''
475 for (const term in r.match) {
476 terms.add(term)
477 }
478 return { ...r, text }
479 })
480 .sort((a, b) => {
481 const pageDiff =
482 getPageOrder(getPageKey(a.id)) - getPageOrder(getPageKey(b.id))
483 if (pageDiff !== 0) return pageDiff
484 return getDocOrder(a.id) - getDocOrder(b.id)
485 })
530 if (showDetailedListValue) {
531 const eagerDocs = new Set<string>()
532 for (const r of _result.slice(0, EAGER_EXCERPTS)) {
533 eagerDocs.add(r.id.slice(0, r.id.indexOf('#')))
534 }
535 await Promise.all(
536 [...eagerDocs].map((docId) => buildDocExcerpt(docId, filterTextValue))
537 )
538 if (canceled) return
539 }
486540
487 currentTerms.value = terms
541 results.value = toRows(_result)
488542
489543 await nextTick()
490544 if (canceled) return
491
492 await new Promise((r) => {
493 mark.value?.unmark({
494 done: () => {
495 mark.value?.markRegExp(formMarkRegex(terms), { done: r })
496 }
497 })
498 })
499
545 await highlight()
500546 await nextTick()
501547 await nextFrame()
502548 if (canceled) return
@@ -505,6 +551,30 @@ watchDebounced(
505551 resultsEl.value.scrollTop = 0
506552 }
507553 centerExcerptsUntilSettled()
554
555 if (showDetailedListValue) {
556 const built = new Set<string>()
557 for (const r of _result.slice(0, EAGER_EXCERPTS)) {
558 built.add(r.id.slice(0, r.id.indexOf('#')))
559 }
560 const remaining = docOrderList.filter((d) => !built.has(d))
561 if (remaining.length) {
562 for (const docId of remaining) {
563 await buildDocExcerpt(docId, filterTextValue)
564 if (canceled) return
565 await nextFrame()
566 if (canceled) return
567 }
568 results.value = toRows(_result)
569 await nextTick()
570 if (canceled) return
571 await highlight()
572 await nextTick()
573 await nextFrame()
574 if (canceled) return
575 centerExcerptsUntilSettled()
576 }
577 }
508578 },
509579 { debounce: 80, immediate: true }
510580)
@@ -551,18 +621,21 @@ onBeforeUnmount(() => {
551621 if (ribbonAnimHandle) cancelAnimationFrame(ribbonAnimHandle)
552622})
553623
554const excerptCache = new LRUCache<string, unknown>(60) // 60 excerpts
624const excerptCache = new LRUCache<string, unknown>(24)
555625
556626async function fetchExcerpt(id: string) {
557 const cache = excerptCache.get(id)
558 if (cache) return { id, mod: cache }
627 const hashIndex = id.indexOf('#')
628 const docId = hashIndex === -1 ? id : id.slice(0, hashIndex)
629
630 const cached = excerptCache.get(docId)
631 if (cached) return { id, mod: cached }
559632
560 const file = pathToFile(id.slice(0, id.indexOf('#')))
633 const file = pathToFile(docId)
561634 try {
562635 if (!file) throw new Error(`Cannot find file for id: ${id}`)
563636 const mod = await import(/*@vite-ignore*/ file)
564637
565 excerptCache.set(id, mod)
638 excerptCache.set(docId, mod)
566639
567640 return { id, mod }
568641 } catch (e) {