]> BookStack Code Mirror - bookstack/blob - resources/js/components/entity-search.js
Finished updating remainder of JS components to new system
[bookstack] / resources / js / components / entity-search.js
1 import {onSelect} from "../services/dom";
2 import {Component} from "./component";
3
4 export class EntitySearch extends Component {
5     setup() {
6         this.entityId = this.$opts.entityId;
7         this.entityType = this.$opts.entityType;
8
9         this.contentView = this.$refs.contentView;
10         this.searchView = this.$refs.searchView;
11         this.searchResults = this.$refs.searchResults;
12         this.searchInput = this.$refs.searchInput;
13         this.searchForm = this.$refs.searchForm;
14         this.clearButton = this.$refs.clearButton;
15         this.loadingBlock = this.$refs.loadingBlock;
16
17         this.setupListeners();
18     }
19
20     setupListeners() {
21         this.searchInput.addEventListener('change', this.runSearch.bind(this));
22         this.searchForm.addEventListener('submit', e => {
23             e.preventDefault();
24             this.runSearch();
25         });
26
27         onSelect(this.clearButton, this.clearSearch.bind(this));
28     }
29
30     runSearch() {
31         const term = this.searchInput.value.trim();
32         if (term.length === 0) {
33             return this.clearSearch();
34         }
35
36         this.searchView.classList.remove('hidden');
37         this.contentView.classList.add('hidden');
38         this.loadingBlock.classList.remove('hidden');
39
40         const url = window.baseUrl(`/search/${this.entityType}/${this.entityId}`);
41         window.$http.get(url, {term}).then(resp => {
42             this.searchResults.innerHTML = resp.data;
43         }).catch(console.error).then(() => {
44             this.loadingBlock.classList.add('hidden');
45         });
46     }
47
48     clearSearch() {
49         this.searchView.classList.add('hidden');
50         this.contentView.classList.remove('hidden');
51         this.loadingBlock.classList.add('hidden');
52         this.searchInput.value = '';
53     }
54 }