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 () => {
365 return markRaw(new Mark(resultsEl.value)) 365 return markRaw(new Mark(resultsEl.value))
366}, null) 366}, null)
367 367
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}
369 444
370watchDebounced( 445watchDebounced(
371 () => [searchIndex.value, filterText.value, showDetailedList.value, matchExact.value] as const, 446 () => [searchIndex.value, filterText.value, showDetailedList.value, matchExact.value] as const,
@@ -384,119 +459,90 @@ watchDebounced(
384 459
385 // Dynamic search options based on matchExact toggle 460 // Dynamic search options based on matchExact toggle
386 const dynamicSearchOptions = { 461 const dynamicSearchOptions = {
387 fuzzy: matchExactValue ? false : (0.07 as number | false), 462 fuzzy: matchExactValue ? false : (0.3 as number | false),
388 prefix: matchExactValue ? false : (term: string) => term.length > 3, 463 prefix: matchExactValue ? false : (term: string) => term.length > 3,
389 maxFuzzy: matchExactValue ? 0 : 1, 464 maxFuzzy: matchExactValue ? 0 : 1,
465 boost: { title: 10, titles: 4, text: 1 },
390 } 466 }
391 467
392 // Search 468 // Search
393 const ranked = index.search(filterTextValue, dynamicSearchOptions) as (SearchResult & Result)[] 469 const ranked = index.search(filterTextValue, dynamicSearchOptions) as (SearchResult & Result)[]
394 470
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
402 const top = ranked.slice(0, 50) 471 const top = ranked.slice(0, 50)
403 const seen = new Set(top.map((r) => r.id)) 472 const seen = new Set(top.map((r) => r.id))
404 const _result = [ 473 const titleHits = ranked.filter(
405 ...top, 474 (r) => !seen.has(r.id) && r.match && Object.keys(r.match).length > 0
406 ...titleHits.filter((r) => !seen.has(r.id)) 475 )
407 ] as (SearchResult & Result)[] 476 const _result = [...top, ...titleHits] as (SearchResult & Result)[]
408 enableNoResults.value = true 477 enableNoResults.value = true
409 478
410 if (!_result) { 479 if (!_result.length) {
411 results.value = [] 480 results.value = []
412 return 481 return
413 } 482 }
414 483
415 // Highlighting 484 // Collect highlight terms up front (cheap — no rendering needed).
416 const mods = showDetailedListValue 485 const terms = new Set<string>()
417 ? await Promise.all(_result.map((r) => fetchExcerpt(r.id))) 486 for (const r of _result) {
418 : [] 487 for (const term in r.match) terms.add(term)
419 if (canceled) return 488 }
420 for (const { id, mod } of mods) { 489 currentTerms.value = terms
421 const mapId = id.slice(0, id.indexOf('#')) 490
422 const cacheId = `${mapId}\n${filterTextValue}` 491 const toRows = (list: (SearchResult & Result)[]) =>
423 let map = cache.get(cacheId) 492 list
424 if (map) continue 493 .map((r) => {
425 map = new Map() 494 const [id, anchor] = r.id.split('#')
426 cache.set(cacheId, map) 495 const map = cache.get(`${id}\n${filterTextValue}`)
427 const comp = mod.default ?? mod 496 return { ...r, text: map?.get(anchor) ?? '' }
428 if (comp?.render || comp?.setup) { 497 })
429 const app = createApp(comp) 498 .sort((a, b) => {
430 // Silence warnings about missing components 499 const pageDiff =
431 app.config.warnHandler = () => {} 500 getPageOrder(getPageKey(a.id)) - getPageOrder(getPageKey(b.id))
432 enhanceAppWithTabs(app) 501 if (pageDiff !== 0) return pageDiff
433 app.provide(dataSymbol, vitePressData) 502 return getDocOrder(a.id) - getDocOrder(b.id)
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 }
445 }) 503 })
446 const div = document.createElement('div') 504
447 app.mount(div) 505 const highlight = () =>
448 await selectExcerptTabs(div, filterTextValue) 506 new Promise<void>((resolve) => {
449 const headings = div.querySelectorAll('h1, h2, h3, h4, h5, h6') 507 if (!terms.size || !mark.value) {
450 headings.forEach((el) => { 508 resolve()
451 const href = el.querySelector('a')?.getAttribute('href') 509 return
452 const anchor = href?.startsWith('#') && href.slice(1) 510 }
453 if (!anchor) return 511 mark.value.unmark({
454 let html = '' 512 done: () => {
455 while ( 513 mark.value?.markRegExp(formMarkRegex(terms), {
456 (el = el.nextElementSibling!) && 514 done: () => resolve()
457 !/^h[1-6]$/i.test(el.tagName) 515 })
458 ) {
459 html += el.outerHTML
460 } 516 }
461 map!.set(anchor, html)
462 }) 517 })
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)
464 } 527 }
465 if (canceled) return
466 } 528 }
467 529
468 const terms = new Set<string>() 530 if (showDetailedListValue) {
469 531 const eagerDocs = new Set<string>()
470 results.value = _result 532 for (const r of _result.slice(0, EAGER_EXCERPTS)) {
471 .map((r) => { 533 eagerDocs.add(r.id.slice(0, r.id.indexOf('#')))
472 const [id, anchor] = r.id.split('#') 534 }
473 const map = cache.get(`${id}\n${filterTextValue}`) 535 await Promise.all(
474 const text = map?.get(anchor) ?? '' 536 [...eagerDocs].map((docId) => buildDocExcerpt(docId, filterTextValue))
475 for (const term in r.match) { 537 )
476 terms.add(term) 538 if (canceled) return
477 } 539 }
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 })
486 540
487 currentTerms.value = terms 541 results.value = toRows(_result)
488 542
489 await nextTick() 543 await nextTick()
490 if (canceled) return 544 if (canceled) return
491 545 await highlight()
492 await new Promise((r) => {
493 mark.value?.unmark({
494 done: () => {
495 mark.value?.markRegExp(formMarkRegex(terms), { done: r })
496 }
497 })
498 })
499
500 await nextTick() 546 await nextTick()
501 await nextFrame() 547 await nextFrame()
502 if (canceled) return 548 if (canceled) return
@@ -505,6 +551,30 @@ watchDebounced(
505 resultsEl.value.scrollTop = 0 551 resultsEl.value.scrollTop = 0
506 } 552 }
507 centerExcerptsUntilSettled() 553 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 }
508 }, 578 },
509 { debounce: 80, immediate: true } 579 { debounce: 80, immediate: true }
510) 580)
@@ -551,18 +621,21 @@ onBeforeUnmount(() => {
551 if (ribbonAnimHandle) cancelAnimationFrame(ribbonAnimHandle) 621 if (ribbonAnimHandle) cancelAnimationFrame(ribbonAnimHandle)
552}) 622})
553 623
554const excerptCache = new LRUCache<string, unknown>(60) // 60 excerpts 624const excerptCache = new LRUCache<string, unknown>(24)
555 625
556async function fetchExcerpt(id: string) { 626async function fetchExcerpt(id: string) {
557 const cache = excerptCache.get(id) 627 const hashIndex = id.indexOf('#')
558 if (cache) return { id, mod: cache } 628 const docId = hashIndex === -1 ? id : id.slice(0, hashIndex)
629
630 const cached = excerptCache.get(docId)
631 if (cached) return { id, mod: cached }
559 632
560 const file = pathToFile(id.slice(0, id.indexOf('#'))) 633 const file = pathToFile(docId)
561 try { 634 try {
562 if (!file) throw new Error(`Cannot find file for id: ${id}`) 635 if (!file) throw new Error(`Cannot find file for id: ${id}`)
563 const mod = await import(/*@vite-ignore*/ file) 636 const mod = await import(/*@vite-ignore*/ file)
564 637
565 excerptCache.set(id, mod) 638 excerptCache.set(docId, mod)
566 639
567 return { id, mod } 640 return { id, mod }
568 } catch (e) { 641 } catch (e) {