]> BookStack Code Mirror - bookstack/blob - resources/assets/js/directives.js
Added basic markdown scroll syncing
[bookstack] / resources / assets / js / directives.js
1 "use strict";
2 var DropZone = require('dropzone');
3 var markdown = require('marked');
4
5 var toggleSwitchTemplate = require('./components/toggle-switch.html');
6 var imagePickerTemplate = require('./components/image-picker.html');
7 var dropZoneTemplate = require('./components/drop-zone.html');
8
9 module.exports = function (ngApp, events) {
10
11     /**
12      * Toggle Switches
13      * Has basic on/off functionality.
14      * Use string values of 'true' & 'false' to dictate the current state.
15      */
16     ngApp.directive('toggleSwitch', function () {
17         return {
18             restrict: 'A',
19             template: toggleSwitchTemplate,
20             scope: true,
21             link: function (scope, element, attrs) {
22                 scope.name = attrs.name;
23                 scope.value = attrs.value;
24                 scope.isActive = scope.value == true && scope.value != 'false';
25                 scope.value = (scope.value == true && scope.value != 'false') ? 'true' : 'false';
26
27                 scope.switch = function () {
28                     scope.isActive = !scope.isActive;
29                     scope.value = scope.isActive ? 'true' : 'false';
30                 }
31
32             }
33         };
34     });
35
36
37     /**
38      * Image Picker
39      * Is a simple front-end interface that connects to an ImageManager if present.
40      */
41     ngApp.directive('imagePicker', ['$http', 'imageManagerService', function ($http, imageManagerService) {
42         return {
43             restrict: 'E',
44             template: imagePickerTemplate,
45             scope: {
46                 name: '@',
47                 resizeHeight: '@',
48                 resizeWidth: '@',
49                 resizeCrop: '@',
50                 showRemove: '=',
51                 currentImage: '@',
52                 currentId: '@',
53                 defaultImage: '@',
54                 imageClass: '@'
55             },
56             link: function (scope, element, attrs) {
57                 var usingIds = typeof scope.currentId !== 'undefined' || scope.currentId === 'false';
58                 scope.image = scope.currentImage;
59                 scope.value = scope.currentImage || '';
60                 if (usingIds) scope.value = scope.currentId;
61
62                 function setImage(imageModel, imageUrl) {
63                     scope.image = imageUrl;
64                     scope.value = usingIds ? imageModel.id : imageUrl;
65                 }
66
67                 scope.reset = function () {
68                     setImage({id: 0}, scope.defaultImage);
69                 };
70
71                 scope.remove = function () {
72                     scope.image = 'none';
73                     scope.value = 'none';
74                 };
75
76                 scope.showImageManager = function () {
77                     imageManagerService.show((image) => {
78                         scope.updateImageFromModel(image);
79                     });
80                 };
81
82                 scope.updateImageFromModel = function (model) {
83                     var isResized = scope.resizeWidth && scope.resizeHeight;
84
85                     if (!isResized) {
86                         scope.$apply(() => {
87                             setImage(model, model.url);
88                         });
89                         return;
90                     }
91
92                     var cropped = scope.resizeCrop ? 'true' : 'false';
93                     var requestString = '/images/thumb/' + model.id + '/' + scope.resizeWidth + '/' + scope.resizeHeight + '/' + cropped;
94                     $http.get(requestString).then((response) => {
95                         setImage(model, response.data.url);
96                     });
97                 };
98
99             }
100         };
101     }]);
102
103     /**
104      * DropZone
105      * Used for uploading images
106      */
107     ngApp.directive('dropZone', [function () {
108         return {
109             restrict: 'E',
110             template: dropZoneTemplate,
111             scope: {
112                 uploadUrl: '@',
113                 eventSuccess: '=',
114                 eventError: '=',
115                 uploadedTo: '@'
116             },
117             link: function (scope, element, attrs) {
118                 var dropZone = new DropZone(element[0].querySelector('.dropzone-container'), {
119                     url: scope.uploadUrl,
120                     init: function () {
121                         var dz = this;
122                         dz.on('sending', function (file, xhr, data) {
123                             var token = window.document.querySelector('meta[name=token]').getAttribute('content');
124                             data.append('_token', token);
125                             var uploadedTo = typeof scope.uploadedTo === 'undefined' ? 0 : scope.uploadedTo;
126                             data.append('uploaded_to', uploadedTo);
127                         });
128                         if (typeof scope.eventSuccess !== 'undefined') dz.on('success', scope.eventSuccess);
129                         dz.on('success', function (file, data) {
130                             $(file.previewElement).fadeOut(400, function () {
131                                 dz.removeFile(file);
132                             });
133                         });
134                         if (typeof scope.eventError !== 'undefined') dz.on('error', scope.eventError);
135                         dz.on('error', function (file, errorMessage, xhr) {
136                             console.log(errorMessage);
137                             console.log(xhr);
138                             function setMessage(message) {
139                                 $(file.previewElement).find('[data-dz-errormessage]').text(message);
140                             }
141
142                             if (xhr.status === 413) setMessage('The server does not allow uploads of this size. Please try a smaller file.');
143                             if (errorMessage.file) setMessage(errorMessage.file[0]);
144
145                         });
146                     }
147                 });
148             }
149         };
150     }]);
151
152
153     ngApp.directive('dropdown', [function () {
154         return {
155             restrict: 'A',
156             link: function (scope, element, attrs) {
157                 var menu = element.find('ul');
158                 element.find('[dropdown-toggle]').on('click', function () {
159                     menu.show().addClass('anim menuIn');
160                     element.mouseleave(function () {
161                         menu.hide();
162                         menu.removeClass('anim menuIn');
163                     });
164                 });
165             }
166         };
167     }]);
168
169     ngApp.directive('tinymce', ['$timeout', function($timeout) {
170         return {
171             restrict: 'A',
172             scope: {
173                 tinymce: '=',
174                 mceModel: '=',
175                 mceChange: '='
176             },
177             link: function (scope, element, attrs) {
178
179                 function tinyMceSetup(editor) {
180                     editor.on('ExecCommand change NodeChange ObjectResized', (e) => {
181                         var content = editor.getContent();
182                         $timeout(() => {
183                             scope.mceModel = content;
184                         });
185                         scope.mceChange(content);
186                     });
187
188                     editor.on('init', (e) => {
189                         scope.mceModel = editor.getContent();
190                     });
191
192                     scope.$on('html-update', (event, value) => {
193                         editor.setContent(value);
194                         editor.selection.select(editor.getBody(), true);
195                         editor.selection.collapse(false);
196                         scope.mceModel = editor.getContent();
197                     });
198                 }
199
200                 scope.tinymce.extraSetups.push(tinyMceSetup);
201
202                 // Custom tinyMCE plugins
203                 tinymce.PluginManager.add('customhr', function(editor) {
204                     editor.addCommand('InsertHorizontalRule', function() {
205                         var hrElem = document.createElement('hr');
206                         var cNode = editor.selection.getNode();
207                         var parentNode = cNode.parentNode;
208                         parentNode.insertBefore(hrElem, cNode);
209                     });
210
211                     editor.addButton('hr', {
212                         icon: 'hr',
213                         tooltip: 'Horizontal line',
214                         cmd: 'InsertHorizontalRule'
215                     });
216
217                     editor.addMenuItem('hr', {
218                         icon: 'hr',
219                         text: 'Horizontal line',
220                         cmd: 'InsertHorizontalRule',
221                         context: 'insert'
222                     });
223                 });
224
225                 tinymce.init(scope.tinymce);
226             }
227         }
228     }]);
229
230     ngApp.directive('markdownInput', ['$timeout', function($timeout) {
231         return {
232             restrict: 'A',
233             scope: {
234                 mdModel: '=',
235                 mdChange: '='
236             },
237             link: function (scope, element, attrs) {
238
239                 // Set initial model content
240                 var content = element.val();
241                 scope.mdModel = content;
242                 scope.mdChange(markdown(content));
243
244                 element.on('change input', (e) => {
245                     content = element.val();
246                     $timeout(() => {
247                         scope.mdModel = content;
248                         scope.mdChange(markdown(content));
249                     });
250                 });
251
252                 scope.$on('markdown-update', (event, value) => {
253                     element.val(value);
254                     scope.mdModel= value;
255                     scope.mdChange(markdown(value));
256                 });
257
258             }
259         }
260     }]);
261
262     ngApp.directive('markdownEditor', ['$timeout', function($timeout) {
263         return {
264             restrict: 'A',
265             link: function (scope, element, attrs) {
266
267                 // Elements
268                 const input = element.find('textarea[markdown-input]');
269                 const display = element.find('.markdown-display').first();
270                 const insertImage = element.find('button[data-action="insertImage"]');
271
272                 let currentCaretPos = 0;
273
274                 input.blur(event => {
275                     currentCaretPos = input[0].selectionStart;
276                 });
277
278                 // Scroll sync
279                 let inputScrollHeight,
280                     inputHeight,
281                     displayScrollHeight,
282                     displayHeight;
283
284                 function setScrollHeights() {
285                     inputScrollHeight = input[0].scrollHeight;
286                     inputHeight = input.height();
287                     displayScrollHeight = display[0].scrollHeight;
288                     displayHeight = display.height();
289                 }
290
291                 setTimeout(() => {
292                     setScrollHeights();
293                 }, 200);
294                 window.addEventListener('resize', setScrollHeights);
295                 let scrollDebounceTime = 800;
296                 let lastScroll = 0;
297                 input.on('scroll', event => {
298                     let now = Date.now();
299                     if (now - lastScroll > scrollDebounceTime) {
300                         setScrollHeights()
301                     }
302                     let scrollPercent = (input.scrollTop() / (inputScrollHeight-inputHeight));
303                     let displayScrollY = (displayScrollHeight - displayHeight) * scrollPercent;
304                     display.scrollTop(displayScrollY);
305                     lastScroll = now;
306                 });
307
308                 // Insert image shortcut
309                 input.keydown(event => {
310                     if (event.which === 73 && event.ctrlKey && event.shiftKey) {
311                         event.preventDefault();
312                         var caretPos = input[0].selectionStart;
313                         var currentContent = input.val();
314                         var mdImageText = "![](http://)";
315                         input.val(currentContent.substring(0, caretPos) + mdImageText + currentContent.substring(caretPos));
316                         input.focus();
317                         input[0].selectionStart = caretPos + ("![](".length);
318                         input[0].selectionEnd = caretPos + ('![](http://'.length);
319                     }
320                 });
321
322                 // Insert image from image manager
323                 insertImage.click(event => {
324                     window.ImageManager.showExternal(image => {
325                         var caretPos = currentCaretPos;
326                         var currentContent = input.val();
327                         var mdImageText = "![" + image.name + "](" + image.url + ")";
328                         input.val(currentContent.substring(0, caretPos) + mdImageText + currentContent.substring(caretPos));
329                         input.change();
330                     });
331                 });
332
333             }
334         }
335     }]);
336     
337     ngApp.directive('toolbox', [function() {
338         return {
339             restrict: 'A',
340             link: function(scope, elem, attrs) {
341
342                 // Get common elements
343                 const $buttons = elem.find('[tab-button]');
344                 const $content = elem.find('[tab-content]');
345                 const $toggle = elem.find('[toolbox-toggle]');
346
347                 // Handle toolbox toggle click
348                 $toggle.click((e) => {
349                     elem.toggleClass('open');
350                 });
351                 
352                 // Set an active tab/content by name
353                 function setActive(tabName, openToolbox) {
354                     $buttons.removeClass('active');
355                     $content.hide();
356                     $buttons.filter(`[tab-button="${tabName}"]`).addClass('active');
357                     $content.filter(`[tab-content="${tabName}"]`).show();
358                     if (openToolbox) elem.addClass('open');
359                 }
360
361                 // Set the first tab content active on load
362                 setActive($content.first().attr('tab-content'), false);
363
364                 // Handle tab button click
365                 $buttons.click(function(e) {
366                     let name = $(this).attr('tab-button');
367                     setActive(name, true);
368                 });
369             }
370         }
371     }]);
372
373     ngApp.directive('autosuggestions', ['$http', function($http) {
374         return {
375             restrict: 'A',
376             link: function(scope, elem, attrs) {
377                 
378                 // Local storage for quick caching.
379                 const localCache = {};
380
381                 // Create suggestion element
382                 const suggestionBox = document.createElement('ul');
383                 suggestionBox.className = 'suggestion-box';
384                 suggestionBox.style.position = 'absolute';
385                 suggestionBox.style.display = 'none';
386                 const $suggestionBox = $(suggestionBox);
387
388                 // General state tracking
389                 let isShowing = false;
390                 let currentInput = false;
391                 let active = 0;
392
393                 // Listen to input events on autosuggest fields
394                 elem.on('input', '[autosuggest]', function(event) {
395                     let $input = $(this);
396                     let val = $input.val();
397                     let url = $input.attr('autosuggest');
398                     // No suggestions until at least 3 chars
399                     if (val.length < 3) {
400                         if (isShowing) {
401                             $suggestionBox.hide();
402                             isShowing = false;
403                         }
404                         return;
405                     };
406
407                     let suggestionPromise = getSuggestions(val.slice(0, 3), url);
408                     suggestionPromise.then((suggestions) => {
409                        if (val.length > 2) {
410                            suggestions = suggestions.filter((item) => {
411                                return item.toLowerCase().indexOf(val.toLowerCase()) !== -1;
412                            }).slice(0, 4);
413                            displaySuggestions($input, suggestions);
414                        }
415                     });
416                 });
417
418                 // Hide autosuggestions when input loses focus.
419                 // Slight delay to allow clicks.
420                 elem.on('blur', '[autosuggest]', function(event) {
421                     setTimeout(() => {
422                         $suggestionBox.hide();
423                         isShowing = false;
424                     }, 200)
425                 });
426
427                 elem.on('keydown', '[autosuggest]', function (event) {
428                     if (!isShowing) return;
429
430                     let suggestionElems = suggestionBox.childNodes;
431                     let suggestCount = suggestionElems.length;
432
433                     // Down arrow
434                     if (event.keyCode === 40) {
435                         let newActive = (active === suggestCount-1) ? 0 : active + 1;
436                         changeActiveTo(newActive, suggestionElems);
437                     }
438                     // Up arrow
439                     else if (event.keyCode === 38) {
440                         let newActive = (active === 0) ? suggestCount-1 : active - 1;
441                         changeActiveTo(newActive, suggestionElems);
442                     }
443                     // Enter key
444                     else if (event.keyCode === 13) {
445                         let text = suggestionElems[active].textContent;
446                         currentInput[0].value = text;
447                         currentInput.focus();
448                         $suggestionBox.hide();
449                         isShowing = false;
450                         event.preventDefault();
451                         return false;
452                     }
453                 });
454
455                 // Change the active suggestion to the given index
456                 function changeActiveTo(index, suggestionElems) {
457                     suggestionElems[active].className = '';
458                     active = index;
459                     suggestionElems[active].className = 'active';
460                 }
461
462                 // Display suggestions on a field
463                 let prevSuggestions = [];
464                 function displaySuggestions($input, suggestions) {
465
466                     // Hide if no suggestions
467                     if (suggestions.length === 0) {
468                         $suggestionBox.hide();
469                         isShowing = false;
470                         prevSuggestions = suggestions;
471                         return;
472                     }
473
474                     // Otherwise show and attach to input
475                     if (!isShowing) {
476                         $suggestionBox.show();
477                         isShowing = true;
478                     }
479                     if ($input !== currentInput) {
480                         $suggestionBox.detach();
481                         $input.after($suggestionBox);
482                         currentInput = $input;
483                     }
484
485                     // Return if no change
486                     if (prevSuggestions.join() === suggestions.join()) {
487                         prevSuggestions = suggestions;
488                         return;
489                     }
490
491                     // Build suggestions
492                     $suggestionBox[0].innerHTML = '';
493                     for (let i = 0; i < suggestions.length; i++) {
494                         var suggestion = document.createElement('li');
495                         suggestion.textContent = suggestions[i];
496                         suggestion.onclick = suggestionClick;
497                         if (i === 0) {
498                             suggestion.className = 'active'
499                             active = 0;
500                         };
501                         $suggestionBox[0].appendChild(suggestion);
502                     }
503
504                     prevSuggestions = suggestions;
505                 }
506
507                 // Suggestion click event
508                 function suggestionClick(event) {
509                     let text = this.textContent;
510                     currentInput[0].value = text;
511                     currentInput.focus();
512                     $suggestionBox.hide();
513                     isShowing = false;
514                 };
515
516                 // Get suggestions & cache
517                 function getSuggestions(input, url) {
518                     let searchUrl = url + '?search=' + encodeURIComponent(input);
519
520                     // Get from local cache if exists
521                     if (localCache[searchUrl]) {
522                         return new Promise((resolve, reject) => {
523                             resolve(localCache[input]);
524                         });
525                     }
526
527                     return $http.get(searchUrl).then((response) => {
528                         localCache[input] = response.data;
529                         return response.data;
530                     });
531                 }
532
533             }
534         }
535     }]);
536 };
537
538
539
540
541
542
543
544
545
546
547
548
549
550