aboutsummaryrefslogtreecommitdiff
path: root/app/javascript/controllers/search_controller.js
blob: 3a47d67355549298fa38f2d4506bc82f2140fc98 (plain)
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
import { Controller } from "@hotwired/stimulus"

// Controller that dynamically fetches search results from the body as
// introduced on an input. Then it fills the `results` elements with them.
export default class extends Controller {
  static targets = ["body"]
  static values = {
    initialBody: String
  }

  connect() {
    this.initialBody = this.bodyTarget.value.trim();
    document.getElementById("search_body").focus();
  }

  load(event) {
    event.preventDefault();

    try {
      fetch("/searches/search?" + new URLSearchParams({body: this.bodyTarget.value}))
        .then(response => response.text())
        .then(html => {
          document.getElementById("results").innerHTML = html;

          if (this.initialBody != this.bodyTarget.value) {
            document.getElementById("save-search").classList.remove('hidden');
          } else {
            document.getElementById("save-search").classList.add('hidden');
          }
        })
    } catch (error) {
      document.getElementById("results").innerHTML = '<div class="notice">Something went wrong!</div>'
    }
  }

  save(event) {
    event.preventDefault();

    document.getElementById("search-form-submit").classList.toggle("hidden");
    document.getElementById("save-search").classList.toggle("hidden");
    document.getElementById("search-form-name").classList.toggle("hidden");
    document.getElementById("search-form-description").classList.toggle("hidden");
    document.getElementById("search-form-shared").classList.toggle("hidden");
    document.getElementById("search-body-label").classList.toggle("hidden");
    document.getElementById("search_name").focus();
  }
}