]> BookStack Code Mirror - bookstack/blob - resources/js/components/entity-selector-popup.js
Default chapter templates: Added tests, extracted repo logic
[bookstack] / resources / js / components / entity-selector-popup.js
1 import {Component} from './component';
2
3 export class EntitySelectorPopup extends Component {
4
5     setup() {
6         this.container = this.$el;
7         this.selectButton = this.$refs.select;
8         this.selectorEl = this.$refs.selector;
9
10         this.callback = null;
11         this.selection = null;
12
13         this.selectButton.addEventListener('click', this.onSelectButtonClick.bind(this));
14         window.$events.listen('entity-select-change', this.onSelectionChange.bind(this));
15         window.$events.listen('entity-select-confirm', this.handleConfirmedSelection.bind(this));
16     }
17
18     /**
19      * Show the selector popup.
20      * @param {Function} callback
21      * @param {String} searchText
22      * @param {EntitySelectorSearchOptions} searchOptions
23      */
24     show(callback, searchText = '', searchOptions = {}) {
25         this.callback = callback;
26         this.getSelector().configureSearchOptions(searchOptions);
27         this.getPopup().show();
28
29         if (searchText) {
30             this.getSelector().searchText(searchText);
31         }
32
33         this.getSelector().focusSearch();
34     }
35
36     hide() {
37         this.getPopup().hide();
38     }
39
40     /**
41      * @returns {Popup}
42      */
43     getPopup() {
44         return window.$components.firstOnElement(this.container, 'popup');
45     }
46
47     /**
48      * @returns {EntitySelector}
49      */
50     getSelector() {
51         return window.$components.firstOnElement(this.selectorEl, 'entity-selector');
52     }
53
54     onSelectButtonClick() {
55         this.handleConfirmedSelection(this.selection);
56     }
57
58     onSelectionChange(entity) {
59         this.selection = entity;
60         if (entity === null) {
61             this.selectButton.setAttribute('disabled', 'true');
62         } else {
63             this.selectButton.removeAttribute('disabled');
64         }
65     }
66
67     handleConfirmedSelection(entity) {
68         this.hide();
69         this.getSelector().reset();
70         if (this.callback && entity) this.callback(entity);
71     }
72
73 }