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