1 import * as DOM from "../services/dom";
3 class TemplateManager {
7 this.list = elem.querySelector('[template-manager-list]');
8 this.searching = false;
10 // Template insert action buttons
11 DOM.onChildEvent(this.elem, '[template-action]', 'click', this.handleTemplateActionClick.bind(this));
13 // Template list pagination click
14 DOM.onChildEvent(this.elem, '.pagination a', 'click', this.handlePaginationClick.bind(this));
16 // Template list item content click
17 DOM.onChildEvent(this.elem, '.template-item-content', 'click', this.handleTemplateItemClick.bind(this));
19 // Template list item drag start
20 DOM.onChildEvent(this.elem, '.template-item', 'dragstart', this.handleTemplateItemDragStart.bind(this));
22 this.setupSearchBox();
25 handleTemplateItemClick(event, templateItem) {
26 const templateId = templateItem.closest('[template-id]').getAttribute('template-id');
27 this.insertTemplate(templateId, 'replace');
30 handleTemplateItemDragStart(event, templateItem) {
31 const templateId = templateItem.closest('[template-id]').getAttribute('template-id');
32 event.dataTransfer.setData('bookstack/template', templateId);
33 event.dataTransfer.setData('text/plain', templateId);
36 handleTemplateActionClick(event, actionButton) {
37 event.stopPropagation();
39 const action = actionButton.getAttribute('template-action');
40 const templateId = actionButton.closest('[template-id]').getAttribute('template-id');
41 this.insertTemplate(templateId, action);
44 async insertTemplate(templateId, action = 'replace') {
45 const resp = await window.$http.get(`/templates/${templateId}`);
46 const eventName = 'editor::' + action;
47 window.$events.emit(eventName, resp.data);
50 async handlePaginationClick(event, paginationLink) {
51 event.preventDefault();
52 const paginationUrl = paginationLink.getAttribute('href');
53 const resp = await window.$http.get(paginationUrl);
54 this.list.innerHTML = resp.data;
58 const searchBox = this.elem.querySelector('.search-box');
60 // Search box may not exist if there are no existing templates in the system.
61 if (!searchBox) return;
63 const input = searchBox.querySelector('input');
64 const submitButton = searchBox.querySelector('button');
65 const cancelButton = searchBox.querySelector('button.search-box-cancel');
67 async function performSearch() {
68 const searchTerm = input.value;
69 const resp = await window.$http.get(`/templates`, {
72 cancelButton.style.display = searchTerm ? 'block' : 'none';
73 this.list.innerHTML = resp.data;
75 performSearch = performSearch.bind(this);
77 // Search box enter press
78 searchBox.addEventListener('keypress', event => {
79 if (event.key === 'Enter') {
80 event.preventDefault();
85 // Submit button press
86 submitButton.addEventListener('click', event => {
90 // Cancel button press
91 cancelButton.addEventListener('click', event => {
98 export default TemplateManager;