]> BookStack Code Mirror - bookstack/blob - resources/js/components/entity-selector-popup.ts
TypeScript: Updated compile target, addressed issues
[bookstack] / resources / js / components / entity-selector-popup.ts
1 import {Component} from './component';
2 import {EntitySelector, EntitySelectorEntity, EntitySelectorSearchOptions} from "./entity-selector";
3 import {Popup} from "./popup";
4
5 export type EntitySelectorPopupCallback = (entity: EntitySelectorEntity) => void;
6
7 export class EntitySelectorPopup extends Component {
8
9     protected container!: HTMLElement;
10     protected selectButton!: HTMLElement;
11     protected selectorEl!: HTMLElement;
12
13     protected callback: EntitySelectorPopupCallback|null = null;
14     protected selection: EntitySelectorEntity|null = null;
15
16     setup() {
17         this.container = this.$el;
18         this.selectButton = this.$refs.select;
19         this.selectorEl = this.$refs.selector;
20
21         this.selectButton.addEventListener('click', this.onSelectButtonClick.bind(this));
22         window.$events.listen('entity-select-change', this.onSelectionChange.bind(this));
23         window.$events.listen('entity-select-confirm', this.handleConfirmedSelection.bind(this));
24     }
25
26     /**
27      * Show the selector popup.
28      */
29     show(callback: EntitySelectorPopupCallback, searchOptions: Partial<EntitySelectorSearchOptions> = {}) {
30         this.callback = callback;
31         this.getSelector().configureSearchOptions(searchOptions);
32         this.getPopup().show();
33
34         this.getSelector().focusSearch();
35     }
36
37     hide() {
38         this.getPopup().hide();
39     }
40
41     getPopup(): Popup {
42         return window.$components.firstOnElement(this.container, 'popup') as Popup;
43     }
44
45     getSelector(): EntitySelector {
46         return window.$components.firstOnElement(this.selectorEl, 'entity-selector') as EntitySelector;
47     }
48
49     onSelectButtonClick() {
50         this.handleConfirmedSelection(this.selection);
51     }
52
53     onSelectionChange(entity: EntitySelectorEntity|{}) {
54         this.selection = (entity.hasOwnProperty('id') ? entity : null) as EntitySelectorEntity|null;
55         if (!this.selection) {
56             this.selectButton.setAttribute('disabled', 'true');
57         } else {
58             this.selectButton.removeAttribute('disabled');
59         }
60     }
61
62     handleConfirmedSelection(entity: EntitySelectorEntity|null): void {
63         this.hide();
64         this.getSelector().reset();
65         if (this.callback && entity) this.callback(entity);
66     }
67
68 }