]> BookStack Code Mirror - bookstack/blob - resources/js/components/global-search.js
Replaced JS logic with CSS focus-within logic
[bookstack] / resources / js / components / global-search.js
1 /**
2  * @extends {Component}
3  */
4 import {htmlToDom} from "../services/dom";
5
6 class GlobalSearch {
7
8     setup() {
9         this.container = this.$el;
10         this.input = this.$refs.input;
11         this.suggestions = this.$refs.suggestions;
12         this.suggestionResultsWrap = this.$refs.suggestionResults;
13
14         this.setupListeners();
15     }
16
17     setupListeners() {
18         this.input.addEventListener('input', () => {
19             const value = this.input.value;
20             if (value.length > 0) {
21                 this.updateSuggestions(value);
22             }  else {
23                 this.hideSuggestions();
24             }
25         });
26     }
27
28     async updateSuggestions(search) {
29         const {data: results} = await window.$http.get('/ajax/search/entities', {term: search, count: 5});
30         const resultDom = htmlToDom(results);
31
32         const childrenToTrim = Array.from(resultDom.children).slice(9);
33         for (const child of childrenToTrim) {
34             child.remove();
35         }
36
37         this.suggestionResultsWrap.innerHTML = '';
38         this.suggestionResultsWrap.append(resultDom);
39         if (!this.container.classList.contains('search-active')) {
40             this.showSuggestions();
41         }
42     }
43
44     showSuggestions() {
45         this.container.classList.add('search-active');
46         window.requestAnimationFrame(() => {
47             this.suggestions.classList.add('search-suggestions-animation');
48         })
49     }
50
51     hideSuggestions() {
52         this.container.classList.remove('search-active');
53         this.suggestions.classList.remove('search-suggestions-animation');
54         this.suggestionResultsWrap.innerHTML = '';
55     }
56 }
57
58 export default GlobalSearch;