Skip to content

Commit

Permalink
[www] Search shortcut (#3654)
Browse files Browse the repository at this point in the history
* Add keyboard shortcut for focussing the search input

* Blur input on result selection
  • Loading branch information
m-allanson authored and calcsam committed Jan 23, 2018
1 parent 735c0ce commit a263f98
Showing 1 changed file with 21 additions and 1 deletion.
22 changes: 21 additions & 1 deletion www/src/components/search-form.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ css.insert(`
font-weight: normal !important;
padding: ${rhythm(0.25)} ${rhythm(0.5)} !important;
}
.algolia-autocomplete .algolia-docsearch-suggestion--subcategory-column:before {
background: ${presets.veryLightPurple} !important;
}
Expand Down Expand Up @@ -227,6 +227,8 @@ class SearchForm extends Component {
constructor() {
super()
this.state = { enabled: true }
this.autocompleteSelected = this.autocompleteSelected.bind(this)
this.focusSearchInput = this.focusSearchInput.bind(this)
}

/**
Expand All @@ -241,9 +243,17 @@ class SearchForm extends Component {
// eslint-disable-next-line no-undef
const a = document.createElement(`a`)
a.href = e._args[0].url
this.searchInput.blur()
navigateTo(`${a.pathname}${a.hash}`)
}

focusSearchInput(e) {
if (e.key !== `s`) return
if (document.activeElement === this.searchInput) return // eslint-disable-line no-undef
e.preventDefault()
this.searchInput.focus()
}

componentDidMount() {
if (
typeof window === `undefined` || // eslint-disable-line no-undef
Expand All @@ -254,6 +264,9 @@ class SearchForm extends Component {
return
}

// eslint-disable-next-line no-undef
window.addEventListener(`keydown`, this.focusSearchInput)

// eslint-disable-next-line no-undef
window.addEventListener(
`autocomplete:selected`,
Expand All @@ -270,6 +283,11 @@ class SearchForm extends Component {
})
}

componentWillUnmount() {
// eslint-disable-next-line no-undef
window.removeEventListener(`keydown`, this.focusSearchInput)
}

render() {
const { enabled } = this.state
const { styles } = this.props.styles
Expand Down Expand Up @@ -320,6 +338,8 @@ class SearchForm extends Component {
type="search"
placeholder="Search docs"
aria-label="Search docs"
title="Hit 's' to search docs"
ref={(input) => { this.searchInput = input }}
/>
</form>
) : null
Expand Down

0 comments on commit a263f98

Please sign in to comment.