Skip to content

Commit 1ba06ae

Browse files
evaerakefranabg
authored andcommitted
feat($plugin-search): Add support for search hotkeys (#1848)
1 parent 0434f15 commit 1ba06ae

File tree

3 files changed

+26
-3
lines changed

3 files changed

+26
-3
lines changed

packages/@vuepress/plugin-search/SearchBox.vue

+17-2
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
@keyup.enter="go(focusIndex)"
1414
@keyup.up="onUp"
1515
@keyup.down="onDown"
16+
ref="input"
1617
>
1718
<ul
1819
class="suggestions"
@@ -37,7 +38,7 @@
3738
</template>
3839

3940
<script>
40-
/* global SEARCH_MAX_SUGGESTIONS, SEARCH_PATHS */
41+
/* global SEARCH_MAX_SUGGESTIONS, SEARCH_PATHS, SEARCH_HOTKEYS */
4142
export default {
4243
data () {
4344
return {
@@ -50,7 +51,13 @@ export default {
5051
5152
mounted () {
5253
this.placeholder = this.$site.themeConfig.searchPlaceholder || ''
54+
document.addEventListener('keydown', this.onHotkey)
5355
},
56+
57+
beforeDestroy () {
58+
document.removeEventListener('keydown', this.onHotkey)
59+
},
60+
5461
computed: {
5562
showSuggestions () {
5663
return (
@@ -70,7 +77,8 @@ export default {
7077
const max = this.$site.themeConfig.searchMaxSuggestions || SEARCH_MAX_SUGGESTIONS
7178
const localePath = this.$localePath
7279
const matches = item => (
73-
item.title
80+
item
81+
&& item.title
7482
&& item.title.toLowerCase().indexOf(query) > -1
7583
)
7684
const res = []
@@ -136,6 +144,13 @@ export default {
136144
}).length > 0
137145
},
138146
147+
onHotkey (event) {
148+
if (event.srcElement === document.body && SEARCH_HOTKEYS.includes(event.key)) {
149+
this.$refs.input.focus()
150+
event.preventDefault()
151+
}
152+
},
153+
139154
onUp () {
140155
if (this.showSuggestions) {
141156
if (this.focusIndex > 0) {

packages/@vuepress/plugin-search/index.js

+2-1
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ module.exports = (options) => ({
88

99
define: {
1010
SEARCH_MAX_SUGGESTIONS: options.searchMaxSuggestions || 5,
11-
SEARCH_PATHS: options.test || null
11+
SEARCH_PATHS: options.test || null,
12+
SEARCH_HOTKEYS: options.searchHotkeys || ['s', '/']
1213
}
1314
})

packages/docs/docs/plugin/official/plugin-search.md

+7
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,13 @@ You can set up searchable paths with `test` as:
9595

9696
Otherwise, the default search will return duplicates, once you can have similar content between folders `/master/`, `/1.0/` and `/2.0/`.
9797

98+
### searchHotkeys
99+
100+
- Type: `Array<string>`
101+
- Default: `['s', '/']`
102+
103+
Configure the hotkeys which when pressed will focus the search box. Set to an empty array to disable this feature.
104+
98105
## Tips
99106

100107
### Tweak the default colors.

0 commit comments

Comments
 (0)