Commit 579ebfe152

579ebfe1527b3c54c180ca851c0147c326f7c99a

parent: fc8d700ec6

Unsigned

Duck <57977673+woducku@users.noreply.github.com> · 2026-05-30 16:53 UTC

Update Search.vue

Layout: unified · split

docs/.vitepress/theme/components/Search.vue +405 −36
@@ -1,6 +1,6 @@
1<script lang="ts" setup> 1<script lang="ts" setup>
2import MiniSearch, { type SearchResult } from 'minisearch' 2import MiniSearch, { type SearchResult } from 'minisearch'
3import { dataSymbol, inBrowser, useRouter } from 'vitepress' 3import { type DefaultTheme, dataSymbol, inBrowser, useRouter } from 'vitepress'
4import { 4import {
5 computed, 5 computed,
6 createApp, 6 createApp,
@@ -36,6 +36,7 @@ import localSearchIndex from '@localSearchIndex'
36 36
37import { 37import {
38 ArrowRight, 38 ArrowRight,
39 ChevronRight,
39 Delete, 40 Delete,
40 File, 41 File,
41 Hash, 42 Hash,
@@ -47,6 +48,7 @@ import { enhanceAppWithTabs } from 'vitepress-plugin-tabs/client'
47import { LRUCache } from '../composables/search/lru-cache' 48import { LRUCache } from '../composables/search/lru-cache'
48import { createSearchTranslate } from '../composables/search/translation' 49import { createSearchTranslate } from '../composables/search/translation'
49import { useData } from '../composables/search/use-data' 50import { useData } from '../composables/search/use-data'
51import { sidebar } from '../../configs/constants'
50 52
51export interface FooterTranslations { 53export interface FooterTranslations {
52 selectText?: string 54 selectText?: string
@@ -174,12 +176,168 @@ watchEffect(() => {
174 176
175const results: Ref<(SearchResult & Result)[]> = shallowRef([]) 177const results: Ref<(SearchResult & Result)[]> = shallowRef([])
176 178
179const currentTerms = shallowRef(new Set<string>())
180
177const enableNoResults = ref(false) 181const enableNoResults = ref(false)
178 182
183const pageMeta = (() => {
184 const map = new Map<string, { label: string; order: number }>()
185 let order = 0
186 const stripIcon = (text: string) =>
187 text
188 .replace(/<[^>]*>/g, '')
189 .replace(/\s+/g, ' ')
190 .trim()
191 const walk = (items: DefaultTheme.SidebarItem[]) => {
192 for (const item of items) {
193 if (item.link) {
194 const key = item.link.replace(/\/$/, '')
195 if (!map.has(key)) {
196 map.set(key, { label: stripIcon(item.text ?? key), order: order++ })
197 }
198 }
199 if (item.items) walk(item.items)
200 }
201 }
202 walk(sidebar as DefaultTheme.SidebarItem[])
203 return map
204})()
205
206const activePageFilter = ref<string | null>(null)
207
208function getPageKey(id: string) {
209 return id.split('#')[0].replace(/\/$/, '')
210}
211
212function getPageLabel(key: string) {
213 return pageMeta.get(key)?.label ?? key.replace(/^\//, '')
214}
215
216function getPageOrder(key: string) {
217 return pageMeta.get(key)?.order ?? Number.MAX_SAFE_INTEGER
218}
219
220const pageGroups = computed(() => {
221 const map = new Map<string, { key: string; label: string; count: number }>()
222 for (const r of results.value) {
223 const key = getPageKey(r.id)
224 const existing = map.get(key)
225 if (existing) existing.count++
226 else map.set(key, { key, label: getPageLabel(key), count: 1 })
227 }
228 return [...map.values()].sort(
229 (a, b) => getPageOrder(a.key) - getPageOrder(b.key)
230 )
231})
232
233const filteredResults = computed(() => {
234 if (!activePageFilter.value) return results.value
235 return results.value.filter(
236 (r) => getPageKey(r.id) === activePageFilter.value
237 )
238})
239
240function setPageFilter(key: string | null) {
241 activePageFilter.value = activePageFilter.value === key ? null : key
242 selectedIndex.value = filteredResults.value.length ? 1 : -1
243 nextTick(() => {
244 if (resultsEl.value) resultsEl.value.scrollTop = 0
245 scrollToSelectedResult()
246 reapplyHighlights()
247 })
248}
249
250async function reapplyHighlights() {
251 if (!showDetailedList.value || !currentTerms.value.size) {
252 centerExcerptsUntilSettled()
253 return
254 }
255 await new Promise<void>((resolve) => {
256 mark.value?.unmark({
257 done: () => {
258 mark.value?.markRegExp(formMarkRegex(currentTerms.value), {
259 done: () => resolve()
260 })
261 }
262 })
263 })
264 await nextTick()
265 centerExcerptsUntilSettled()
266}
267
268watch(results, () => {
269 if (
270 activePageFilter.value &&
271 !pageGroups.value.some((g) => g.key === activePageFilter.value)
272 ) {
273 activePageFilter.value = null
274 }
275})
276
179watch(filterText, () => { 277watch(filterText, () => {
180 enableNoResults.value = false 278 enableNoResults.value = false
181}) 279})
182 280
281const ribbonTrack = shallowRef<HTMLElement>()
282const ribbonCanScrollLeft = ref(false)
283const ribbonCanScrollRight = ref(false)
284
285function getRibbonTrack(): HTMLElement | null {
286 return (
287 ribbonTrack.value ??
288 (el.value?.querySelector('.page-ribbon-track') as HTMLElement | null)
289 )
290}
291
292function updateRibbonOverflow() {
293 const track = getRibbonTrack()
294 if (!track) {
295 ribbonCanScrollLeft.value = false
296 ribbonCanScrollRight.value = false
297 return
298 }
299 ribbonCanScrollLeft.value = track.scrollLeft > 2
300 ribbonCanScrollRight.value =
301 track.scrollWidth - track.clientWidth - track.scrollLeft > 2
302}
303
304let ribbonAnimHandle = 0
305
306function scrollRibbon(direction: number) {
307 const track = getRibbonTrack()
308 if (!track) return
309 const max = track.scrollWidth - track.clientWidth
310 const amount = track.clientWidth * 0.7 * direction
311 const from = track.scrollLeft
312 const to = Math.max(0, Math.min(max, from + amount))
313 if (to === from) return
314
315 if (ribbonAnimHandle) cancelAnimationFrame(ribbonAnimHandle)
316 const duration = 280
317 const start = performance.now()
318 const ease = (t: number) => 1 - Math.pow(1 - t, 3)
319
320 const step = (now: number) => {
321 const t = Math.min(1, (now - start) / duration)
322 track.scrollLeft = from + (to - from) * ease(t)
323 updateRibbonOverflow()
324 if (t < 1) {
325 ribbonAnimHandle = requestAnimationFrame(step)
326 } else {
327 ribbonAnimHandle = 0
328 }
329 }
330 ribbonAnimHandle = requestAnimationFrame(step)
331}
332
333watch(pageGroups, () => {
334 nextTick(updateRibbonOverflow)
335})
336
337useEventListener('resize', () => {
338 updateRibbonOverflow()
339})
340
183const mark = computedAsync(async () => { 341const mark = computedAsync(async () => {
184 if (!resultsEl.value) return 342 if (!resultsEl.value) return
185 return markRaw(new Mark(resultsEl.value)) 343 return markRaw(new Mark(resultsEl.value))
@@ -278,6 +436,8 @@ watchDebounced(
278 return { ...r, text } 436 return { ...r, text }
279 }) 437 })
280 438
439 currentTerms.value = terms
440
281 await nextTick() 441 await nextTick()
282 if (canceled) return 442 if (canceled) return
283 443
@@ -289,39 +449,64 @@ watchDebounced(
289 }) 449 })
290 }) 450 })
291 451
292 const excerpts = el.value?.querySelectorAll('.result .excerpt') ?? [] 452 await nextTick()
293 const scrollMutations: { element: HTMLElement; scrollTop: number }[] = [] 453 await nextFrame()
294 for (let i = 0; i < excerpts.length; i++) { 454 if (canceled) return
295 const excerptElement = excerpts[i] as HTMLElement 455
296
297 const markNode = excerptElement.querySelector(
298 'mark[data-markjs="true"]'
299 ) as HTMLElement | null
300 if (markNode) {
301 const markRect = markNode.getBoundingClientRect()
302 const excerptRect = excerptElement.getBoundingClientRect()
303
304 const relativeTop = (markRect.top - excerptRect.top) +
305 excerptElement.scrollTop
306 const targetScrollTop = relativeTop -
307 (excerptElement.clientHeight / 2) + (markRect.height / 2)
308
309 scrollMutations.push({
310 element: excerptElement,
311 scrollTop: targetScrollTop
312 })
313 }
314 }
315 for (let i = 0; i < scrollMutations.length; i++) {
316 scrollMutations[i].element.scrollTop = scrollMutations[i].scrollTop
317 }
318 if (resultsEl.value) { 456 if (resultsEl.value) {
319 resultsEl.value.scrollTop = 0 457 resultsEl.value.scrollTop = 0
320 } 458 }
459 centerExcerptsUntilSettled()
321 }, 460 },
322 { debounce: 180, immediate: true } 461 { debounce: 180, immediate: true }
323) 462)
324 463
464function centerExcerpts() {
465 const excerpts = el.value?.querySelectorAll('.result .excerpt') ?? []
466 for (let i = 0; i < excerpts.length; i++) {
467 const excerptElement = excerpts[i] as HTMLElement
468
469 const markNode = excerptElement.querySelector(
470 'mark[data-markjs="true"]'
471 ) as HTMLElement | null
472 if (!markNode) continue
473
474 const viewportHeight =
475 Number.parseFloat(getComputedStyle(excerptElement).maxHeight) || 84
476
477 let offset = 0
478 let node: HTMLElement | null = markNode
479 while (node && node !== excerptElement) {
480 offset += node.offsetTop
481 node = node.offsetParent as HTMLElement | null
482 }
483
484 const targetScrollTop = offset - viewportHeight / 2 + markNode.offsetHeight / 2
485 excerptElement.scrollTop = Math.max(0, targetScrollTop)
486 }
487}
488
489let centerHandle = 0
490
491function centerExcerptsUntilSettled(duration = 450) {
492 if (centerHandle) cancelAnimationFrame(centerHandle)
493 const start = performance.now()
494 const tick = () => {
495 centerExcerpts()
496 if (performance.now() - start < duration) {
497 centerHandle = requestAnimationFrame(tick)
498 } else {
499 centerHandle = 0
500 }
501 }
502 centerHandle = requestAnimationFrame(tick)
503}
504
505onBeforeUnmount(() => {
506 if (centerHandle) cancelAnimationFrame(centerHandle)
507 if (ribbonAnimHandle) cancelAnimationFrame(ribbonAnimHandle)
508})
509
325const excerptCache = new LRUCache<string, unknown>(60) // 60 excerpts 510const excerptCache = new LRUCache<string, unknown>(60) // 60 excerpts
326 511
327async function fetchExcerpt(id: string) { 512async function fetchExcerpt(id: string) {
@@ -420,7 +605,7 @@ function onSearchBarClick(event: PointerEvent) {
420const selectedIndex = ref(-1) 605const selectedIndex = ref(-1)
421const disableMouseOver = ref(true) 606const disableMouseOver = ref(true)
422 607
423watch(results, (r) => { 608watch(filteredResults, (r) => {
424 selectedIndex.value = r.length ? 0 : -1 609 selectedIndex.value = r.length ? 0 : -1
425 scrollToSelectedResult() 610 scrollToSelectedResult()
426}) 611})
@@ -436,7 +621,7 @@ onKeyStroke('ArrowUp', (event) => {
436 event.preventDefault() 621 event.preventDefault()
437 selectedIndex.value-- 622 selectedIndex.value--
438 if (selectedIndex.value < 0) { 623 if (selectedIndex.value < 0) {
439 selectedIndex.value = results.value.length - 1 624 selectedIndex.value = filteredResults.value.length - 1
440 } 625 }
441 disableMouseOver.value = true 626 disableMouseOver.value = true
442 scrollToSelectedResult() 627 scrollToSelectedResult()
@@ -445,7 +630,7 @@ onKeyStroke('ArrowUp', (event) => {
445onKeyStroke('ArrowDown', (event) => { 630onKeyStroke('ArrowDown', (event) => {
446 event.preventDefault() 631 event.preventDefault()
447 selectedIndex.value++ 632 selectedIndex.value++
448 if (selectedIndex.value >= results.value.length + 1) { 633 if (selectedIndex.value >= filteredResults.value.length + 1) {
449 selectedIndex.value = 0 634 selectedIndex.value = 0
450 } 635 }
451 disableMouseOver.value = true 636 disableMouseOver.value = true
@@ -470,7 +655,7 @@ onKeyStroke('Enter', (e) => {
470 return 655 return
471 } 656 }
472 657
473 const selectedPackage = results.value[index] 658 const selectedPackage = filteredResults.value[index]
474 if (e.target instanceof HTMLInputElement && !selectedPackage) { 659 if (e.target instanceof HTMLInputElement && !selectedPackage) {
475 e.preventDefault() 660 e.preventDefault()
476 return 661 return
@@ -547,7 +732,10 @@ watch(
547 732
548 nextTick(() => { 733 nextTick(() => {
549 isLocked.value = true 734 isLocked.value = true
550 nextTick().then(() => activate()) 735 nextTick().then(() => {
736 activate()
737 updateRibbonOverflow()
738 })
551 }) 739 })
552 } 740 }
553) 741)
@@ -711,6 +899,63 @@ function onMouseMove(e: MouseEvent) {
711 </div> 899 </div>
712 </motion.form> 900 </motion.form>
713 901
902 <AnimatePresence>
903 <motion.div
904 v-if="pageGroups.length > 1"
905 layout="position"
906 class="page-ribbon"
907 :initial="{ opacity: 0, height: 0 }"
908 :animate="{ opacity: 1, height: 'auto' }"
909 :exit="{ opacity: 0, height: 0 }"
910 :transition="{ duration: 0.4, ease: [0.16, 1, 0.3, 1] }"
911 >
912 <button
913 v-if="ribbonCanScrollLeft"
914 type="button"
915 class="page-ribbon-arrow left"
916 aria-label="Scroll filters left"
917 @click="scrollRibbon(-1)"
918 >
919 <ChevronRight :size="18" stroke-width="1.75" />
920 </button>
921 <div
922 ref="ribbonTrack"
923 class="page-ribbon-track"
924 @scroll="updateRibbonOverflow"
925 >
926 <button
927 type="button"
928 class="page-pill"
929 :class="{ active: activePageFilter === null }"
930 @click="setPageFilter(null)"
931 >
932 All
933 <span class="page-pill-count">{{ results.length }}</span>
934 </button>
935 <button
936 v-for="group in pageGroups"
937 :key="group.key"
938 type="button"
939 class="page-pill"
940 :class="{ active: activePageFilter === group.key }"
941 @click="setPageFilter(group.key)"
942 >
943 <span class="page-pill-label">{{ group.label }}</span>
944 <span class="page-pill-count">{{ group.count }}</span>
945 </button>
946 </div>
947 <button
948 v-if="ribbonCanScrollRight"
949 type="button"
950 class="page-ribbon-arrow right"
951 aria-label="Scroll filters right"
952 @click="scrollRibbon(1)"
953 >
954 <ChevronRight :size="18" stroke-width="1.75" />
955 </button>
956 </motion.div>
957 </AnimatePresence>
958
714 <ul 959 <ul
715 ref="resultsEl" 960 ref="resultsEl"
716 :id="results?.length ? 'localsearch-list' : undefined" 961 :id="results?.length ? 'localsearch-list' : undefined"
@@ -722,7 +967,7 @@ function onMouseMove(e: MouseEvent) {
722 <AnimatePresence> 967 <AnimatePresence>
723 <motion.div 968 <motion.div
724 class="flex flex-col justify-center items-center h-47.5 gap-2 font-medium text-sm text-gray-500 dark:text-gray-300 m-auto md:mt-10 md:mb-6 opacity-90" 969 class="flex flex-col justify-center items-center h-47.5 gap-2 font-medium text-sm text-gray-500 dark:text-gray-300 m-auto md:mt-10 md:mb-6 opacity-90"
725 v-if="!filterText || (filterText && !results.length)" 970 v-if="!filterText || (filterText && !filteredResults.length)"
726 :initial="{ 971 :initial="{
727 opacity: 0 972 opacity: 0
728 }" 973 }"
@@ -749,7 +994,7 @@ function onMouseMove(e: MouseEvent) {
749 src="/asset/smolame.png" 994 src="/asset/smolame.png"
750 alt="Smol ame" 995 alt="Smol ame"
751 /> 996 />
752 <h1 v-if="filterText && !results.length"> 997 <h1 v-if="filterText && !filteredResults.length">
753 Couldn't find anything, try again? 998 Couldn't find anything, try again?
754 </h1> 999 </h1>
755 <h1 v-else>Looking for something?</h1> 1000 <h1 v-else>Looking for something?</h1>
@@ -758,7 +1003,7 @@ function onMouseMove(e: MouseEvent) {
758 1003
759 <AnimatePresence> 1004 <AnimatePresence>
760 <motion.li 1005 <motion.li
761 v-for="(p, index) in results" 1006 v-for="(p, index) in filteredResults"
762 :key="p.id" 1007 :key="p.id"
763 layout 1008 layout
764 class="result-layout" 1009 class="result-layout"
@@ -957,6 +1202,130 @@ function onMouseMove(e: MouseEvent) {
957 border-color: var(--vp-c-brand-1); 1202 border-color: var(--vp-c-brand-1);
958} 1203}
959 1204
1205.page-ribbon {
1206 display: block;
1207 padding: 12px 0 4px;
1208 padding-inline: calc(var(--spacing) * 3);
1209 position: relative;
1210 min-width: 0;
1211 flex: none;
1212}
1213
1214.page-ribbon-track {
1215 display: flex;
1216 flex-wrap: nowrap;
1217 gap: 8px;
1218 min-width: 0;
1219 overflow-x: auto;
1220 overflow-y: hidden;
1221 scrollbar-width: none;
1222 -ms-overflow-style: none;
1223 overscroll-behavior-x: contain;
1224}
1225
1226.page-ribbon-track::-webkit-scrollbar {
1227 display: none;
1228 width: 0;
1229 height: 0;
1230}
1231
1232.page-ribbon-arrow {
1233 position: absolute;
1234 top: 50%;
1235 transform: translateY(-50%);
1236 z-index: 2;
1237 display: inline-flex;
1238 align-items: center;
1239 justify-content: center;
1240 width: 30px;
1241 height: 30px;
1242 border-radius: 999px;
1243 border: 1px solid var(--vp-c-divider);
1244 background: var(--vp-local-search-bg, var(--vp-c-bg-soft));
1245 color: var(--vp-c-text-1);
1246 cursor: pointer;
1247 box-shadow: 0 2px 8px rgba(0, 0, 0, 0.18);
1248 transition: color 0.15s, border-color 0.15s, background-color 0.15s;
1249}
1250
1251.page-ribbon-arrow:hover {
1252 color: var(--vp-c-brand-1);
1253 border-color: var(--vp-c-brand-1);
1254}
1255
1256.page-ribbon-arrow.right {
1257 right: calc(var(--spacing) * 3);
1258}
1259
1260.page-ribbon-arrow.left {
1261 left: calc(var(--spacing) * 3);
1262}
1263
1264.page-ribbon-arrow.left svg {
1265 transform: rotate(180deg);
1266}
1267
1268.page-pill {
1269 flex: none;
1270 display: inline-flex;
1271 align-items: center;
1272 gap: 6px;
1273 padding: 8px 14px;
1274 font-size: 0.8rem;
1275 line-height: 1.2;
1276 white-space: nowrap;
1277 border-radius: 999px;
1278 border: 1px solid var(--vp-c-divider);
1279 background: var(--vp-c-bg-soft);
1280 color: var(--vp-c-text-2);
1281 cursor: pointer;
1282 transition: color 0.15s, border-color 0.15s, background-color 0.15s;
1283}
1284
1285.page-pill:hover {
1286 color: var(--vp-c-text-1);
1287 border-color: var(--vp-c-brand-1);
1288}
1289
1290.page-pill.active {
1291 color: var(--vp-c-brand-1);
1292 border-color: var(--vp-c-brand-1);
1293 background: rgba(86, 180, 252, 0.12);
1294}
1295
1296.page-pill-label {
1297 max-width: 180px;
1298 overflow: hidden;
1299 text-overflow: ellipsis;
1300}
1301
1302.page-pill-count {
1303 font-variant-numeric: tabular-nums;
1304 font-size: 0.7rem;
1305 padding: 1px 6px;
1306 border-radius: 999px;
1307 background: rgba(128, 128, 128, 0.15);
1308 color: inherit;
1309}
1310
1311.page-pill.active .page-pill-count {
1312 background: rgba(86, 180, 252, 0.22);
1313}
1314
1315@media (max-width: 767px) {
1316 .page-ribbon {
1317 padding: 14px 0 4px;
1318 }
1319
1320 .page-pill {
1321 padding: 9px 14px;
1322 font-size: 0.82rem;
1323 background: var(--vp-c-bg-elv, var(--vp-c-bg-soft));
1324 border-color: var(--vp-c-divider);
1325 color: var(--vp-c-text-1);
1326 }
1327}
1328
960.local-search-icon { 1329.local-search-icon {
961 display: block; 1330 display: block;
962 font-size: 18px; 1331 font-size: 18px;
@@ -1208,4 +1577,4 @@ svg {
1208 background-color: rgba(var(--vp-c-brand-1), 0.1); 1577 background-color: rgba(var(--vp-c-brand-1), 0.1);
1209 border-radius: 4px; 1578 border-radius: 4px;
1210} 1579}
1211</style> 1580</style>\ No newline at end of file