aboutsummaryrefslogtreecommitdiff
path: root/src/components/Search.js
blob: 43924b8f5492f080e236e6c2811e5a6d34a6f40c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import React, { Component } from "react";
import { Index } from "elasticlunr";
import Link from "./Link";

// Search component
export default class Search extends Component {
  constructor(props) {
    super(props);
    this.state = {
      query: ``,
      results: []
    };
  }

  render() {
    var list;
    if (this.state.results.length !== 0) {
      list = (
        <ul>
          {this.state.results.map(page => (
            <li key={page.id}>
              <Link to={page.path}>{page.name}</Link>
            </li>
          ))}
        </ul>
      );
    } else {
      if (this.state.query !== "") {
        list = <span>No curves found.</span>;
      } else {
        list = <span></span>;
      }
    }

    return (
      <div>
        <input type="text" value={this.state.query} onChange={this.search} />
        <br />
        {list}
      </div>
    );
  }
  getOrCreateIndex = () =>
    this.index
      ? this.index
      : // Create an elastic lunr index and hydrate with graphql query results
        Index.load(this.props.searchIndex);

  search = evt => {
    const query = evt.target.value;
    this.index = this.getOrCreateIndex();
    const results = this.index
      .search(query, { expand: true })
      // Map over each ID and return the full document
      .map(({ ref }) => this.index.documentStore.getDoc(ref));
    this.setState({
      query,
      // Query the index with search string to get an [] of IDs
      results: results
    });
  };
}