Commit ddb2b92275

ddb2b9227536528c1f6db69c24ad7cf381ec2cec

parent: 9e030629ae

Unsigned

Duck <57977673+woducku@users.noreply.github.com> · 2026-07-28 06:59 UTC

init

Layout: unified · split

docs/.vitepress/theme/Layout.vue +142 −2
@@ -36,6 +36,7 @@ import SidebarCard from './components/SidebarCard.vue'
3636import { AccentBgStorageKey, AccentBgStrengthStorageKey, AccentColorStorageKey } from './constants'
3737import { useEffects } from './composables/useEffects'
3838import { applyFavicons, removeFavicons, useFavicons } from './composables/useFavicons'
39import { searchResultHighlightMode } from './searchState'
3940
4041const route = useRoute()
4142const { frontmatter, isDark, site, theme } = useData()
@@ -59,6 +60,7 @@ watch(() => route.path, () => {
5960
6061let searchNavigated = false
6162let searchQuery = ''
63let searchResultText = ''
6264
6365if (!import.meta.env.SSR) {
6466 useEventListener(window, 'search-nav', (event) => {
@@ -67,6 +69,10 @@ if (!import.meta.env.SSR) {
6769 typeof event.detail?.query === 'string'
6870 ? event.detail.query
6971 : ''
72 searchResultText = event instanceof CustomEvent &&
73 typeof event.detail?.resultText === 'string'
74 ? event.detail.resultText
75 : ''
7076 })
7177}
7278
@@ -80,6 +86,127 @@ const getSearchTerms = (query: string) =>
8086 .map((term) => term.trim())
8187 .filter(Boolean)
8288
89const getSearchResultText = (value: string) => {
90 const el = document.createElement('div')
91 el.innerHTML = value
92 return (el.textContent ?? '').replace(/\s+/g, ' ').trim()
93}
94
95const removeSearchResultHighlights = () => {
96 document.querySelectorAll<HTMLElement>('.search-result-highlight').forEach(
97 (highlight) => highlight.replaceWith(...highlight.childNodes)
98 )
99}
100
101
102let highlightTerm = ''
103let highlightTabPath: string[] | null = null
104
105const isHighlightEnabled = () => {
106 const mode = searchResultHighlightMode.value
107 return mode !== 'off' && mode !== false
108}
109
110const isWordChar = (ch: string | undefined) =>
111 ch !== undefined && /[\p{L}\p{N}_]/u.test(ch)
112
113const getPanelTabPath = (panel: HTMLElement): string[] => {
114 const path: string[] = []
115 let current: HTMLElement | null = panel
116
117 while (current?.dataset.tabAnchor) {
118 path.unshift(current.dataset.tabAnchor)
119 const tabsGroup = current.closest<HTMLElement>('.plugin-tabs')
120 current = tabsGroup?.parentElement?.closest<HTMLElement>(
121 '.plugin-tabs--content[data-tab-anchor]'
122 ) ?? null
123 }
124
125 return path
126}
127
128const applyHighlightWithin = (root: HTMLElement, term: string) => {
129 const mode = searchResultHighlightMode.value
130 const termLower = term.toLocaleLowerCase()
131 const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, {
132 acceptNode(node) {
133 const parent = node.parentElement
134 if (!parent || parent.closest('.search-result-highlight, script, style')) {
135 return NodeFilter.FILTER_REJECT
136 }
137 return NodeFilter.FILTER_ACCEPT
138 }
139 })
140
141 let node: Text | null
142 while ((node = walker.nextNode() as Text | null)) {
143 const dataLower = node.data.toLocaleLowerCase()
144 let searchFrom = 0
145
146 while (true) {
147 const index = dataLower.indexOf(termLower, searchFrom)
148 if (index < 0) break
149
150 // Reject partial-word matches, e.g. "AnimeX" inside "AnimeXin" —
151 // only accept the term at an actual word boundary on both sides.
152 if (
153 isWordChar(node.data[index - 1]) ||
154 isWordChar(node.data[index + term.length])
155 ) {
156 searchFrom = index + 1
157 continue
158 }
159
160 const highlight = document.createElement('span')
161 highlight.className = 'search-result-highlight'
162 if (mode === 'solid') {
163 highlight.classList.add('search-result-highlight--solid')
164 }
165 const before = node.data.slice(0, index)
166 const match = node.data.slice(index, index + term.length)
167 const after = node.data.slice(index + term.length)
168 const fragment = document.createDocumentFragment()
169 if (before) fragment.append(before)
170 highlight.textContent = match
171 fragment.append(highlight)
172 if (after) fragment.append(after)
173 node.replaceWith(fragment)
174 return true
175 }
176 }
177 return false
178}
179
180const highlightSearchResult = (target?: HTMLElement) => {
181 removeSearchResultHighlights()
182 highlightTerm = ''
183 highlightTabPath = null
184
185 if (!isHighlightEnabled()) return
186
187 const term = getSearchResultText(searchResultText)
188 if (!target || !term) return
189
190 const panel = target.closest<HTMLElement>(
191 '.plugin-tabs--content[data-tab-anchor]'
192 )
193 highlightTabPath = panel ? getPanelTabPath(panel) : null
194 highlightTerm = term
195 applyHighlightWithin(target, term)
196}
197
198const reapplyHighlightIfNeeded = (panel: HTMLElement) => {
199 if (!highlightTerm || !highlightTabPath || !isHighlightEnabled()) return
200
201 const panelPath = getPanelTabPath(panel)
202 const isSamePanel = panelPath.length === highlightTabPath.length &&
203 panelPath.every((anchor, i) => anchor === highlightTabPath![i])
204 if (!isSamePanel) return
205
206 if (panel.querySelector('.search-result-highlight')) return
207 applyHighlightWithin(panel, highlightTerm)
208}
209
83210const getTargetByHash = (hash: string) => {
84211 const ids = [hash]
85212 try {
@@ -468,6 +595,7 @@ const openCollapsibles = async (target: HTMLElement) => {
468595const resetSearchNavigation = () => {
469596 searchNavigated = false
470597 searchQuery = ''
598 searchResultText = ''
471599}
472600
473601const tryOpenAnchoredContent = async () => {
@@ -485,6 +613,11 @@ const tryOpenAnchoredContent = async () => {
485613 const hash = window.location.hash.slice(1)
486614
487615 if (!hash) {
616 const scrollTarget = openedCollapsible ??
617 (selectedTabs
618 ? getSelectedTabScrollTarget(selectedTabs)
619 : document.querySelector<HTMLElement>('.VPDoc') ?? undefined)
620 if (searchNavigated) highlightSearchResult(scrollTarget)
488621 resetSearchNavigation()
489622 if (openedCollapsible) {
490623 scrollToElement(openedCollapsible, false)
@@ -512,6 +645,7 @@ const tryOpenAnchoredContent = async () => {
512645
513646 if (searchNavigated) {
514647 await openCollapsibles(target)
648 highlightSearchResult(target)
515649 const collapsiblePath = getOpenCollapsiblePath(target)
516650 if (collapsiblePath.length) {
517651 const tabPath = getEnclosingTabPath(target)
@@ -1107,12 +1241,14 @@ function setupManualCopyButtons() {
11071241 wrapTablesInRoot(node)
11081242 initCopyButtonsInRoot(node)
11091243 if (faviconsEnabled.value) applyFavicons(node)
1244 reapplyHighlightIfNeeded(node)
11101245 } else {
11111246 node.querySelectorAll<HTMLElement>('.plugin-tabs--content').forEach(
11121247 (panel) => {
11131248 wrapTablesInRoot(panel)
11141249 initCopyButtonsInRoot(panel)
11151250 if (faviconsEnabled.value) applyFavicons(panel)
1251 reapplyHighlightIfNeeded(panel)
11161252 }
11171253 )
11181254 }
@@ -1124,7 +1260,11 @@ function setupManualCopyButtons() {
11241260
11251261watch(
11261262 () => route.path,
1127 () => nextTick(() => { initTitleOnly(); setupManualCopyButtons() }),
1263 () => {
1264 highlightTerm = ''
1265 highlightTabPath = null
1266 nextTick(() => { initTitleOnly(); setupManualCopyButtons() })
1267 },
11281268 { flush: 'post' }
11291269)
11301270
@@ -1448,4 +1588,4 @@ onUnmounted(() => {
14481588 </span>
14491589 </template>
14501590 </Layout>
1451</template>
1591</template>
\ No newline at end of file
docs/.vitepress/theme/components/Search.vue +105 −47
@@ -25,7 +25,6 @@ import {
2525 onKeyStroke,
2626 useElementBounding,
2727 useEventListener,
28 useLocalStorage,
2928 useScrollLock,
3029 useSessionStorage,
3130 watchDebounced
@@ -45,6 +44,7 @@ import {
4544 Clock,
4645 File,
4746 Globe,
47 Highlighter,
4848 Hash,
4949 Layers,
5050 LayoutList,
@@ -65,6 +65,16 @@ import { useData } from '../composables/search/use-data'
6565import { useEffects } from '../composables/useEffects'
6666import { applyFavicons, useFavicons } from '../composables/useFavicons'
6767import { registerGlobalComponents } from '../globalComponents'
68import {
69 excerptPreload,
70 saveHistoryEnabled,
71 searchHistory,
72 searchMode,
73 searchResultHighlightMode,
74 showDetailedList,
75 type SearchHistoryEntry,
76 type SearchSortMode
77} from '../searchState'
6878import { enhanceAppWithTabs } from './tabs'
6979
7080export interface FooterTranslations {
@@ -265,23 +275,6 @@ watch(filterText, (v) => {
265275})
266276onBeforeUnmount(() => clearTimeout(urlDebounceTimer))
267277
268const showDetailedList = useLocalStorage(
269 'vitepress:local-search-detailed-list',
270 true
271)
272
273// Three search modes: 'exact' | 'fuzzy' | 'url'
274const searchMode = useLocalStorage<'exact' | 'fuzzy' | 'url'>(
275 'vitepress:local-search-mode',
276 'exact'
277)
278
279// How many result pages get their excerpts rendered ahead of time
280const excerptPreload = useLocalStorage<'off' | 'next' | 'all'>(
281 'vitepress:local-search-excerpt-preload',
282 'off'
283)
284
285278// Cycle through modes on mobile (only active button is visible, tap it to advance)
286279function cycleSearchMode() {
287280 const modes = ['exact', 'fuzzy', 'url'] as const
@@ -293,31 +286,22 @@ function cycleSearchMode() {
293286const matchExact = computed(() => searchMode.value === 'exact')
294287const urlSearchMode = computed(() => searchMode.value === 'url')
295288
296// Search history
297interface SearchHistoryEntry {
298 query: string
299 mode: SearchMode
300 path?: string[]
301 href?: string
302}
303
304const saveHistoryEnabled = useLocalStorage('vitepress:local-search-save-history', false)
305
306const searchHistory = useLocalStorage<SearchHistoryEntry[]>(
307 'vitepress:local-search-history',
308 []
309)
310
311289const showHistory = computed(
312290 () => !filterText.value && searchHistory.value.length > 0
313291)
314292
315function saveToHistory(query: string, mode: SearchMode, path?: string[], href?: string) {
293function saveToHistory(
294 query: string,
295 mode: SearchSortMode,
296 path?: string[],
297 href?: string,
298 resultText?: string
299) {
316300 const trimmed = query.trim()
317301 if (!trimmed || !saveHistoryEnabled.value) return
318302 const pathKey = (path ?? []).join('\n')
319303 searchHistory.value = [
320 { query: trimmed, mode, path, href },
304 { query: trimmed, mode, path, href, resultText },
321305 ...searchHistory.value.filter(
322306 (h) => !(h.query === trimmed && h.mode === mode && (h.path ?? []).join('\n') === pathKey)
323307 )
@@ -331,7 +315,9 @@ function removeFromHistory(index: number) {
331315function applyHistory(entry: SearchHistoryEntry) {
332316 if (entry.href) {
333317 window.dispatchEvent(
334 new CustomEvent('search-nav', { detail: { query: entry.query } })
318 new CustomEvent('search-nav', {
319 detail: { query: entry.query, resultText: entry.resultText }
320 })
335321 )
336322 router.go(entry.href)
337323 showSearch.value = false
@@ -347,7 +333,12 @@ const showSettingsPopup = ref(false)
347333const settingsButtonRef = ref<HTMLButtonElement>()
348334const settingsPopupRef = ref<HTMLDivElement>()
349335const settingsBounding = useElementBounding(settingsButtonRef)
350type HelpSection = 'search' | 'view' | 'preload' | 'history'
336type HelpSection =
337 | 'search'
338 | 'view'
339 | 'preload'
340 | 'highlight'
341 | 'history'
351342const activeHelpSection = ref<HelpSection | null>(null)
352343const helpPopupEl = ref<HTMLDivElement>()
353344const helpPopupPos = ref({ top: -9999, left: -9999 })
@@ -651,8 +642,6 @@ const pageMeta = (() => {
651642 return map
652643})()
653644
654type SearchMode = 'exact' | 'fuzzy' | 'url'
655
656645interface TextSearchWorkerPayload {
657646 results: (SearchResult & Result)[]
658647 terms: string[]
@@ -674,7 +663,7 @@ interface LoadIndexWorkerRequest {
674663interface TextSearchWorkerRequest {
675664 type: 'text-search'
676665 query: string
677 mode: SearchMode
666 mode: SearchSortMode
678667 pageOrderEntries: [string, number][]
679668}
680669
@@ -1797,9 +1786,11 @@ function getSearchResultHref(item: SearchResult & Result) {
17971786}
17981787
17991788function navigateToUrlResult(item: UrlResult) {
1800 saveToHistory(filterText.value, searchMode.value, [getPageLabel(item.pageId), ...item.titles, item.linkText].map(toHistoryPathHtml).filter(Boolean), buildResultHref(item.pageId, item.tabs, item.anchor))
1789 saveToHistory(filterText.value, searchMode.value, [getPageLabel(item.pageId), ...item.titles, item.linkText].map(toHistoryPathHtml).filter(Boolean), buildResultHref(item.pageId, item.tabs, item.anchor), item.linkText)
18011790 window.dispatchEvent(
1802 new CustomEvent('search-nav', { detail: { query: filterText.value } })
1791 new CustomEvent('search-nav', {
1792 detail: { query: filterText.value, resultText: item.linkText }
1793 })
18031794 )
18041795 router.go(buildResultHref(item.pageId, item.tabs, item.anchor))
18051796 showSearch.value = false
@@ -1837,10 +1828,10 @@ onKeyStroke('Enter', (e) => {
18371828 }
18381829
18391830 if (selectedPackage) {
1840 saveToHistory(filterText.value, searchMode.value, [getPageLabel(getPageKey(String(selectedPackage.id))), ...selectedPackage.titles, selectedPackage.title].map(toHistoryPathHtml).filter(Boolean), getSearchResultHref(selectedPackage))
1831 saveToHistory(filterText.value, searchMode.value, [getPageLabel(getPageKey(String(selectedPackage.id))), ...selectedPackage.titles, selectedPackage.title].map(toHistoryPathHtml).filter(Boolean), getSearchResultHref(selectedPackage), selectedPackage.title)
18411832 window.dispatchEvent(
18421833 new CustomEvent('search-nav', {
1843 detail: { query: filterText.value }
1834 detail: { query: filterText.value, resultText: selectedPackage.title }
18441835 })
18451836 )
18461837 router.go(getSearchResultHref(selectedPackage))
@@ -1849,10 +1840,10 @@ onKeyStroke('Enter', (e) => {
18491840})
18501841
18511842function onResultClick(item: SearchResult & Result) {
1852 saveToHistory(filterText.value, searchMode.value, [getPageLabel(getPageKey(String(item.id))), ...item.titles, item.title].map(toHistoryPathHtml).filter(Boolean), getSearchResultHref(item))
1843 saveToHistory(filterText.value, searchMode.value, [getPageLabel(getPageKey(String(item.id))), ...item.titles, item.title].map(toHistoryPathHtml).filter(Boolean), getSearchResultHref(item), item.title)
18531844 window.dispatchEvent(
18541845 new CustomEvent('search-nav', {
1855 detail: { query: filterText.value }
1846 detail: { query: filterText.value, resultText: item.title }
18561847 })
18571848 )
18581849 showSearch.value = false
@@ -2747,6 +2738,54 @@ function onMouseMove(e: MouseEvent) {
27472738 </button>
27482739 </div>
27492740 </div>
2741 <div class="settings-section">
2742 <div class="settings-section-header">
2743 <div class="settings-section-label">
2744 <Highlighter :size="14" stroke-width="1.75" />
2745 Highlight
2746 </div>
2747 <button
2748 type="button"
2749 class="settings-help-btn"
2750 :class="{ active: activeHelpSection === 'highlight' }"
2751 aria-label="Search result highlight help"
2752 @click.stop="toggleHelpSection('highlight', $event)"
2753 @mouseenter="onHelpEnter('highlight', $event)"
2754 @mouseleave="onHelpLeave"
2755 >
2756 <span class="i-carbon:help-filled settings-help-icon" />
2757 </button>
2758 </div>
2759 <div
2760 class="settings-options"
2761 :class="{ 'is-highlighted': activeHelpSection === 'highlight' }"
2762 >
2763 <button
2764 type="button"
2765 class="settings-option"
2766 :class="{ active: searchResultHighlightMode === 'soft' }"
2767 @click="searchResultHighlightMode = 'soft'"
2768 >
2769 <span>Soft</span>
2770 </button>
2771 <button
2772 type="button"
2773 class="settings-option"
2774 :class="{ active: searchResultHighlightMode === 'solid' }"
2775 @click="searchResultHighlightMode = 'solid'"
2776 >
2777 <span>Solid</span>
2778 </button>
2779 <button
2780 type="button"
2781 class="settings-option"
2782 :class="{ active: searchResultHighlightMode === 'off' }"
2783 @click="searchResultHighlightMode = 'off'"
2784 >
2785 <span>Off</span>
2786 </button>
2787 </div>
2788 </div>
27502789 <div class="settings-section">
27512790 <div class="settings-section-header">
27522791 <div class="settings-section-label">
@@ -2870,6 +2909,25 @@ function onMouseMove(e: MouseEvent) {
28702909 </div>
28712910 </div>
28722911 </template>
2912 <template v-else-if="activeHelpSection === 'highlight'">
2913 <h4 class="sh-title">
2914 <Highlighter :size="16" stroke-width="1.75" class="sh-title-icon" />
2915 Search Result Highlight
2916 </h4>
2917 <p class="sh-desc">
2918 Highlights the exact result you open.
2919 </p>
2920 <div class="sh-options">
2921 <div class="sh-option">
2922 <strong>Soft</strong>
2923 <span>Soft accent background with a solid border.</span>
2924 </div>
2925 <div class="sh-option">
2926 <strong>Solid</strong>
2927 <span>Solid accent fill with no border.</span>
2928 </div>
2929 </div>
2930 </template>
28732931 <template v-else-if="activeHelpSection === 'history'">
28742932 <h4 class="sh-title">
28752933 <Clock :size="16" stroke-width="1.75" class="sh-title-icon" />
@@ -3974,4 +4032,4 @@ html.effects-disabled .clear-button:active {
39744032 color: var(--vp-c-text-1);
39754033 opacity: 1;
39764034}
3977</style>
4035</style>
\ No newline at end of file
docs/.vitepress/theme/searchState.ts +46 −1
@@ -1,7 +1,52 @@
1import { useLocalStorage } from '@vueuse/core'
12import { ref } from 'vue'
23
4
5export type SearchResultHighlightMode = 'off' | 'soft' | 'solid'
6export type SearchSortMode = 'exact' | 'fuzzy' | 'url'
7export type SearchExcerptPreload = 'off' | 'next' | 'all'
8
9export interface SearchHistoryEntry {
10 query: string
11 mode: SearchSortMode
12 path?: string[]
13 href?: string
14 resultText?: string
15}
16
317export const searchOpen = ref(false)
418
19export const searchResultHighlightMode = useLocalStorage<SearchResultHighlightMode>(
20 'vitepress:local-search-result-highlight',
21 'off'
22)
23
24export const showDetailedList = useLocalStorage(
25 'vitepress:local-search-detailed-list',
26 true
27)
28
29export const searchMode = useLocalStorage<SearchSortMode>(
30 'vitepress:local-search-mode',
31 'exact'
32)
33
34// How many result pages get their excerpts rendered ahead of time
35export const excerptPreload = useLocalStorage<SearchExcerptPreload>(
36 'vitepress:local-search-excerpt-preload',
37 'off'
38)
39
40export const saveHistoryEnabled = useLocalStorage(
41 'vitepress:local-search-save-history',
42 false
43)
44
45export const searchHistory = useLocalStorage<SearchHistoryEntry[]>(
46 'vitepress:local-search-history',
47 []
48)
49
550export function openSearch() {
651 searchOpen.value = true
7}
52}
\ No newline at end of file
docs/.vitepress/theme/styles/style.scss +30 −1
@@ -192,6 +192,35 @@ $ease-in-expo: cubic-bezier(0.7, 0, 0.84, 0);
192192 --vp-badge-danger-bg: theme("colors.carnation.950");
193193}
194194
195.search-result-highlight {
196 display: inline-block;
197 position: relative;
198 padding: 0 0.25em;
199 border: 1px solid var(--vp-c-brand-1);
200 border-radius: 4px;
201 background-color: var(--vp-collapsible-bg);
202 color: var(--vp-c-brand-1);
203 font-size: 0.9em;
204 font-weight: 600;
205 line-height: 1.5;
206 white-space: nowrap;
207 vertical-align: baseline;
208}
209
210.search-result-highlight--solid {
211 border: none;
212 background-color: var(--vp-c-brand-1);
213 color: var(--vp-button-brand-text);
214}
215
216html:not(.dark) .search-result-highlight {
217 color: #fff;
218}
219
220html.dark .search-result-highlight {
221 color: #000;
222}
223
195224.vp-doc a {
196225 color: var(--vp-c-brand-2);
197226 text-decoration: underline;
@@ -2082,4 +2111,4 @@ html:not(.dark) .nolebase-ui-input-horizontal-option {
20822111.screen-menu-social-links {
20832112 padding-top: 8px;
20842113 border-top: 1px solid var(--vp-c-divider);
2085}
2114}
\ No newline at end of file