Allow the search bar to be focused with '/' and closed with 'esc'

This commit is contained in:
itepechi 2023-11-10 06:35:49 +09:00
parent 315d306eb4
commit 8398670530
2 changed files with 39 additions and 0 deletions

View File

@ -10,6 +10,12 @@ library.add(
)
const SearchBar = {
mounted () {
window.addEventListener('keydown', this.autoFocus)
},
beforeDestroy () {
window.removeEventListener('keydown', this.autoFocus)
},
data: () => ({
searchTerm: undefined,
hidden: true,
@ -36,6 +42,36 @@ const SearchBar = {
this.$refs.searchInput.focus()
}
})
},
autoFocus (event) {
if (
event.target.tagName !== 'BODY' ||
event.altKey ||
event.ctrlKey ||
event.isComposing ||
event.metaKey ||
event.repeat ||
event.shiftKey
) {
return
}
if (event.key === '/') {
if (this.hidden) {
this.toggleHidden()
} else {
this.$refs.searchInput.focus()
}
event.preventDefault()
} else if (event.key === 'Escape') {
if (!this.hidden) {
this.toggleHidden()
}
event.preventDefault()
}
},
blur () {
this.$refs.searchInput.blur()
}
}
}

View File

@ -27,6 +27,9 @@
@keydown.enter="
$event.isComposing || $event.keyCode === 229 || find(searchTerm)
"
@keydown.escape="
$event.isComposing || blur()
"
>
<button
class="button-default search-button"