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