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