]> BookStack Code Mirror - bookstack/blob - resources/js/components/page-picker.js
Default chapter templates: Added tests, extracted repo logic
[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.selectorEndpoint = this.$opts.selectorEndpoint;
18
19         this.value = this.input.value;
20         this.setupListeners();
21     }
22
23     setupListeners() {
24         this.selectButton.addEventListener('click', this.showPopup.bind(this));
25         this.display.parentElement.addEventListener('click', this.showPopup.bind(this));
26         this.display.addEventListener('click', e => e.stopPropagation());
27
28         this.resetButton.addEventListener('click', () => {
29             this.setValue('', '');
30         });
31     }
32
33     showPopup() {
34         /** @type {EntitySelectorPopup} * */
35         const selectorPopup = window.$components.first('entity-selector-popup');
36         selectorPopup.show(entity => {
37             this.setValue(entity.id, entity.name);
38         }, '', {
39             searchEndpoint: this.selectorEndpoint,
40             entityTypes: 'page',
41             entityPermission: 'view',
42         });
43     }
44
45     setValue(value, name) {
46         this.value = value;
47         this.input.value = value;
48         this.controlView(name);
49     }
50
51     controlView(name) {
52         const hasValue = this.value && this.value !== 0;
53         toggleElem(this.resetButton, hasValue);
54         toggleElem(this.buttonSep, hasValue);
55         toggleElem(this.defaultDisplay, !hasValue);
56         toggleElem(this.display, hasValue);
57         if (hasValue) {
58             const id = this.getAssetIdFromVal();
59             this.display.textContent = `#${id}, ${name}`;
60             this.display.href = window.baseUrl(`/link/${id}`);
61         }
62     }
63
64     getAssetIdFromVal() {
65         return Number(this.value);
66     }
67
68 }