Commit bdf64bf47b

bdf64bf47b847b6532f7e777a73b7647c3cd4118

parent: f17cadfd87

Unsigned

Duck <57977673+woducku@users.noreply.github.com> · 2026-07-31 16:56 UTC

Update Search.vue

Layout: unified · split

docs/.vitepress/theme/components/search/Search.vue +371 −123
@@ -16,6 +16,8 @@ import {
16} from 'vue' 16} from 'vue'
17// @ts-ignore 17// @ts-ignore
18import { pathToFile } from 'vitepress/dist/client/app/utils' 18import { pathToFile } from 'vitepress/dist/client/app/utils'
19// @ts-ignore
20import { RouterSymbol } from 'vitepress/dist/client/app/router'
19 21
20import { 22import {
21 computedAsync, 23 computedAsync,
@@ -31,71 +33,67 @@ import { AnimatePresence } from 'motion-v'
31// @ts-ignore 33// @ts-ignore
32import localSearchIndex from '@localSearchIndex' 34import localSearchIndex from '@localSearchIndex'
33 35
34import { 36import { ArrowRight, File, Hash } from 'lucide-vue-next'
35 File,
36 Hash,
37 ArrowRight
38} from 'lucide-vue-next'
39 37
40import Mark from 'mark.js/dist/mark.es6.js' 38import Mark from 'mark.js/dist/mark.es6.js'
41import { sidebar } from '../../../configs/constants' 39import { sidebar } from '../../../configs/constants'
42import type { PageLink } from '../../plugins/urlSearchPlugin'
43import { LRUCache } from '../../composables/search/lru-cache' 40import { LRUCache } from '../../composables/search/lru-cache'
44import { createSearchTranslate } from '../../composables/search/translation' 41import { createSearchTranslate } from '../../composables/search/translation'
45import { useData } from '../../composables/search/use-data' 42import { useData } from '../../composables/search/use-data'
46import { useEffects } from '../../composables/useEffects' 43import { useEffects } from '../../composables/useEffects'
47import { applyFavicons, useFavicons } from '../../composables/useFavicons' 44import { applyFavicons, useFavicons } from '../../composables/useFavicons'
48import { registerGlobalComponents } from '../../globalComponents' 45import { registerGlobalComponents } from '../../globalComponents'
46import type { PageLink } from '../../plugins/urlSearchPlugin'
49import { 47import {
50 excerptPreload, 48 excerptPreload,
51 ribbonStyle, 49 ribbonStyle,
52 saveHistoryEnabled, 50 saveHistoryEnabled,
53 searchHistory, 51 searchHistory,
52 type SearchHistoryEntry,
54 searchMode, 53 searchMode,
55 searchResultHighlightMode, 54 searchResultHighlightMode,
56 showDetailedList, 55 type SearchSortMode,
57 type SearchHistoryEntry, 56 showDetailedList
58 type SearchSortMode
59} from '../../searchState' 57} from '../../searchState'
60import { enhanceAppWithTabs } from '../tabs' 58import { enhanceAppWithTabs } from '../tabs'
61 59
62import type { 60import type {
63 FooterTranslations, 61 FooterTranslations,
64 ModalTranslations, 62 ModalTranslations,
65 Result,
66 PageGroupCount, 63 PageGroupCount,
67 UrlResult, 64 Result,
65 SearchWorkerRequest,
68 TextSearchWorkerPayload, 66 TextSearchWorkerPayload,
69 UrlSearchWorkerPayload, 67 UrlResult,
70 SearchWorkerRequest 68 UrlSearchWorkerPayload
71} from './types' 69} from './types'
72 70
73import { 71import {
72 buildResultHref,
74 escapeHtml, 73 escapeHtml,
75 highlightUrl,
76 formMarkRegex, 74 formMarkRegex,
77 toHistoryPathHtml,
78 hasExcerptPreview,
79 getPageKey,
80 getDocId,
81 getDocAnchor, 75 getDocAnchor,
76 getDocId,
77 getPageKey,
82 getPageLabel, 78 getPageLabel,
83 getPageOrder, 79 getPageOrder,
84 buildResultHref, 80 getPageOrderEntries,
85 getSearchResultHref, 81 getSearchResultHref,
82 hasExcerptPreview,
83 highlightUrl,
84 nextFrame,
86 stripNonCloneable, 85 stripNonCloneable,
87 getPageOrderEntries, 86 toHistoryPathHtml
88 nextFrame
89} from './utils' 87} from './utils'
90 88
91import { useSearchMotion } from './SearchMotion' 89import { useSearchMotion } from './SearchMotion'
92 90
93import SearchBar from './SearchBar.vue' 91import SearchBar from './SearchBar.vue'
94import SearchRibbon from './SearchRibbon.vue'
95import SearchPagination from './SearchPagination.vue'
96import SearchKeyboardShortcuts from './SearchKeyboardShortcuts.vue'
97import SearchEmptyState from './SearchEmptyState.vue' 92import SearchEmptyState from './SearchEmptyState.vue'
98import SearchHistory from './SearchHistory.vue' 93import SearchHistory from './SearchHistory.vue'
94import SearchKeyboardShortcuts from './SearchKeyboardShortcuts.vue'
95import SearchPagination from './SearchPagination.vue'
96import SearchRibbon from './SearchRibbon.vue'
99import SearchSettings from './SearchSettings.vue' 97import SearchSettings from './SearchSettings.vue'
100 98
101const showSearch = defineModel<boolean>() 99const showSearch = defineModel<boolean>()
@@ -106,8 +104,12 @@ const searchBarRef = ref<InstanceType<typeof SearchBar>>()
106const ribbonRef = ref<InstanceType<typeof SearchRibbon>>() 104const ribbonRef = ref<InstanceType<typeof SearchRibbon>>()
107 105
108/* Refs exposed by SearchBar */ 106/* Refs exposed by SearchBar */
109const searchInput = computed(() => searchBarRef.value?.searchInput as HTMLInputElement | undefined) 107const searchInput = computed(() =>
110const settingsButtonRef = computed(() => searchBarRef.value?.settingsButtonRef as HTMLButtonElement | undefined) 108 searchBarRef.value?.searchInput as HTMLInputElement | undefined
109)
110const settingsButtonRef = computed(() =>
111 searchBarRef.value?.settingsButtonRef as HTMLButtonElement | undefined
112)
111 113
112/* Search */ 114/* Search */
113const searchIndexData = shallowRef(localSearchIndex) 115const searchIndexData = shallowRef(localSearchIndex)
@@ -199,7 +201,9 @@ function saveToHistory(
199 searchHistory.value = [ 201 searchHistory.value = [
200 { query: trimmed, mode, path, href, resultText }, 202 { query: trimmed, mode, path, href, resultText },
201 ...searchHistory.value.filter( 203 ...searchHistory.value.filter(
202 (h) => !(h.query === trimmed && h.mode === mode && (h.path ?? []).join('\n') === pathKey) 204 (h) =>
205 !(h.query === trimmed && h.mode === mode &&
206 (h.path ?? []).join('\n') === pathKey)
203 ) 207 )
204 ] 208 ]
205} 209}
@@ -241,7 +245,9 @@ const urlPageGroups = computed(() =>
241 label: getPageLabel(group.key, pageMeta), 245 label: getPageLabel(group.key, pageMeta),
242 count: group.count 246 count: group.count
243 })) 247 }))
244 .sort((a, b) => getPageOrder(a.key, pageMeta) - getPageOrder(b.key, pageMeta)) 248 .sort((a, b) =>
249 getPageOrder(a.key, pageMeta) - getPageOrder(b.key, pageMeta)
250 )
245) 251)
246 252
247const urlFilteredMatches = computed((): PageLink[] => { 253const urlFilteredMatches = computed((): PageLink[] => {
@@ -303,7 +309,9 @@ function goToUrlPage(p: number) {
303 }) 309 })
304} 310}
305 311
306watch([urlFilterDebounced, urlActivePageFilter], () => { urlPage.value = 1 }) 312watch([urlFilterDebounced, urlActivePageFilter], () => {
313 urlPage.value = 1
314})
307 315
308watch(urlMatches, () => { 316watch(urlMatches, () => {
309 if ( 317 if (
@@ -392,7 +400,9 @@ let searchWorker: Worker | undefined
392let searchWorkerRequestId = 0 400let searchWorkerRequestId = 0
393let loadedWorkerIndexKey = '' 401let loadedWorkerIndexKey = ''
394let preloadedSearchDataKey = '' 402let preloadedSearchDataKey = ''
395let preloadSearchDataRequest: { key: string; promise: Promise<void> } | undefined 403let preloadSearchDataRequest:
404 | { key: string; promise: Promise<void> }
405 | undefined
396const searchWorkerRequests = new Map< 406const searchWorkerRequests = new Map<
397 number, 407 number,
398 { resolve: (value: unknown) => void; reject: (reason?: unknown) => void } 408 { resolve: (value: unknown) => void; reject: (reason?: unknown) => void }
@@ -402,11 +412,18 @@ function getMiniSearchWorkerConfig() {
402 const miniSearch = theme.value.search?.provider === 'local' 412 const miniSearch = theme.value.search?.provider === 'local'
403 ? theme.value.search.options?.miniSearch 413 ? theme.value.search.options?.miniSearch
404 : undefined 414 : undefined
405 const rawSearchOptions = miniSearch?.searchOptions as Record<string, unknown> | undefined 415 const rawSearchOptions = miniSearch?.searchOptions as
416 | Record<string, unknown>
417 | undefined
406 return { 418 return {
407 options: stripNonCloneable(miniSearch?.options) as Record<string, unknown> | undefined, 419 options: stripNonCloneable(miniSearch?.options) as
408 searchOptions: stripNonCloneable(rawSearchOptions) as Record<string, unknown> | undefined, 420 | Record<string, unknown>
409 useDefaultBoostDocument: typeof rawSearchOptions?.boostDocument === 'function' 421 | undefined,
422 searchOptions: stripNonCloneable(rawSearchOptions) as
423 | Record<string, unknown>
424 | undefined,
425 useDefaultBoostDocument:
426 typeof rawSearchOptions?.boostDocument === 'function'
410 } 427 }
411} 428}
412 429
@@ -424,7 +441,8 @@ async function preloadSearchData(
424 441
425 const promise = (async () => { 442 const promise = (async () => {
426 if (loadedWorkerIndexKey !== workerIndexKey) { 443 if (loadedWorkerIndexKey !== workerIndexKey) {
427 const indexJson = (await searchIndexData.value[localeIndexValue]?.())?.default 444 const indexJson = (await searchIndexData.value[localeIndexValue]?.())
445 ?.default
428 await postSearchWorker<void>({ 446 await postSearchWorker<void>({
429 type: 'load-index', 447 type: 'load-index',
430 localeIndex: localeIndexValue, 448 localeIndex: localeIndexValue,
@@ -466,7 +484,12 @@ function ensureSearchWorker() {
466 } 484 }
467 485
468 searchWorker.onmessage = (event: MessageEvent) => { 486 searchWorker.onmessage = (event: MessageEvent) => {
469 const data = event.data as { id: number; type: string; payload?: unknown; error?: string } 487 const data = event.data as {
488 id: number
489 type: string
490 payload?: unknown
491 error?: string
492 }
470 const request = searchWorkerRequests.get(data.id) 493 const request = searchWorkerRequests.get(data.id)
471 if (!request) return 494 if (!request) return
472 searchWorkerRequests.delete(data.id) 495 searchWorkerRequests.delete(data.id)
@@ -489,12 +512,17 @@ function postSearchWorker<T>(message: SearchWorkerRequest) {
489 512
490 const id = ++searchWorkerRequestId 513 const id = ++searchWorkerRequestId
491 return new Promise<T>((resolve, reject) => { 514 return new Promise<T>((resolve, reject) => {
492 searchWorkerRequests.set(id, { resolve: (value) => resolve(value as T), reject }) 515 searchWorkerRequests.set(id, {
516 resolve: (value) => resolve(value as T),
517 reject
518 })
493 worker.postMessage({ ...message, id }) 519 worker.postMessage({ ...message, id })
494 }) 520 })
495} 521}
496 522
497onMounted(() => { ensureSearchWorker() }) 523onMounted(() => {
524 ensureSearchWorker()
525})
498 526
499onBeforeUnmount(() => { 527onBeforeUnmount(() => {
500 searchWorker?.terminate() 528 searchWorker?.terminate()
@@ -511,7 +539,14 @@ onBeforeUnmount(() => {
511 539
512// Watch: preload search data when search opens 540// Watch: preload search data when search opens
513watch( 541watch(
514 () => [searchWorkerReady.value, showSearch.value, localeIndex.value, searchIndexVersion.value, searchWorkerConfigKey.value] as const, 542 () =>
543 [
544 searchWorkerReady.value,
545 showSearch.value,
546 localeIndex.value,
547 searchIndexVersion.value,
548 searchWorkerConfigKey.value
549 ] as const,
515 async ([ready, isOpen, localeIndexValue, indexVersion, configKey]) => { 550 async ([ready, isOpen, localeIndexValue, indexVersion, configKey]) => {
516 if (!ready || !isOpen) return 551 if (!ready || !isOpen) return
517 try { 552 try {
@@ -525,17 +560,28 @@ watch(
525 560
526// Watch: URL search 561// Watch: URL search
527watch( 562watch(
528 () => [searchWorkerReady.value, showSearch.value, urlSearchMode.value, urlFilterDebounced.value] as const, 563 () =>
564 [
565 searchWorkerReady.value,
566 showSearch.value,
567 urlSearchMode.value,
568 urlFilterDebounced.value
569 ] as const,
529 async ([ready, isOpen, active, query], _old, onCleanup) => { 570 async ([ready, isOpen, active, query], _old, onCleanup) => {
530 let canceled = false 571 let canceled = false
531 onCleanup(() => { canceled = true }) 572 onCleanup(() => {
573 canceled = true
574 })
532 if (!active || !isOpen || !query.trim()) { 575 if (!active || !isOpen || !query.trim()) {
533 urlMatches.value = [] 576 urlMatches.value = []
534 urlPageGroupCounts.value = [] 577 urlPageGroupCounts.value = []
535 urlSearchLoading.value = false 578 urlSearchLoading.value = false
536 return 579 return
537 } 580 }
538 if (!ready) { urlSearchLoading.value = false; return } 581 if (!ready) {
582 urlSearchLoading.value = false
583 return
584 }
539 urlSearchLoading.value = true 585 urlSearchLoading.value = true
540 try { 586 try {
541 const payload = await postSearchWorker<UrlSearchWorkerPayload>({ 587 const payload = await postSearchWorker<UrlSearchWorkerPayload>({
@@ -575,7 +621,9 @@ const pageGroups = computed(() => {
575 621
576const filteredResults = computed(() => { 622const filteredResults = computed(() => {
577 if (!activePageFilter.value) return results.value 623 if (!activePageFilter.value) return results.value
578 return results.value.filter((r) => getPageKey(r.id) === activePageFilter.value) 624 return results.value.filter((r) =>
625 getPageKey(r.id) === activePageFilter.value
626 )
579}) 627})
580 628
581// Normal pagination 629// Normal pagination
@@ -651,6 +699,7 @@ async function reapplyHighlights() {
651 mark.value?.unmark({ 699 mark.value?.unmark({
652 done: () => { 700 done: () => {
653 mark.value?.markRegExp(formMarkRegex(currentTerms.value), { 701 mark.value?.markRegExp(formMarkRegex(currentTerms.value), {
702 filter: shouldMarkTextNode,
654 done: () => resolve() 703 done: () => resolve()
655 }) 704 })
656 } 705 }
@@ -763,19 +812,39 @@ function buildDocExcerpt(docId: string): Promise<void> {
763 enhanceAppWithTabs(app, { renderAll: true }) 812 enhanceAppWithTabs(app, { renderAll: true })
764 registerGlobalComponents(app) 813 registerGlobalComponents(app)
765 app.provide(dataSymbol, vitePressData) 814 app.provide(dataSymbol, vitePressData)
815 // Pages embed <Feedback>, which calls useRouter() in the excerpt app.
816 app.provide(RouterSymbol, router)
766 Object.defineProperties(app.config.globalProperties, { 817 Object.defineProperties(app.config.globalProperties, {
767 $frontmatter: { get() { return vitePressData.frontmatter.value } }, 818 $frontmatter: {
768 $params: { get() { return vitePressData.page.value.params } } 819 get() {
820 return vitePressData.frontmatter.value
821 }
822 },
823 $params: {
824 get() {
825 return vitePressData.page.value.params
826 }
827 }
769 }) 828 })
770 const div = document.createElement('div') 829 const div = document.createElement('div')
771 try { 830 try {
772 const originalCreateElement = document.createElement 831 const originalCreateElement = document.createElement
773 document.createElement = function (this: Document, ...args: Parameters<Document['createElement']>) { 832 document.createElement = function(
833 this: Document,
834 ...args: Parameters<Document['createElement']>
835 ) {
774 const el = originalCreateElement.apply(this, args) 836 const el = originalCreateElement.apply(this, args)
775 if (el instanceof HTMLImageElement) { el.loading = 'lazy'; el.decoding = 'async' } 837 if (el instanceof HTMLImageElement) {
838 el.loading = 'lazy'
839 el.decoding = 'async'
840 }
776 return el 841 return el
777 } as typeof document.createElement 842 } as typeof document.createElement
778 try { app.mount(div) } finally { document.createElement = originalCreateElement } 843 try {
844 app.mount(div)
845 } finally {
846 document.createElement = originalCreateElement
847 }
779 const headings = div.querySelectorAll('h1, h2, h3, h4, h5, h6') 848 const headings = div.querySelectorAll('h1, h2, h3, h4, h5, h6')
780 headings.forEach((heading) => { 849 headings.forEach((heading) => {
781 const href = heading.querySelector('a')?.getAttribute('href') 850 const href = heading.querySelector('a')?.getAttribute('href')
@@ -783,7 +852,9 @@ function buildDocExcerpt(docId: string): Promise<void> {
783 const anchor = hashIndex >= 0 ? href!.slice(hashIndex + 1) : '' 852 const anchor = hashIndex >= 0 ? href!.slice(hashIndex + 1) : ''
784 if (!anchor) return 853 if (!anchor) return
785 854
786 const collapsible = heading.closest('details.custom-block') as HTMLDetailsElement | null 855 const collapsible = heading.closest('details.custom-block') as
856 | HTMLDetailsElement
857 | null
787 if (collapsible) { 858 if (collapsible) {
788 collapsible.open = true 859 collapsible.open = true
789 map.set(anchor, collapsible.outerHTML) 860 map.set(anchor, collapsible.outerHTML)
@@ -792,7 +863,9 @@ function buildDocExcerpt(docId: string): Promise<void> {
792 863
793 let html = '' 864 let html = ''
794 let node = heading as Element 865 let node = heading as Element
795 while ((node = node.nextElementSibling!) && !/^h[1-6]$/i.test(node.tagName)) { 866 while (
867 (node = node.nextElementSibling!) && !/^h[1-6]$/i.test(node.tagName)
868 ) {
796 html += (node as HTMLElement).outerHTML 869 html += (node as HTMLElement).outerHTML
797 } 870 }
798 map.set(anchor, html) 871 map.set(anchor, html)
@@ -800,7 +873,9 @@ function buildDocExcerpt(docId: string): Promise<void> {
800 } catch (e) { 873 } catch (e) {
801 console.error('[search] excerpt render failed for', docId, e) 874 console.error('[search] excerpt render failed for', docId, e)
802 } finally { 875 } finally {
803 try { app.unmount() } catch { /* ignore */ } 876 try {
877 app.unmount()
878 } catch { /* ignore */ }
804 } 879 }
805 cache.set(docId, map) 880 cache.set(docId, map)
806 })() 881 })()
@@ -828,7 +903,9 @@ async function fetchExcerpt(id: string) {
828 } 903 }
829} 904}
830 905
831watch(excerptPreload, () => { void buildVisibleExcerpts() }) 906watch(excerptPreload, () => {
907 void buildVisibleExcerpts()
908})
832 909
833watch(results, () => { 910watch(results, () => {
834 if ( 911 if (
@@ -839,19 +916,52 @@ watch(results, () => {
839 } 916 }
840}) 917})
841 918
842watch(filterText, () => { enableNoResults.value = false }) 919watch(filterText, () => {
920 enableNoResults.value = false
921})
843 922
844// Debounced text search 923// Debounced text search
845watchDebounced( 924watchDebounced(
846 () => [searchWorkerReady.value, showSearch.value, localeIndex.value, searchIndexVersion.value, searchWorkerConfigKey.value, filterText.value, showDetailedList.value, searchMode.value] as const, 925 () =>
847 async ([ready, isOpen, localeIndexValue, indexVersion, configKey, filterTextValue, showDetailedListValue, mode], old, onCleanup) => { 926 [
848 if (old?.[2] !== localeIndexValue || old?.[3] !== indexVersion || old?.[4] !== configKey) { 927 searchWorkerReady.value,
928 showSearch.value,
929 localeIndex.value,
930 searchIndexVersion.value,
931 searchWorkerConfigKey.value,
932 filterText.value,
933 showDetailedList.value,
934 searchMode.value
935 ] as const,
936 async (
937 [
938 ready,
939 isOpen,
940 localeIndexValue,
941 indexVersion,
942 configKey,
943 filterTextValue,
944 showDetailedListValue,
945 mode
946 ],
947 old,
948 onCleanup
949 ) => {
950 if (
951 old?.[2] !== localeIndexValue || old?.[3] !== indexVersion ||
952 old?.[4] !== configKey
953 ) {
849 cache.clear() 954 cache.clear()
850 } 955 }
851 let canceled = false 956 let canceled = false
852 onCleanup(() => { canceled = true }) 957 onCleanup(() => {
958 canceled = true
959 })
853 excerptBuildToken++ 960 excerptBuildToken++
854 if (!ready || !isOpen) { textSearchLoading.value = false; return } 961 if (!ready || !isOpen) {
962 textSearchLoading.value = false
963 return
964 }
855 965
856 if (mode === 'url') { 966 if (mode === 'url') {
857 results.value = [] 967 results.value = []
@@ -869,14 +979,18 @@ watchDebounced(
869 } catch (error) { 979 } catch (error) {
870 if (!canceled) { 980 if (!canceled) {
871 console.error('[search] text search index preload failed', error) 981 console.error('[search] text search index preload failed', error)
872 results.value = []; currentTerms.value = new Set() 982 results.value = []
873 enableNoResults.value = Boolean(searchQuery); textSearchLoading.value = false 983 currentTerms.value = new Set()
984 enableNoResults.value = Boolean(searchQuery)
985 textSearchLoading.value = false
874 } 986 }
875 return 987 return
876 } 988 }
877 if (!searchQuery) { 989 if (!searchQuery) {
878 results.value = []; currentTerms.value = new Set() 990 results.value = []
879 enableNoResults.value = false; textSearchLoading.value = false 991 currentTerms.value = new Set()
992 enableNoResults.value = false
993 textSearchLoading.value = false
880 return 994 return
881 } 995 }
882 996
@@ -891,8 +1005,10 @@ watchDebounced(
891 } catch (error) { 1005 } catch (error) {
892 if (!canceled) { 1006 if (!canceled) {
893 console.error('[search] text search worker request failed', error) 1007 console.error('[search] text search worker request failed', error)
894 results.value = []; currentTerms.value = new Set() 1008 results.value = []
895 enableNoResults.value = true; textSearchLoading.value = false 1009 currentTerms.value = new Set()
1010 enableNoResults.value = true
1011 textSearchLoading.value = false
896 } 1012 }
897 return 1013 return
898 } 1014 }
@@ -902,14 +1018,24 @@ watchDebounced(
902 const terms = new Set(workerPayload.terms) 1018 const terms = new Set(workerPayload.terms)
903 currentTerms.value = terms 1019 currentTerms.value = terms
904 enableNoResults.value = true 1020 enableNoResults.value = true
905 if (!_result.length) { results.value = []; textSearchLoading.value = false; return } 1021 if (!_result.length) {
1022 results.value = []
1023 textSearchLoading.value = false
1024 return
1025 }
906 1026
907 const highlight = () => 1027 const highlight = () =>
908 new Promise<void>((resolve) => { 1028 new Promise<void>((resolve) => {
909 if (!terms.size || !mark.value) { resolve(); return } 1029 if (!terms.size || !mark.value) {
1030 resolve()
1031 return
1032 }
910 mark.value.unmark({ 1033 mark.value.unmark({
911 done: () => { 1034 done: () => {
912 mark.value?.markRegExp(formMarkRegex(terms), { done: () => resolve() }) 1035 mark.value?.markRegExp(formMarkRegex(terms), {
1036 filter: shouldMarkTextNode,
1037 done: () => resolve()
1038 })
913 } 1039 }
914 }) 1040 })
915 }) 1041 })
@@ -934,6 +1060,36 @@ watchDebounced(
934) 1060)
935 1061
936// Excerpt centering 1062// Excerpt centering
1063const findTargetLinkInExcerpt = (
1064 excerptElement: HTMLElement,
1065 linkTitle: string
1066) => {
1067 const links = excerptElement.querySelectorAll('a')
1068 const normalizedTitle = linkTitle.trim().toLowerCase()
1069 for (const link of links) {
1070 if (link.textContent?.trim().toLowerCase() === normalizedTitle) {
1071 return link
1072 }
1073 }
1074 return null
1075}
1076
1077// For pinned results, only mark text inside the target link so other substring matches are skipped.
1078const shouldMarkTextNode = (textNode: Text) => {
1079 const parent = textNode.parentElement
1080 if (!parent) return true
1081
1082 const resultEl = parent.closest('.result') as HTMLElement | null
1083 const linkTitle = resultEl?.dataset?.linkTitle
1084 if (!linkTitle) return true
1085
1086 const excerpt = parent.closest('.excerpt') as HTMLElement | null
1087 if (!excerpt) return true
1088
1089 const targetLink = findTargetLinkInExcerpt(excerpt, linkTitle)
1090 return targetLink ? targetLink.contains(textNode) : true
1091}
1092
937function centerExcerpts() { 1093function centerExcerpts() {
938 const excerpts = el.value?.querySelectorAll('.result .excerpt') ?? [] 1094 const excerpts = el.value?.querySelectorAll('.result .excerpt') ?? []
939 for (let i = 0; i < excerpts.length; i++) { 1095 for (let i = 0; i < excerpts.length; i++) {
@@ -944,20 +1100,18 @@ function centerExcerpts() {
944 1100
945 let markNode: HTMLElement | null 1101 let markNode: HTMLElement | null
946 if (linkTitle) { 1102 if (linkTitle) {
947 const links = excerptElement.querySelectorAll('a') 1103 const targetLink = findTargetLinkInExcerpt(excerptElement, linkTitle)
948 let targetLink: HTMLAnchorElement | null = null
949 const normalizedTitle = linkTitle.trim().toLowerCase()
950 for (const link of links) {
951 if (link.textContent?.trim().toLowerCase() === normalizedTitle) {
952 targetLink = link
953 break
954 }
955 }
956 markNode = targetLink 1104 markNode = targetLink
957 ? (targetLink.querySelector('mark[data-markjs="true"]') as HTMLElement | null) 1105 ? (targetLink.querySelector('mark[data-markjs="true"]') as
958 : (excerptElement.querySelector('mark[data-markjs="true"]') as HTMLElement | null) 1106 | HTMLElement
1107 | null)
1108 : (excerptElement.querySelector('mark[data-markjs="true"]') as
1109 | HTMLElement
1110 | null)
959 } else { 1111 } else {
960 markNode = excerptElement.querySelector('mark[data-markjs="true"]') as HTMLElement | null 1112 markNode = excerptElement.querySelector('mark[data-markjs="true"]') as
1113 | HTMLElement
1114 | null
961 } 1115 }
962 1116
963 if (!markNode) continue 1117 if (!markNode) continue
@@ -968,17 +1122,23 @@ function centerExcerpts() {
968 offset += node.offsetTop 1122 offset += node.offsetTop
969 node = node.offsetParent as HTMLElement | null 1123 node = node.offsetParent as HTMLElement | null
970 } 1124 }
971 const targetScrollTop = offset - viewportHeight / 2 + markNode.offsetHeight / 2 1125 const targetScrollTop = offset - viewportHeight / 2 +
1126 markNode.offsetHeight / 2
972 excerptElement.scrollTop = Math.max(0, targetScrollTop) 1127 excerptElement.scrollTop = Math.max(0, targetScrollTop)
973 } 1128 }
974} 1129}
975 1130
976let centerHandle = 0 1131let centerHandle = 0
977 1132
978function centerExcerptsUntilSettled(duration = searchAnimationsEnabled.value ? 450 : 0) { 1133function centerExcerptsUntilSettled(
1134 duration = searchAnimationsEnabled.value ? 450 : 0
1135) {
979 if (centerHandle) cancelAnimationFrame(centerHandle) 1136 if (centerHandle) cancelAnimationFrame(centerHandle)
980 if (duration <= 0) { 1137 if (duration <= 0) {
981 centerHandle = requestAnimationFrame(() => { centerExcerpts(); centerHandle = 0 }) 1138 centerHandle = requestAnimationFrame(() => {
1139 centerExcerpts()
1140 centerHandle = 0
1141 })
982 return 1142 return
983 } 1143 }
984 const start = performance.now() 1144 const start = performance.now()
@@ -986,7 +1146,7 @@ function centerExcerptsUntilSettled(duration = searchAnimationsEnabled.value ? 4
986 centerExcerpts() 1146 centerExcerpts()
987 if (performance.now() - start < duration) { 1147 if (performance.now() - start < duration) {
988 centerHandle = requestAnimationFrame(tick) 1148 centerHandle = requestAnimationFrame(tick)
989 } else { centerHandle = 0 } 1149 } else centerHandle = 0
990 } 1150 }
991 centerHandle = requestAnimationFrame(tick) 1151 centerHandle = requestAnimationFrame(tick)
992} 1152}
@@ -1003,7 +1163,9 @@ function focusSearchInput(select = true) {
1003 select && searchInput.value?.select() 1163 select && searchInput.value?.select()
1004} 1164}
1005 1165
1006onMounted(() => { focusSearchInput() }) 1166onMounted(() => {
1167 focusSearchInput()
1168})
1007 1169
1008function onSearchBarClick(event: PointerEvent) { 1170function onSearchBarClick(event: PointerEvent) {
1009 if (event.pointerType === 'mouse') focusSearchInput() 1171 if (event.pointerType === 'mouse') focusSearchInput()
@@ -1014,20 +1176,30 @@ const selectedIndex = ref(-1)
1014const disableMouseOver = ref(true) 1176const disableMouseOver = ref(true)
1015 1177
1016const activeResultsLength = computed(() => 1178const activeResultsLength = computed(() =>
1017 urlSearchMode.value ? filteredUrlResults.value.length : pagedResults.value.length 1179 urlSearchMode.value
1180 ? filteredUrlResults.value.length
1181 : pagedResults.value.length
1018) 1182)
1019 1183
1020watch(pagedResults, (r) => { 1184watch(pagedResults, (r) => {
1021 if (!urlSearchMode.value) { selectedIndex.value = r.length ? 0 : -1; scrollToSelectedResult() } 1185 if (!urlSearchMode.value) {
1186 selectedIndex.value = r.length ? 0 : -1
1187 scrollToSelectedResult()
1188 }
1022}) 1189})
1023 1190
1024watch(filteredUrlResults, (r) => { 1191watch(filteredUrlResults, (r) => {
1025 if (urlSearchMode.value) { selectedIndex.value = r.length ? 0 : -1; scrollToSelectedResult() } 1192 if (urlSearchMode.value) {
1193 selectedIndex.value = r.length ? 0 : -1
1194 scrollToSelectedResult()
1195 }
1026}) 1196})
1027 1197
1028watch([pagedResults, filteredUrlResults, faviconsEnabled], () => { 1198watch([pagedResults, filteredUrlResults, faviconsEnabled], () => {
1029 if (!faviconsEnabled.value) return 1199 if (!faviconsEnabled.value) return
1030 nextTick(() => { if (resultsEl.value) applyFavicons(resultsEl.value) }) 1200 nextTick(() => {
1201 if (resultsEl.value) applyFavicons(resultsEl.value)
1202 })
1031}) 1203})
1032 1204
1033function scrollToSelectedResult() { 1205function scrollToSelectedResult() {
@@ -1072,7 +1244,9 @@ function cyclePageTab(delta: number) {
1072onKeyStroke('ArrowUp', (event) => { 1244onKeyStroke('ArrowUp', (event) => {
1073 event.preventDefault() 1245 event.preventDefault()
1074 selectedIndex.value-- 1246 selectedIndex.value--
1075 if (selectedIndex.value < 0) selectedIndex.value = activeResultsLength.value - 1 1247 if (selectedIndex.value < 0) {
1248 selectedIndex.value = activeResultsLength.value - 1
1249 }
1076 disableMouseOver.value = true 1250 disableMouseOver.value = true
1077 scrollToSelectedResult() 1251 scrollToSelectedResult()
1078}) 1252})
@@ -1080,7 +1254,9 @@ onKeyStroke('ArrowUp', (event) => {
1080onKeyStroke('ArrowDown', (event) => { 1254onKeyStroke('ArrowDown', (event) => {
1081 event.preventDefault() 1255 event.preventDefault()
1082 selectedIndex.value++ 1256 selectedIndex.value++
1083 if (selectedIndex.value >= activeResultsLength.value + 1) selectedIndex.value = 0 1257 if (selectedIndex.value >= activeResultsLength.value + 1) {
1258 selectedIndex.value = 0
1259 }
1084 disableMouseOver.value = true 1260 disableMouseOver.value = true
1085 scrollToSelectedResult() 1261 scrollToSelectedResult()
1086}) 1262})
@@ -1108,9 +1284,13 @@ const router = useRouter()
1108 1284
1109function navigateToUrlResult(item: UrlResult) { 1285function navigateToUrlResult(item: UrlResult) {
1110 saveToHistory( 1286 saveToHistory(
1111 filterText.value, searchMode.value, 1287 filterText.value,
1112 [getPageLabel(item.pageId, pageMeta), ...item.titles, item.linkText].map(toHistoryPathHtml).filter(Boolean), 1288 searchMode.value,
1113 buildResultHref(item.pageId, item.tabs, item.anchor), item.linkText 1289 [getPageLabel(item.pageId, pageMeta), ...item.titles, item.linkText].map(
1290 toHistoryPathHtml
1291 ).filter(Boolean),
1292 buildResultHref(item.pageId, item.tabs, item.anchor),
1293 item.linkText
1114 ) 1294 )
1115 window.dispatchEvent( 1295 window.dispatchEvent(
1116 new CustomEvent('search-nav', { 1296 new CustomEvent('search-nav', {
@@ -1127,7 +1307,9 @@ function navigateToUrlResult(item: UrlResult) {
1127 1307
1128onKeyStroke('Enter', (e) => { 1308onKeyStroke('Enter', (e) => {
1129 if (e.isComposing) return 1309 if (e.isComposing) return
1130 if (e.target instanceof HTMLButtonElement && e.target.type !== 'submit') return 1310 if (e.target instanceof HTMLButtonElement && e.target.type !== 'submit') {
1311 return
1312 }
1131 1313
1132 const index = selectedIndex.value - 1 1314 const index = selectedIndex.value - 1
1133 if (index === -1) { 1315 if (index === -1) {
@@ -1144,12 +1326,21 @@ onKeyStroke('Enter', (e) => {
1144 } 1326 }
1145 1327
1146 const selectedPackage = pagedResults.value[index] 1328 const selectedPackage = pagedResults.value[index]
1147 if (e.target instanceof HTMLInputElement && !selectedPackage) { e.preventDefault(); return } 1329 if (e.target instanceof HTMLInputElement && !selectedPackage) {
1330 e.preventDefault()
1331 return
1332 }
1148 if (selectedPackage) { 1333 if (selectedPackage) {
1149 saveToHistory( 1334 saveToHistory(
1150 filterText.value, searchMode.value, 1335 filterText.value,
1151 [getPageLabel(getPageKey(String(selectedPackage.id)), pageMeta), ...selectedPackage.titles, selectedPackage.title].map(toHistoryPathHtml).filter(Boolean), 1336 searchMode.value,
1152 getSearchResultHref(selectedPackage), selectedPackage.title 1337 [
1338 getPageLabel(getPageKey(String(selectedPackage.id)), pageMeta),
1339 ...selectedPackage.titles,
1340 selectedPackage.title
1341 ].map(toHistoryPathHtml).filter(Boolean),
1342 getSearchResultHref(selectedPackage),
1343 selectedPackage.title
1153 ) 1344 )
1154 window.dispatchEvent( 1345 window.dispatchEvent(
1155 new CustomEvent('search-nav', { 1346 new CustomEvent('search-nav', {
@@ -1167,9 +1358,15 @@ onKeyStroke('Enter', (e) => {
1167 1358
1168function onResultClick(item: SearchResult & Result) { 1359function onResultClick(item: SearchResult & Result) {
1169 saveToHistory( 1360 saveToHistory(
1170 filterText.value, searchMode.value, 1361 filterText.value,
1171 [getPageLabel(getPageKey(String(item.id)), pageMeta), ...item.titles, item.title].map(toHistoryPathHtml).filter(Boolean), 1362 searchMode.value,
1172 getSearchResultHref(item), item.title 1363 [
1364 getPageLabel(getPageKey(String(item.id)), pageMeta),
1365 ...item.titles,
1366 item.title
1367 ].map(toHistoryPathHtml).filter(Boolean),
1368 getSearchResultHref(item),
1369 item.title
1173 ) 1370 )
1174 window.dispatchEvent( 1371 window.dispatchEvent(
1175 new CustomEvent('search-nav', { 1372 new CustomEvent('search-nav', {
@@ -1184,7 +1381,10 @@ function onResultClick(item: SearchResult & Result) {
1184} 1381}
1185 1382
1186onKeyStroke('Escape', () => { 1383onKeyStroke('Escape', () => {
1187 if (showSettingsPopup.value) { showSettingsPopup.value = false; return } 1384 if (showSettingsPopup.value) {
1385 showSettingsPopup.value = false
1386 return
1387 }
1188 showSearch.value = false 1388 showSearch.value = false
1189}) 1389})
1190 1390
@@ -1215,17 +1415,27 @@ const defaultTranslations: { modal: ModalTranslations } = {
1215const translate = createSearchTranslate(defaultTranslations) 1415const translate = createSearchTranslate(defaultTranslations)
1216 1416
1217// Back 1417// Back
1218onMounted(() => { window.history.pushState(null, '', null) }) 1418onMounted(() => {
1219useEventListener('popstate', (event) => { event.preventDefault(); showSearch.value = false }) 1419 window.history.pushState(null, '', null)
1420})
1421useEventListener('popstate', (event) => {
1422 event.preventDefault()
1423 showSearch.value = false
1424})
1220 1425
1221// Lock body 1426// Lock body
1222const isLocked = useScrollLock(inBrowser ? document.body : null) 1427const isLocked = useScrollLock(inBrowser ? document.body : null)
1223 1428
1224watch(() => showSearch.value, (val) => { 1429watch(() => showSearch.value, (val) => {
1225 if (!val) { isLocked.value = false; return } 1430 if (!val) {
1431 isLocked.value = false
1432 return
1433 }
1226 nextTick(() => { 1434 nextTick(() => {
1227 isLocked.value = true 1435 isLocked.value = true
1228 nextTick().then(() => { activate() }) 1436 nextTick().then(() => {
1437 activate()
1438 })
1229 }) 1439 })
1230}) 1440})
1231 1441
@@ -1352,16 +1562,21 @@ function onMouseMove(e: MouseEvent) {
1352 item.anchor + '-' + index" 1562 item.anchor + '-' + index"
1353 class="result-layout" 1563 class="result-layout"
1354 :id="'localsearch-item-' + (index + 1)" 1564 :id="'localsearch-item-' + (index + 1)"
1355 :aria-selected="selectedIndex === index + 1 ? 'true' : 'false'" 1565 :aria-selected="selectedIndex === index + 1
1566 ? 'true'
1567 : 'false'"
1356 role="option" 1568 role="option"
1357 v-bind="resultMotion(index)" 1569 v-bind="resultMotion(index)"
1358 > 1570 >
1359 <div 1571 <div
1360 class="result url-result-card" 1572 class="result url-result-card"
1361 :class="{ selected: selectedIndex === index + 1 }" 1573 :class="{
1574 selected: selectedIndex === index + 1
1575 }"
1362 :aria-label="item.href" 1576 :aria-label="item.href"
1363 role="button" 1577 role="button"
1364 @mouseenter="!disableMouseOver && (selectedIndex = index + 1)" 1578 @mouseenter="!disableMouseOver &&
1579 (selectedIndex = index + 1)"
1365 @focusin="selectedIndex = index + 1" 1580 @focusin="selectedIndex = index + 1"
1366 @click="navigateToUrlResult(item)" 1581 @click="navigateToUrlResult(item)"
1367 :data-index="index + 1" 1582 :data-index="index + 1"
@@ -1369,16 +1584,29 @@ function onMouseMove(e: MouseEvent) {
1369 <div class="url-result-body"> 1584 <div class="url-result-body">
1370 <div class="url-path"> 1585 <div class="url-path">
1371 <Hash 1586 <Hash
1372 v-if="item.anchor || item.titles.length > 0" 1587 v-if="item.anchor ||
1588 item.titles.length > 0"
1373 stroke-width="2" 1589 stroke-width="2"
1374 :size="18" 1590 :size="18"
1375 /> 1591 />
1376 <File v-else stroke-width="2" :size="18" /> 1592 <File v-else stroke-width="2" :size="18" />
1377 <span v-for="(t, ti) in item.titles" :key="ti" class="url-path-segment"> 1593 <span
1594 v-for="(t, ti) in item.titles"
1595 :key="ti"
1596 class="url-path-segment"
1597 >
1378 <span class="text" v-html="t" /> 1598 <span class="text" v-html="t" />
1379 <ArrowRight stroke-width="2" :size="18" class="mx-0.5" /> 1599 <ArrowRight
1600 stroke-width="2"
1601 :size="18"
1602 class="mx-0.5"
1603 />
1380 </span> 1604 </span>
1381 <span v-if="item.linkText" class="url-path-current" v-html="item.linkText" /> 1605 <span
1606 v-if="item.linkText"
1607 class="url-path-current"
1608 v-html="item.linkText"
1609 />
1382 </div> 1610 </div>
1383 <a 1611 <a
1384 :href="item.href" 1612 :href="item.href"
@@ -1401,42 +1629,62 @@ function onMouseMove(e: MouseEvent) {
1401 <component 1629 <component
1402 :is="searchMotionLi" 1630 :is="searchMotionLi"
1403 v-for="(p, index) in pagedResults" 1631 v-for="(p, index) in pagedResults"
1404 :key="'normal-' + normalCurrentPage + '-' + p.id + (p._linkIndex != null ? '-' + p._linkIndex : '')" 1632 :key="'normal-' + normalCurrentPage + '-' +
1633 p.id + (p._linkIndex != null
1634 ? '-' + p._linkIndex
1635 : '')"
1405 class="result-layout" 1636 class="result-layout"
1406 :id="'localsearch-item-' + (index + 1)" 1637 :id="'localsearch-item-' + (index + 1)"
1407 :aria-selected="selectedIndex === index + 1 ? 'true' : 'false'" 1638 :aria-selected="selectedIndex === index + 1
1639 ? 'true'
1640 : 'false'"
1408 role="option" 1641 role="option"
1409 v-bind="resultMotion(index)" 1642 v-bind="resultMotion(index)"
1410 > 1643 >
1411 <a 1644 <a
1412 :href="getSearchResultHref(p)" 1645 :href="getSearchResultHref(p)"
1413 class="result" 1646 class="result"
1414 :class="{ selected: selectedIndex === index + 1 }" 1647 :class="{
1648 selected: selectedIndex === index + 1
1649 }"
1415 :aria-label="[...p.titles, p.title].join(' > ')" 1650 :aria-label="[...p.titles, p.title].join(' > ')"
1416 @mouseenter="!disableMouseOver && (selectedIndex = index + 1)" 1651 @mouseenter="!disableMouseOver &&
1652 (selectedIndex = index + 1)"
1417 @focusin="selectedIndex = index + 1" 1653 @focusin="selectedIndex = index + 1"
1418 @click="onResultClick(p)" 1654 @click="onResultClick(p)"
1419 :data-index="index + 1" 1655 :data-index="index + 1"
1420 :data-link-title="p._linkIndex != null ? p.title : undefined" 1656 :data-link-title="p._linkIndex != null
1657 ? p.title
1658 : undefined"
1421 > 1659 >
1422 <div> 1660 <div>
1423 <div class="titles"> 1661 <div class="titles">
1424 <Hash 1662 <Hash
1425 v-if="getDocAnchor(p.id) || p.titles.length > 0" 1663 v-if="getDocAnchor(p.id) ||
1664 p.titles.length > 0"
1426 stroke-width="2" 1665 stroke-width="2"
1427 :size="18" 1666 :size="18"
1428 /> 1667 />
1429 <File v-else stroke-width="2" :size="18" /> 1668 <File v-else stroke-width="2" :size="18" />
1430 <span v-for="(t, index) in p.titles" :key="index" class="title"> 1669 <span
1670 v-for="(t, index) in p.titles"
1671 :key="index"
1672 class="title"
1673 >
1431 <span class="text" v-html="t" /> 1674 <span class="text" v-html="t" />
1432 <ArrowRight stroke-width="2" :size="18" class="mx-0.5" /> 1675 <ArrowRight
1676 stroke-width="2"
1677 :size="18"
1678 class="mx-0.5"
1679 />
1433 </span> 1680 </span>
1434 <span class="title main"> 1681 <span class="title main">
1435 <span class="text" v-html="p.title" /> 1682 <span class="text" v-html="p.title" />
1436 </span> 1683 </span>
1437 </div> 1684 </div>
1438 <div 1685 <div
1439 v-if="showDetailedList && hasExcerptPreview(p.text)" 1686 v-if="showDetailedList &&
1687 hasExcerptPreview(p.text)"
1440 class="excerpt-wrapper" 1688 class="excerpt-wrapper"
1441 > 1689 >
1442 <component 1690 <component
@@ -1758,4 +2006,4 @@ svg {
1758 text-decoration: underline; 2006 text-decoration: underline;
1759 text-underline-offset: 2px; 2007 text-underline-offset: 2px;
1760} 2008}
1761</style>\ No newline at end of file 2009</style>