]> BookStack Code Mirror - bookstack/blob - resources/js/components/page-picker.js
577e9f6db7c8a19491c37860a20a6bd6711d3445
[bookstack] / resources / js / components / page-picker.js
1
2 class PagePicker {
3
4     constructor(elem) {
5         this.elem = elem;
6         this.input = elem.querySelector('input');
7         this.resetButton = elem.querySelector('[page-picker-reset]');
8         this.selectButton = elem.querySelector('[page-picker-select]');
9         this.display = elem.querySelector('[page-picker-display]');
10         this.defaultDisplay = elem.querySelector('[page-picker-default]');
11         this.buttonSep = elem.querySelector('span.sep');
12
13         this.value = this.input.value;
14         this.setupListeners();
15     }
16
17     setupListeners() {
18         this.selectButton.addEventListener('click', this.showPopup.bind(this));
19         this.display.parentElement.addEventListener('click', this.showPopup.bind(this));
20
21         this.resetButton.addEventListener('click', event => {
22             this.setValue('', '');
23         });
24     }
25
26     showPopup() {
27         window.EntitySelectorPopup.show(entity => {
28             this.setValue(entity.id, entity.name);
29         });
30     }
31
32     setValue(value, name) {
33         this.value = value;
34         this.input.value = value;
35         this.controlView(name);
36     }
37
38     controlView(name) {
39         let hasValue = this.value && this.value !== 0;
40         toggleElem(this.resetButton, hasValue);
41         toggleElem(this.buttonSep, hasValue);
42         toggleElem(this.defaultDisplay, !hasValue);
43         toggleElem(this.display, hasValue);
44         if (hasValue) {
45             let id = this.getAssetIdFromVal();
46             this.display.textContent = `#${id}, ${name}`;
47             this.display.href = window.baseUrl(`/link/${id}`);
48         }
49     }
50
51     getAssetIdFromVal() {
52         return Number(this.value);
53     }
54
55 }
56
57 function toggleElem(elem, show) {
58     let display = (elem.tagName === 'BUTTON' || elem.tagName === 'SPAN') ? 'inline-block' : 'block';
59     elem.style.display = show ? display : 'none';
60 }
61
62 export default PagePicker;