Skip to content

Commit 168b08e

Browse files
committed
feat: enter key open the first package when searching (#916)
1 parent 0b55ca4 commit 168b08e

1 file changed

Lines changed: 41 additions & 0 deletions

File tree

app/pages/search.vue

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -541,7 +541,48 @@ function focusElement(el: HTMLElement) {
541541
el.scrollIntoView({ block: 'nearest', behavior: 'smooth' })
542542
}
543543
544+
// Find latest package name
545+
function findLatestPackageName() {
546+
const packageName = displayResults.value?.[0]?.package.name
547+
if (packageName === query.value) {
548+
return packageName.split('/')
549+
}
550+
}
551+
552+
// Navigate to package page
553+
const navigateToPackage = debounce((packageName?: string[]) => {
554+
router.push({
555+
name: 'package',
556+
params: { package: packageName },
557+
})
558+
}, 500)
559+
544560
function handleResultsKeydown(e: KeyboardEvent) {
561+
// If the active element is an input and there are results, navigate to the first result
562+
if (e.key === 'Enter' && document.activeElement?.tagName === 'INPUT') {
563+
// After entering quickly and pressing Enter, find the latest packages
564+
const latestPackageName = findLatestPackageName()
565+
// Find successful . navigate to package page
566+
if (latestPackageName) return navigateToPackage(latestPackageName)
567+
// Waiting for the latest search results (maximum 1.5 seconds)
568+
let waitSearchResultInterval: ReturnType<typeof setInterval> | null
569+
function clearSearchResultInterval() {
570+
if (waitSearchResultInterval) clearInterval(waitSearchResultInterval)
571+
waitSearchResultInterval = null
572+
}
573+
waitSearchResultInterval = setInterval(() => {
574+
const latestPackageName = findLatestPackageName()
575+
if (latestPackageName) {
576+
clearSearchResultInterval()
577+
return navigateToPackage(latestPackageName)
578+
}
579+
}, 100)
580+
581+
setTimeout(() => {
582+
clearSearchResultInterval()
583+
}, 1500)
584+
}
585+
545586
if (totalSelectableCount.value <= 0) return
546587
547588
const elements = getFocusableElements()

0 commit comments

Comments
 (0)