]> BookStack Code Mirror - bookstack/blob - resources/js/components/page-picker.js
Merge pull request #4728 from BookStackApp/friendlier_buttons
[bookstack] / resources / js / components / page-picker.js
1 import {Component} from './component';
2
3 function toggleElem(elem, show) {
4     elem.toggleAttribute('hidden', !show);
5 }
6
7 export class PagePicker extends Component {
8
9     setup() {
10         this.input = this.$refs.input;
11         this.resetButton = this.$refs.resetButton;
12         this.selectButton = this.$refs.selectButton;
13         this.display = this.$refs.display;
14         this.defaultDisplay = this.$refs.defaultDisplay;
15         this.buttonSep = this.$refs.buttonSeperator;
16
17         this.value = this.input.value;
18         this.setupListeners();
19     }
20
21     setupListeners() {
22         this.selectButton.addEventListener('click', this.showPopup.bind(this));
23         this.display.parentElement.addEventListener('click', this.showPopup.bind(this));
24         this.display.addEventListener('click', e => e.stopPropagation());
25
26         this.resetButton.addEventListener('click', () => {
27             this.setValue('', '');
28         });
29     }
30
31     showPopup() {
32         /** @type {EntitySelectorPopup} * */
33         const selectorPopup = window.$components.first('entity-selector-popup');
34         selectorPopup.show(entity => {
35             this.setValue(entity.id, entity.name);
36         });
37     }
38
39     setValue(value, name) {
40         this.value = value;
41         this.input.value = value;
42         this.controlView(name);
43     }
44
45     controlView(name) {
46         const hasValue = this.value && this.value !== 0;
47         toggleElem(this.resetButton, hasValue);
48         toggleElem(this.buttonSep, hasValue);
49         toggleElem(this.defaultDisplay, !hasValue);
50         toggleElem(this.display, hasValue);
51         if (hasValue) {
52             const id = this.getAssetIdFromVal();
53             this.display.textContent = `#${id}, ${name}`;
54             this.display.href = window.baseUrl(`/link/${id}`);
55         }
56     }
57
58     getAssetIdFromVal() {
59         return Number(this.value);
60     }
61
62 }