SearchForm.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. import React from 'react';
  2. import PropTypes from 'prop-types';
  3. // Header.SearchForm
  4. export default class SearchForm extends React.Component {
  5. constructor(props) {
  6. super(props);
  7. this.state = {
  8. keyword: '',
  9. searchedKeyword: '',
  10. };
  11. this.handleChange = this.handleChange.bind(this);
  12. this.handleFocus = this.handleFocus.bind(this);
  13. this.handleBlur = this.handleBlur.bind(this);
  14. this.clearForm = this.clearForm.bind(this);
  15. this.ticker = null;
  16. }
  17. componentDidMount() {
  18. this.ticker = setInterval(this.searchFieldTicker.bind(this), this.props.pollInterval);
  19. }
  20. componentWillUnmount() {
  21. clearInterval(this.ticker);
  22. }
  23. search() {
  24. if (this.state.searchedKeyword != this.state.keyword) {
  25. this.props.onSearchFormChanged({keyword: this.state.keyword});
  26. this.setState({searchedKeyword: this.state.keyword});
  27. }
  28. }
  29. getFormClearComponent() {
  30. if (this.state.keyword !== '') {
  31. return <a className="search-top-clear" onClick={this.clearForm}><i className="fa fa-times-circle" /></a>;
  32. } else {
  33. return '';
  34. }
  35. }
  36. clearForm() {
  37. this.setState({keyword: ''});
  38. this.search();
  39. }
  40. searchFieldTicker() {
  41. this.search();
  42. }
  43. handleFocus(event) {
  44. this.props.isShown(true);
  45. }
  46. handleBlur(event) {
  47. //this.props.isShown(false);
  48. }
  49. handleChange(event) {
  50. const keyword = event.target.value;
  51. this.setState({keyword});
  52. }
  53. render() {
  54. const formClear = this.getFormClearComponent();
  55. return (
  56. <form
  57. action="/_search"
  58. className="search-form form-group input-group search-top-input-group"
  59. >
  60. <input
  61. autoComplete="off"
  62. type="text"
  63. className="search-top-input form-control"
  64. placeholder="Search ... Page Title (Path) and Content"
  65. name="q"
  66. value={this.state.keyword}
  67. onFocus={this.handleFocus}
  68. onBlur={this.handleBlur}
  69. onChange={this.handleChange}
  70. />
  71. <span className="input-group-btn">
  72. <button type="submit" className="btn btn-default">
  73. <i className="search-top-icon fa fa-search"></i>
  74. </button>
  75. </span>
  76. {formClear}
  77. </form>
  78. );
  79. }
  80. }
  81. SearchForm.propTypes = {
  82. onSearchFormChanged: PropTypes.func.isRequired,
  83. isShown: PropTypes.func.isRequired,
  84. pollInterval: PropTypes.number,
  85. };
  86. SearchForm.defaultProps = {
  87. pollInterval: 1000,
  88. };