SearchPage.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. // This is the root component for #search-page
  2. import React from 'react';
  3. import axios from 'axios'
  4. import SearchForm from './SearchPage/SearchForm';
  5. import SearchResult from './SearchPage/SearchResult';
  6. export default class SearchPage extends React.Component {
  7. constructor(props) {
  8. super(props);
  9. this.state = {
  10. location: location,
  11. searchingKeyword: this.props.query.q || '',
  12. searchedPages: [],
  13. searchResultMeta: {},
  14. searchError: null,
  15. }
  16. this.search = this.search.bind(this);
  17. this.changeURL = this.changeURL.bind(this);
  18. }
  19. componentDidMount() {
  20. if (this.state.searchingKeyword !== '') {
  21. this.search({keyword: this.state.searchingKeyword});
  22. this.setState({searchedKeyword: this.state.keyword});
  23. }
  24. }
  25. static getQueryByLocation(location) {
  26. let search = location.search || '';
  27. let query = {};
  28. search.replace(/^\?/, '').split('&').forEach(function(element) {
  29. let queryParts = element.split('=');
  30. query[queryParts[0]] = decodeURIComponent(queryParts[1]).replace(/\+/g, ' ');
  31. });
  32. return query;
  33. }
  34. changeURL(keyword) {
  35. // TODO 整理する
  36. if (location && location.hash) {
  37. location.hash = '';
  38. }
  39. if (window.history && window.history.pushState){
  40. history.pushState('', '', `/_search?q=${keyword}`);
  41. }
  42. }
  43. search(data) {
  44. const keyword = data.keyword;
  45. if (keyword === '') {
  46. this.setState({
  47. searchingKeyword: '',
  48. searchedPages: [],
  49. });
  50. return true;
  51. }
  52. this.setState({
  53. searchingKeyword: keyword,
  54. });
  55. axios.get('/_api/search', {params: {q: keyword}})
  56. .then((res) => {
  57. if (res.data.ok) {
  58. this.setState({
  59. searchingKeyword: keyword,
  60. searchedPages: res.data.data,
  61. searchResultMeta: res.data.meta,
  62. });
  63. }
  64. this.changeURL(keyword);
  65. // TODO error
  66. })
  67. .catch((res) => {
  68. // TODO error
  69. });
  70. };
  71. render() {
  72. return (
  73. <div>
  74. <div className="header-wrap">
  75. <header>
  76. <SearchForm
  77. onSearchFormChanged={this.search}
  78. keyword={this.state.searchingKeyword}
  79. />
  80. </header>
  81. </div>
  82. <SearchResult
  83. pages={this.state.searchedPages}
  84. searchingKeyword={this.state.searchingKeyword}
  85. searchResultMeta={this.state.searchResultMeta}
  86. />
  87. </div>
  88. );
  89. }
  90. }
  91. SearchPage.propTypes = {
  92. query: React.PropTypes.object,
  93. };
  94. SearchPage.defaultProps = {
  95. //pollInterval: 1000,
  96. query: SearchPage.getQueryByLocation(location || {}),
  97. };