]> BookStack Code Mirror - bookstack/blob - resources/assets/js/directives.js
converted image picker to blade-based component
[bookstack] / resources / assets / js / directives.js
1 "use strict";
2 import DropZone from "dropzone";
3 import markdown from "marked";
4
5 export default function (ngApp, events) {
6
7     /**
8      * Common tab controls using simple jQuery functions.
9      */
10     ngApp.directive('tabContainer', function() {
11         return {
12             restrict: 'A',
13             link: function (scope, element, attrs) {
14                 const $content = element.find('[tab-content]');
15                 const $buttons = element.find('[tab-button]');
16
17                 if (attrs.tabContainer) {
18                     let initial = attrs.tabContainer;
19                     $buttons.filter(`[tab-button="${initial}"]`).addClass('selected');
20                     $content.hide().filter(`[tab-content="${initial}"]`).show();
21                 } else {
22                     $content.hide().first().show();
23                     $buttons.first().addClass('selected');
24                 }
25
26                 $buttons.click(function() {
27                     let clickedTab = $(this);
28                     $buttons.removeClass('selected');
29                     $content.hide();
30                     let name = clickedTab.addClass('selected').attr('tab-button');
31                     $content.filter(`[tab-content="${name}"]`).show();
32                 });
33             }
34         };
35     });
36
37     /**
38      * Sub form component to allow inner-form sections to act like their own forms.
39      */
40     ngApp.directive('subForm', function() {
41         return {
42             restrict: 'A',
43             link: function (scope, element, attrs) {
44                 element.on('keypress', e => {
45                     if (e.keyCode === 13) {
46                         submitEvent(e);
47                     }
48                 });
49
50                 element.find('button[type="submit"]').click(submitEvent);
51
52                 function submitEvent(e) {
53                     e.preventDefault();
54                     if (attrs.subForm) scope.$eval(attrs.subForm);
55                 }
56             }
57         };
58     });
59
60     /**
61      * DropZone
62      * Used for uploading images
63      */
64     ngApp.directive('dropZone', [function () {
65         return {
66             restrict: 'E',
67             template: `
68             <div class="dropzone-container">
69                 <div class="dz-message">{{message}}</div>
70             </div>
71             `,
72             scope: {
73                 uploadUrl: '@',
74                 eventSuccess: '=',
75                 eventError: '=',
76                 uploadedTo: '@',
77             },
78             link: function (scope, element, attrs) {
79                 scope.message = attrs.message;
80                 if (attrs.placeholder) element[0].querySelector('.dz-message').textContent = attrs.placeholder;
81                 let dropZone = new DropZone(element[0].querySelector('.dropzone-container'), {
82                     url: scope.uploadUrl,
83                     init: function () {
84                         let dz = this;
85                         dz.on('sending', function (file, xhr, data) {
86                             let token = window.document.querySelector('meta[name=token]').getAttribute('content');
87                             data.append('_token', token);
88                             let uploadedTo = typeof scope.uploadedTo === 'undefined' ? 0 : scope.uploadedTo;
89                             data.append('uploaded_to', uploadedTo);
90                         });
91                         if (typeof scope.eventSuccess !== 'undefined') dz.on('success', scope.eventSuccess);
92                         dz.on('success', function (file, data) {
93                             $(file.previewElement).fadeOut(400, function () {
94                                 dz.removeFile(file);
95                             });
96                         });
97                         if (typeof scope.eventError !== 'undefined') dz.on('error', scope.eventError);
98                         dz.on('error', function (file, errorMessage, xhr) {
99                             console.log(errorMessage);
100                             console.log(xhr);
101                             function setMessage(message) {
102                                 $(file.previewElement).find('[data-dz-errormessage]').text(message);
103                             }
104
105                             if (xhr.status === 413) setMessage('The server does not allow uploads of this size. Please try a smaller file.');
106                             if (errorMessage.file) setMessage(errorMessage.file[0]);
107
108                         });
109                     }
110                 });
111             }
112         };
113     }]);
114
115     /**
116      * Dropdown
117      * Provides some simple logic to create small dropdown menus
118      */
119     ngApp.directive('dropdown', [function () {
120         return {
121             restrict: 'A',
122             link: function (scope, element, attrs) {
123                 const menu = element.find('ul');
124                 element.find('[dropdown-toggle]').on('click', function () {
125                     menu.show().addClass('anim menuIn');
126                     let inputs = menu.find('input');
127                     let hasInput = inputs.length > 0;
128                     if (hasInput) {
129                         inputs.first().focus();
130                         element.on('keypress', 'input', event => {
131                             if (event.keyCode === 13) {
132                                 event.preventDefault();
133                                 menu.hide();
134                                 menu.removeClass('anim menuIn');
135                                 return false;
136                             }
137                         });
138                     }
139                     element.mouseleave(function () {
140                         menu.hide();
141                         menu.removeClass('anim menuIn');
142                     });
143                 });
144             }
145         };
146     }]);
147
148     /**
149      * TinyMCE
150      * An angular wrapper around the tinyMCE editor.
151      */
152     ngApp.directive('tinymce', ['$timeout', function ($timeout) {
153         return {
154             restrict: 'A',
155             scope: {
156                 tinymce: '=',
157                 mceModel: '=',
158                 mceChange: '='
159             },
160             link: function (scope, element, attrs) {
161
162                 function tinyMceSetup(editor) {
163                     editor.on('ExecCommand change NodeChange ObjectResized', (e) => {
164                         let content = editor.getContent();
165                         $timeout(() => {
166                             scope.mceModel = content;
167                         });
168                         scope.mceChange(content);
169                     });
170
171                     editor.on('keydown', (event) => {
172                         scope.$emit('editor-keydown', event);
173                     });
174
175                     editor.on('init', (e) => {
176                         scope.mceModel = editor.getContent();
177                     });
178
179                     scope.$on('html-update', (event, value) => {
180                         editor.setContent(value);
181                         editor.selection.select(editor.getBody(), true);
182                         editor.selection.collapse(false);
183                         scope.mceModel = editor.getContent();
184                     });
185                 }
186
187                 scope.tinymce.extraSetups.push(tinyMceSetup);
188
189                 // Custom tinyMCE plugins
190                 tinymce.PluginManager.add('customhr', function (editor) {
191                     editor.addCommand('InsertHorizontalRule', function () {
192                         let hrElem = document.createElement('hr');
193                         let cNode = editor.selection.getNode();
194                         let parentNode = cNode.parentNode;
195                         parentNode.insertBefore(hrElem, cNode);
196                     });
197
198                     editor.addButton('hr', {
199                         icon: 'hr',
200                         tooltip: 'Horizontal line',
201                         cmd: 'InsertHorizontalRule'
202                     });
203
204                     editor.addMenuItem('hr', {
205                         icon: 'hr',
206                         text: 'Horizontal line',
207                         cmd: 'InsertHorizontalRule',
208                         context: 'insert'
209                     });
210                 });
211
212                 tinymce.init(scope.tinymce);
213             }
214         }
215     }]);
216
217     /**
218      * Markdown input
219      * Handles the logic for just the editor input field.
220      */
221     ngApp.directive('markdownInput', ['$timeout', function ($timeout) {
222         return {
223             restrict: 'A',
224             scope: {
225                 mdModel: '=',
226                 mdChange: '='
227             },
228             link: function (scope, element, attrs) {
229
230                 // Set initial model content
231                 element = element.find('textarea').first();
232                 let content = element.val();
233                 scope.mdModel = content;
234                 scope.mdChange(markdown(content));
235
236                 element.on('change input', (event) => {
237                     content = element.val();
238                     $timeout(() => {
239                         scope.mdModel = content;
240                         scope.mdChange(markdown(content));
241                     });
242                 });
243
244                 scope.$on('markdown-update', (event, value) => {
245                     element.val(value);
246                     scope.mdModel = value;
247                     scope.mdChange(markdown(value));
248                 });
249
250             }
251         }
252     }]);
253
254     /**
255      * Markdown Editor
256      * Handles all functionality of the markdown editor.
257      */
258     ngApp.directive('markdownEditor', ['$timeout', function ($timeout) {
259         return {
260             restrict: 'A',
261             link: function (scope, element, attrs) {
262
263                 // Elements
264                 const input = element.find('[markdown-input] textarea').first();
265                 const display = element.find('.markdown-display').first();
266                 const insertImage = element.find('button[data-action="insertImage"]');
267                 const insertEntityLink = element.find('button[data-action="insertEntityLink"]')
268
269                 let currentCaretPos = 0;
270
271                 input.blur(event => {
272                     currentCaretPos = input[0].selectionStart;
273                 });
274
275                 // Scroll sync
276                 let inputScrollHeight,
277                     inputHeight,
278                     displayScrollHeight,
279                     displayHeight;
280
281                 function setScrollHeights() {
282                     inputScrollHeight = input[0].scrollHeight;
283                     inputHeight = input.height();
284                     displayScrollHeight = display[0].scrollHeight;
285                     displayHeight = display.height();
286                 }
287
288                 setTimeout(() => {
289                     setScrollHeights();
290                 }, 200);
291                 window.addEventListener('resize', setScrollHeights);
292                 let scrollDebounceTime = 800;
293                 let lastScroll = 0;
294                 input.on('scroll', event => {
295                     let now = Date.now();
296                     if (now - lastScroll > scrollDebounceTime) {
297                         setScrollHeights()
298                     }
299                     let scrollPercent = (input.scrollTop() / (inputScrollHeight - inputHeight));
300                     let displayScrollY = (displayScrollHeight - displayHeight) * scrollPercent;
301                     display.scrollTop(displayScrollY);
302                     lastScroll = now;
303                 });
304
305                 // Editor key-presses
306                 input.keydown(event => {
307                     // Insert image shortcut
308                     if (event.which === 73 && event.ctrlKey && event.shiftKey) {
309                         event.preventDefault();
310                         let caretPos = input[0].selectionStart;
311                         let currentContent = input.val();
312                         const mdImageText = "![](http://)";
313                         input.val(currentContent.substring(0, caretPos) + mdImageText + currentContent.substring(caretPos));
314                         input.focus();
315                         input[0].selectionStart = caretPos + ("![](".length);
316                         input[0].selectionEnd = caretPos + ('![](http://'.length);
317                         return;
318                     }
319
320                     // Insert entity link shortcut
321                     if (event.which === 75 && event.ctrlKey && event.shiftKey) {
322                         showLinkSelector();
323                         return;
324                     }
325
326                     // Pass key presses to controller via event
327                     scope.$emit('editor-keydown', event);
328                 });
329
330                 // Insert image from image manager
331                 insertImage.click(event => {
332                     window.ImageManager.showExternal(image => {
333                         let caretPos = currentCaretPos;
334                         let currentContent = input.val();
335                         let mdImageText = "![" + image.name + "](" + image.thumbs.display + ")";
336                         input.val(currentContent.substring(0, caretPos) + mdImageText + currentContent.substring(caretPos));
337                         input.change();
338                     });
339                 });
340
341                 function showLinkSelector() {
342                     window.showEntityLinkSelector((entity) => {
343                         let selectionStart = currentCaretPos;
344                         let selectionEnd = input[0].selectionEnd;
345                         let textSelected = (selectionEnd !== selectionStart);
346                         let currentContent = input.val();
347
348                         if (textSelected) {
349                             let selectedText = currentContent.substring(selectionStart, selectionEnd);
350                             let linkText = `[${selectedText}](${entity.link})`;
351                             input.val(currentContent.substring(0, selectionStart) + linkText + currentContent.substring(selectionEnd));
352                         } else {
353                             let linkText = ` [${entity.name}](${entity.link}) `;
354                             input.val(currentContent.substring(0, selectionStart) + linkText + currentContent.substring(selectionStart))
355                         }
356                         input.change();
357                     });
358                 }
359                 insertEntityLink.click(showLinkSelector);
360
361                 // Upload and insert image on paste
362                 function editorPaste(e) {
363                     e = e.originalEvent;
364                     if (!e.clipboardData) return
365                     let items = e.clipboardData.items;
366                     if (!items) return;
367                     for (let i = 0; i < items.length; i++) {
368                         uploadImage(items[i].getAsFile());
369                     }
370                 }
371
372                 input.on('paste', editorPaste);
373
374                 // Handle image drop, Uploads images to BookStack.
375                 function handleImageDrop(event) {
376                     event.stopPropagation();
377                     event.preventDefault();
378                     let files = event.originalEvent.dataTransfer.files;
379                     for (let i = 0; i < files.length; i++) {
380                         uploadImage(files[i]);
381                     }
382                 }
383
384                 input.on('drop', handleImageDrop);
385
386                 // Handle image upload and add image into markdown content
387                 function uploadImage(file) {
388                     if (file.type.indexOf('image') !== 0) return;
389                     let formData = new FormData();
390                     let ext = 'png';
391                     let xhr = new XMLHttpRequest();
392
393                     if (file.name) {
394                         let fileNameMatches = file.name.match(/\.(.+)$/);
395                         if (fileNameMatches) {
396                             ext = fileNameMatches[1];
397                         }
398                     }
399
400                     // Insert image into markdown
401                     let id = "image-" + Math.random().toString(16).slice(2);
402                     let selectStart = input[0].selectionStart;
403                     let selectEnd = input[0].selectionEnd;
404                     let content = input[0].value;
405                     let selectText = content.substring(selectStart, selectEnd);
406                     let placeholderImage = window.baseUrl(`/loading.gif#upload${id}`);
407                     let innerContent = ((selectEnd > selectStart) ? `![${selectText}]` : '![]') + `(${placeholderImage})`;
408                     input[0].value = content.substring(0, selectStart) +  innerContent + content.substring(selectEnd);
409
410                     input.focus();
411                     input[0].selectionStart = selectStart;
412                     input[0].selectionEnd = selectStart;
413
414                     let remoteFilename = "image-" + Date.now() + "." + ext;
415                     formData.append('file', file, remoteFilename);
416                     formData.append('_token', document.querySelector('meta[name="token"]').getAttribute('content'));
417
418                     xhr.open('POST', window.baseUrl('/images/gallery/upload'));
419                     xhr.onload = function () {
420                         let selectStart = input[0].selectionStart;
421                         if (xhr.status === 200 || xhr.status === 201) {
422                             let result = JSON.parse(xhr.responseText);
423                             input[0].value = input[0].value.replace(placeholderImage, result.thumbs.display);
424                             input.change();
425                         } else {
426                             console.log('An error occurred uploading the image');
427                             console.log(xhr.responseText);
428                             input[0].value = input[0].value.replace(innerContent, '');
429                             input.change();
430                         }
431                         input.focus();
432                         input[0].selectionStart = selectStart;
433                         input[0].selectionEnd = selectStart;
434                     };
435                     xhr.send(formData);
436                 }
437
438             }
439         }
440     }]);
441
442     /**
443      * Page Editor Toolbox
444      * Controls all functionality for the sliding toolbox
445      * on the page edit view.
446      */
447     ngApp.directive('toolbox', [function () {
448         return {
449             restrict: 'A',
450             link: function (scope, elem, attrs) {
451
452                 // Get common elements
453                 const $buttons = elem.find('[toolbox-tab-button]');
454                 const $content = elem.find('[toolbox-tab-content]');
455                 const $toggle = elem.find('[toolbox-toggle]');
456
457                 // Handle toolbox toggle click
458                 $toggle.click((e) => {
459                     elem.toggleClass('open');
460                 });
461
462                 // Set an active tab/content by name
463                 function setActive(tabName, openToolbox) {
464                     $buttons.removeClass('active');
465                     $content.hide();
466                     $buttons.filter(`[toolbox-tab-button="${tabName}"]`).addClass('active');
467                     $content.filter(`[toolbox-tab-content="${tabName}"]`).show();
468                     if (openToolbox) elem.addClass('open');
469                 }
470
471                 // Set the first tab content active on load
472                 setActive($content.first().attr('toolbox-tab-content'), false);
473
474                 // Handle tab button click
475                 $buttons.click(function (e) {
476                     let name = $(this).attr('toolbox-tab-button');
477                     setActive(name, true);
478                 });
479             }
480         }
481     }]);
482
483     /**
484      * Tag Autosuggestions
485      * Listens to child inputs and provides autosuggestions depending on field type
486      * and input. Suggestions provided by server.
487      */
488     ngApp.directive('tagAutosuggestions', ['$http', function ($http) {
489         return {
490             restrict: 'A',
491             link: function (scope, elem, attrs) {
492
493                 // Local storage for quick caching.
494                 const localCache = {};
495
496                 // Create suggestion element
497                 const suggestionBox = document.createElement('ul');
498                 suggestionBox.className = 'suggestion-box';
499                 suggestionBox.style.position = 'absolute';
500                 suggestionBox.style.display = 'none';
501                 const $suggestionBox = $(suggestionBox);
502
503                 // General state tracking
504                 let isShowing = false;
505                 let currentInput = false;
506                 let active = 0;
507
508                 // Listen to input events on autosuggest fields
509                 elem.on('input focus', '[autosuggest]', function (event) {
510                     let $input = $(this);
511                     let val = $input.val();
512                     let url = $input.attr('autosuggest');
513                     let type = $input.attr('autosuggest-type');
514
515                     // Add name param to request if for a value
516                     if (type.toLowerCase() === 'value') {
517                         let $nameInput = $input.closest('tr').find('[autosuggest-type="name"]').first();
518                         let nameVal = $nameInput.val();
519                         if (nameVal !== '') {
520                             url += '?name=' + encodeURIComponent(nameVal);
521                         }
522                     }
523
524                     let suggestionPromise = getSuggestions(val.slice(0, 3), url);
525                     suggestionPromise.then(suggestions => {
526                         if (val.length === 0) {
527                             displaySuggestions($input, suggestions.slice(0, 6));
528                         } else  {
529                             suggestions = suggestions.filter(item => {
530                                 return item.toLowerCase().indexOf(val.toLowerCase()) !== -1;
531                             }).slice(0, 4);
532                             displaySuggestions($input, suggestions);
533                         }
534                     });
535                 });
536
537                 // Hide autosuggestions when input loses focus.
538                 // Slight delay to allow clicks.
539                 let lastFocusTime = 0;
540                 elem.on('blur', '[autosuggest]', function (event) {
541                     let startTime = Date.now();
542                     setTimeout(() => {
543                         if (lastFocusTime < startTime) {
544                             $suggestionBox.hide();
545                             isShowing = false;
546                         }
547                     }, 200)
548                 });
549                 elem.on('focus', '[autosuggest]', function (event) {
550                     lastFocusTime = Date.now();
551                 });
552
553                 elem.on('keydown', '[autosuggest]', function (event) {
554                     if (!isShowing) return;
555
556                     let suggestionElems = suggestionBox.childNodes;
557                     let suggestCount = suggestionElems.length;
558
559                     // Down arrow
560                     if (event.keyCode === 40) {
561                         let newActive = (active === suggestCount - 1) ? 0 : active + 1;
562                         changeActiveTo(newActive, suggestionElems);
563                     }
564                     // Up arrow
565                     else if (event.keyCode === 38) {
566                         let newActive = (active === 0) ? suggestCount - 1 : active - 1;
567                         changeActiveTo(newActive, suggestionElems);
568                     }
569                     // Enter or tab key
570                     else if ((event.keyCode === 13 || event.keyCode === 9) && !event.shiftKey) {
571                         let text = suggestionElems[active].textContent;
572                         currentInput[0].value = text;
573                         currentInput.focus();
574                         $suggestionBox.hide();
575                         isShowing = false;
576                         if (event.keyCode === 13) {
577                             event.preventDefault();
578                             return false;
579                         }
580                     }
581                 });
582
583                 // Change the active suggestion to the given index
584                 function changeActiveTo(index, suggestionElems) {
585                     suggestionElems[active].className = '';
586                     active = index;
587                     suggestionElems[active].className = 'active';
588                 }
589
590                 // Display suggestions on a field
591                 let prevSuggestions = [];
592
593                 function displaySuggestions($input, suggestions) {
594
595                     // Hide if no suggestions
596                     if (suggestions.length === 0) {
597                         $suggestionBox.hide();
598                         isShowing = false;
599                         prevSuggestions = suggestions;
600                         return;
601                     }
602
603                     // Otherwise show and attach to input
604                     if (!isShowing) {
605                         $suggestionBox.show();
606                         isShowing = true;
607                     }
608                     if ($input !== currentInput) {
609                         $suggestionBox.detach();
610                         $input.after($suggestionBox);
611                         currentInput = $input;
612                     }
613
614                     // Return if no change
615                     if (prevSuggestions.join() === suggestions.join()) {
616                         prevSuggestions = suggestions;
617                         return;
618                     }
619
620                     // Build suggestions
621                     $suggestionBox[0].innerHTML = '';
622                     for (let i = 0; i < suggestions.length; i++) {
623                         let suggestion = document.createElement('li');
624                         suggestion.textContent = suggestions[i];
625                         suggestion.onclick = suggestionClick;
626                         if (i === 0) {
627                             suggestion.className = 'active';
628                             active = 0;
629                         }
630                         $suggestionBox[0].appendChild(suggestion);
631                     }
632
633                     prevSuggestions = suggestions;
634                 }
635
636                 // Suggestion click event
637                 function suggestionClick(event) {
638                     currentInput[0].value = this.textContent;
639                     currentInput.focus();
640                     $suggestionBox.hide();
641                     isShowing = false;
642                 }
643
644                 // Get suggestions & cache
645                 function getSuggestions(input, url) {
646                     let hasQuery = url.indexOf('?') !== -1;
647                     let searchUrl = url + (hasQuery ? '&' : '?') + 'search=' + encodeURIComponent(input);
648
649                     // Get from local cache if exists
650                     if (typeof localCache[searchUrl] !== 'undefined') {
651                         return new Promise((resolve, reject) => {
652                             resolve(localCache[searchUrl]);
653                         });
654                     }
655
656                     return $http.get(searchUrl).then(response => {
657                         localCache[searchUrl] = response.data;
658                         return response.data;
659                     });
660                 }
661
662             }
663         }
664     }]);
665
666     ngApp.directive('entityLinkSelector', [function($http) {
667         return {
668             restict: 'A',
669             link: function(scope, element, attrs) {
670
671                 const selectButton = element.find('.entity-link-selector-confirm');
672                 let callback = false;
673                 let entitySelection = null;
674
675                 // Handle entity selection change, Stores the selected entity locally
676                 function entitySelectionChange(entity) {
677                     entitySelection = entity;
678                     if (entity === null) {
679                         selectButton.attr('disabled', 'true');
680                     } else {
681                         selectButton.removeAttr('disabled');
682                     }
683                 }
684                 events.listen('entity-select-change', entitySelectionChange);
685
686                 // Handle selection confirm button click
687                 selectButton.click(event => {
688                     hide();
689                     if (entitySelection !== null) callback(entitySelection);
690                 });
691
692                 // Show selector interface
693                 function show() {
694                     element.fadeIn(240);
695                 }
696
697                 // Hide selector interface
698                 function hide() {
699                     element.fadeOut(240);
700                 }
701
702                 // Listen to confirmation of entity selections (doubleclick)
703                 events.listen('entity-select-confirm', entity => {
704                     hide();
705                     callback(entity);
706                 });
707
708                 // Show entity selector, Accessible globally, and store the callback
709                 window.showEntityLinkSelector = function(passedCallback) {
710                     show();
711                     callback = passedCallback;
712                 };
713
714             }
715         };
716     }]);
717
718
719     ngApp.directive('entitySelector', ['$http', '$sce', function ($http, $sce) {
720         return {
721             restrict: 'A',
722             scope: true,
723             link: function (scope, element, attrs) {
724                 scope.loading = true;
725                 scope.entityResults = false;
726                 scope.search = '';
727
728                 // Add input for forms
729                 const input = element.find('[entity-selector-input]').first();
730
731                 // Detect double click events
732                 let lastClick = 0;
733                 function isDoubleClick() {
734                     let now = Date.now();
735                     let answer = now - lastClick < 300;
736                     lastClick = now;
737                     return answer;
738                 }
739
740                 // Listen to entity item clicks
741                 element.on('click', '.entity-list a', function(event) {
742                     event.preventDefault();
743                     event.stopPropagation();
744                     let item = $(this).closest('[data-entity-type]');
745                     itemSelect(item, isDoubleClick());
746                 });
747                 element.on('click', '[data-entity-type]', function(event) {
748                     itemSelect($(this), isDoubleClick());
749                 });
750
751                 // Select entity action
752                 function itemSelect(item, doubleClick) {
753                     let entityType = item.attr('data-entity-type');
754                     let entityId = item.attr('data-entity-id');
755                     let isSelected = !item.hasClass('selected') || doubleClick;
756                     element.find('.selected').removeClass('selected').removeClass('primary-background');
757                     if (isSelected) item.addClass('selected').addClass('primary-background');
758                     let newVal = isSelected ? `${entityType}:${entityId}` : '';
759                     input.val(newVal);
760
761                     if (!isSelected) {
762                         events.emit('entity-select-change', null);
763                     }
764
765                     if (!doubleClick && !isSelected) return;
766
767                     let link = item.find('.entity-list-item-link').attr('href');
768                     let name = item.find('.entity-list-item-name').text();
769
770                     if (doubleClick) {
771                         events.emit('entity-select-confirm', {
772                             id: Number(entityId),
773                             name: name,
774                             link: link
775                         });
776                     }
777
778                     if (isSelected) {
779                         events.emit('entity-select-change', {
780                             id: Number(entityId),
781                             name: name,
782                             link: link
783                         });
784                     }
785                 }
786
787                 // Get search url with correct types
788                 function getSearchUrl() {
789                     let types = (attrs.entityTypes) ? encodeURIComponent(attrs.entityTypes) : encodeURIComponent('page,book,chapter');
790                     return window.baseUrl(`/ajax/search/entities?types=${types}`);
791                 }
792
793                 // Get initial contents
794                 $http.get(getSearchUrl()).then(resp => {
795                     scope.entityResults = $sce.trustAsHtml(resp.data);
796                     scope.loading = false;
797                 });
798
799                 // Search when typing
800                 scope.searchEntities = function() {
801                     scope.loading = true;
802                     input.val('');
803                     let url = getSearchUrl() + '&term=' + encodeURIComponent(scope.search);
804                     $http.get(url).then(resp => {
805                         scope.entityResults = $sce.trustAsHtml(resp.data);
806                         scope.loading = false;
807                     });
808                 };
809             }
810         };
811     }]);
812 };