scinote-web/app/javascript/packs/shared/navigation/components/SearchDropdown.jsx

104 lines
2.6 KiB
React
Raw Normal View History

2017-08-07 15:31:24 +08:00
import React, { Component } from "react";
2017-08-09 18:46:04 +08:00
import {
NavDropdown,
MenuItem,
FormGroup,
InputGroup,
Glyphicon
} from "react-bootstrap";
import styled from "styled-components";
import { FormattedMessage } from "react-intl";
2017-08-08 21:44:28 +08:00
import { SEARCH_PATH } from "../../../app/routes";
2017-08-09 22:01:03 +08:00
import { ENTER_KEY_CODE } from "../../../app/constants/numeric";
2017-08-07 15:31:24 +08:00
2017-08-09 18:46:04 +08:00
const StyledFormGroup = styled(FormGroup)`
margin-bottom: 0px;
`;
const StyledMenuItem = styled(MenuItem)`
padding-top: 10px;
padding-bottom: 10px;
`;
const StyledNavDropdown = styled(NavDropdown)`
& > .dropdown-menu {
width: 250px;
}
`;
2017-08-07 15:31:24 +08:00
class SearchDropdown extends Component {
constructor(props) {
super(props);
this.state = { searchTerm: "" };
this.handleSearchTermChange = this.handleSearchTermChange.bind(this);
2017-08-08 21:44:28 +08:00
this.handleKeyPress = this.handleKeyPress.bind(this);
this.setFocusToInput = this.setFocusToInput.bind(this);
2017-08-09 18:46:04 +08:00
this.submitSearch = this.submitSearch.bind(this);
2017-08-07 15:31:24 +08:00
}
2017-08-08 21:44:28 +08:00
setFocusToInput(ev) {
this.navSearchInput.focus();
ev.stopPropagation();
ev.nativeEvent.stopImmediatePropagation();
2017-08-07 15:31:24 +08:00
}
2017-08-08 21:44:28 +08:00
handleKeyPress(ev) {
2017-08-09 22:01:03 +08:00
if (ev.charCode === ENTER_KEY_CODE) {
2017-08-09 18:46:04 +08:00
this.submitSearch();
2017-08-08 21:44:28 +08:00
}
}
handleSearchTermChange(ev) {
this.setState({ searchTerm: ev.target.value });
2017-08-07 15:31:24 +08:00
}
2017-08-09 18:46:04 +08:00
submitSearch() {
window.location = `${SEARCH_PATH}?q=${this.state.searchTerm}`;
this.setState({ searchTerm: "" });
}
2017-08-07 15:31:24 +08:00
render() {
return (
2017-08-09 18:46:04 +08:00
<StyledNavDropdown
2017-08-07 17:13:09 +08:00
noCaret
title={
<span>
<span className="glyphicon glyphicon-search" />&nbsp;
<span className="visible-xs-inline visible-sm-inline">
<FormattedMessage id="navbar.search_label" />
</span>
</span>
}
2017-08-08 21:44:28 +08:00
onClick={this.setFocusToInput}
2017-08-07 19:51:22 +08:00
id="search-dropdown"
2017-08-07 15:31:24 +08:00
>
2017-08-09 18:46:04 +08:00
<StyledMenuItem>
<StyledFormGroup>
<InputGroup>
<input
onChange={this.handleSearchTermChange}
onClick={this.setFocusToInput}
onKeyPress={this.handleKeyPress}
ref={el => {
this.navSearchInput = el;
}}
type="text"
placeholder="Search"
className="form-control"
/>
<InputGroup.Addon
onClick={this.submitSearch}
className="visible-xs visible-sm"
>
<Glyphicon glyph="menu-right" />
</InputGroup.Addon>
</InputGroup>
</StyledFormGroup>
</StyledMenuItem>
</StyledNavDropdown>
2017-08-07 15:31:24 +08:00
);
}
}
export default SearchDropdown;