]> BookStack Code Mirror - bookstack/blob - resources/assets/js/directives.js
Removed code from the directives.
[bookstack] / resources / assets / js / directives.js
1 "use strict";
2 const MarkdownIt = require("markdown-it");
3 const mdTasksLists = require('markdown-it-task-lists');
4 const code = require('./code');
5
6 module.exports = function (ngApp, events) {
7
8     /**
9      * TinyMCE
10      * An angular wrapper around the tinyMCE editor.
11      */
12     ngApp.directive('tinymce', ['$timeout', function ($timeout) {
13         return {
14             restrict: 'A',
15             scope: {
16                 tinymce: '=',
17                 mceModel: '=',
18                 mceChange: '='
19             },
20             link: function (scope, element, attrs) {
21
22                 function tinyMceSetup(editor) {
23                     editor.on('ExecCommand change NodeChange ObjectResized', (e) => {
24                         let content = editor.getContent();
25                         $timeout(() => {
26                             scope.mceModel = content;
27                         });
28                         scope.mceChange(content);
29                     });
30
31                     editor.on('keydown', (event) => {
32                         scope.$emit('editor-keydown', event);
33                     });
34
35                     editor.on('init', (e) => {
36                         scope.mceModel = editor.getContent();
37                     });
38
39                     scope.$on('html-update', (event, value) => {
40                         editor.setContent(value);
41                         editor.selection.select(editor.getBody(), true);
42                         editor.selection.collapse(false);
43                         scope.mceModel = editor.getContent();
44                     });
45                 }
46
47                 scope.tinymce.extraSetups.push(tinyMceSetup);
48                 tinymce.init(scope.tinymce);
49             }
50         }
51     }]);
52
53     const md = new MarkdownIt({html: true});
54     md.use(mdTasksLists, {label: true});
55
56     /**
57      * Markdown input
58      * Handles the logic for just the editor input field.
59      */
60     ngApp.directive('markdownInput', ['$timeout', function ($timeout) {
61         return {
62             restrict: 'A',
63             scope: {
64                 mdModel: '=',
65                 mdChange: '='
66             },
67             link: function (scope, element, attrs) {
68
69                 // Codemirror Setup
70                 element = element.find('textarea').first();
71                 let cm = code.markdownEditor(element[0]);
72
73                 // Custom key commands
74                 let metaKey = code.getMetaKey();
75                 const extraKeys = {};
76                 // Insert Image shortcut
77                 extraKeys[`${metaKey}-Alt-I`] = function(cm) {
78                     let selectedText = cm.getSelection();
79                     let newText = `![${selectedText}](http://)`;
80                     let cursorPos = cm.getCursor('from');
81                     cm.replaceSelection(newText);
82                     cm.setCursor(cursorPos.line, cursorPos.ch + newText.length -1);
83                 };
84                 // Save draft
85                 extraKeys[`${metaKey}-S`] = function(cm) {scope.$emit('save-draft');};
86                 // Show link selector
87                 extraKeys[`Shift-${metaKey}-K`] = function(cm) {showLinkSelector()};
88                 // Insert Link
89                 extraKeys[`${metaKey}-K`] = function(cm) {insertLink()};
90                 // FormatShortcuts
91                 extraKeys[`${metaKey}-1`] = function(cm) {replaceLineStart('##');};
92                 extraKeys[`${metaKey}-2`] = function(cm) {replaceLineStart('###');};
93                 extraKeys[`${metaKey}-3`] = function(cm) {replaceLineStart('####');};
94                 extraKeys[`${metaKey}-4`] = function(cm) {replaceLineStart('#####');};
95                 extraKeys[`${metaKey}-5`] = function(cm) {replaceLineStart('');};
96                 extraKeys[`${metaKey}-d`] = function(cm) {replaceLineStart('');};
97                 extraKeys[`${metaKey}-6`] = function(cm) {replaceLineStart('>');};
98                 extraKeys[`${metaKey}-q`] = function(cm) {replaceLineStart('>');};
99                 extraKeys[`${metaKey}-7`] = function(cm) {wrapSelection('\n```\n', '\n```');};
100                 extraKeys[`${metaKey}-8`] = function(cm) {wrapSelection('`', '`');};
101                 extraKeys[`Shift-${metaKey}-E`] = function(cm) {wrapSelection('`', '`');};
102                 extraKeys[`${metaKey}-9`] = function(cm) {wrapSelection('<p class="callout info">', '</div>');};
103                 cm.setOption('extraKeys', extraKeys);
104
105                 // Update data on content change
106                 cm.on('change', (instance, changeObj) => {
107                     update(instance);
108                 });
109
110                 // Handle scroll to sync display view
111                 cm.on('scroll', instance => {
112                     // Thanks to http://liuhao.im/english/2015/11/10/the-sync-scroll-of-markdown-editor-in-javascript.html
113                     let scroll = instance.getScrollInfo();
114                     let atEnd = scroll.top + scroll.clientHeight === scroll.height;
115                     if (atEnd) {
116                         scope.$emit('markdown-scroll', -1);
117                         return;
118                     }
119                     let lineNum = instance.lineAtHeight(scroll.top, 'local');
120                     let range = instance.getRange({line: 0, ch: null}, {line: lineNum, ch: null});
121                     let parser = new DOMParser();
122                     let doc = parser.parseFromString(md.render(range), 'text/html');
123                     let totalLines = doc.documentElement.querySelectorAll('body > *');
124                     scope.$emit('markdown-scroll', totalLines.length);
125                 });
126
127                 // Handle image paste
128                 cm.on('paste', (cm, event) => {
129                     if (!event.clipboardData || !event.clipboardData.items) return;
130                     for (let i = 0; i < event.clipboardData.items.length; i++) {
131                         uploadImage(event.clipboardData.items[i].getAsFile());
132                     }
133                 });
134
135                 // Handle images on drag-drop
136                 cm.on('drop', (cm, event) => {
137                     event.stopPropagation();
138                     event.preventDefault();
139                     let cursorPos = cm.coordsChar({left: event.pageX, top: event.pageY});
140                     cm.setCursor(cursorPos);
141                     if (!event.dataTransfer || !event.dataTransfer.files) return;
142                     for (let i = 0; i < event.dataTransfer.files.length; i++) {
143                         uploadImage(event.dataTransfer.files[i]);
144                     }
145                 });
146
147                 // Helper to replace editor content
148                 function replaceContent(search, replace) {
149                     let text = cm.getValue();
150                     let cursor = cm.listSelections();
151                     cm.setValue(text.replace(search, replace));
152                     cm.setSelections(cursor);
153                 }
154
155                 // Helper to replace the start of the line
156                 function replaceLineStart(newStart) {
157                     let cursor = cm.getCursor();
158                     let lineContent = cm.getLine(cursor.line);
159                     let lineLen = lineContent.length;
160                     let lineStart = lineContent.split(' ')[0];
161
162                     // Remove symbol if already set
163                     if (lineStart === newStart) {
164                         lineContent = lineContent.replace(`${newStart} `, '');
165                         cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
166                         cm.setCursor({line: cursor.line, ch: cursor.ch - (newStart.length + 1)});
167                         return;
168                     }
169
170                     let alreadySymbol = /^[#>`]/.test(lineStart);
171                     let posDif = 0;
172                     if (alreadySymbol) {
173                         posDif = newStart.length - lineStart.length;
174                         lineContent = lineContent.replace(lineStart, newStart).trim();
175                     } else if (newStart !== '') {
176                         posDif = newStart.length + 1;
177                         lineContent = newStart + ' ' + lineContent;
178                     }
179                     cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
180                     cm.setCursor({line: cursor.line, ch: cursor.ch + posDif});
181                 }
182
183                 function wrapLine(start, end) {
184                     let cursor = cm.getCursor();
185                     let lineContent = cm.getLine(cursor.line);
186                     let lineLen = lineContent.length;
187                     let newLineContent = lineContent;
188
189                     if (lineContent.indexOf(start) === 0 && lineContent.slice(-end.length) === end) {
190                         newLineContent = lineContent.slice(start.length, lineContent.length - end.length);
191                     } else {
192                         newLineContent = `${start}${lineContent}${end}`;
193                     }
194
195                     cm.replaceRange(newLineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
196                     cm.setCursor({line: cursor.line, ch: cursor.ch + (newLineContent.length - lineLen)});
197                 }
198
199                 function wrapSelection(start, end) {
200                     let selection = cm.getSelection();
201                     if (selection === '') return wrapLine(start, end);
202                     let newSelection = selection;
203                     let frontDiff = 0;
204                     let endDiff = 0;
205
206                     if (selection.indexOf(start) === 0 && selection.slice(-end.length) === end) {
207                         newSelection = selection.slice(start.length, selection.length - end.length);
208                         endDiff = -(end.length + start.length);
209                     } else {
210                         newSelection = `${start}${selection}${end}`;
211                         endDiff = start.length + end.length;
212                     }
213
214                     let selections = cm.listSelections()[0];
215                     cm.replaceSelection(newSelection);
216                     let headFirst = selections.head.ch <= selections.anchor.ch;
217                     selections.head.ch += headFirst ? frontDiff : endDiff;
218                     selections.anchor.ch += headFirst ? endDiff : frontDiff;
219                     cm.setSelections([selections]);
220                 }
221
222                 // Handle image upload and add image into markdown content
223                 function uploadImage(file) {
224                     if (file === null || file.type.indexOf('image') !== 0) return;
225                     let ext = 'png';
226
227                     if (file.name) {
228                         let fileNameMatches = file.name.match(/\.(.+)$/);
229                         if (fileNameMatches.length > 1) ext = fileNameMatches[1];
230                     }
231
232                     // Insert image into markdown
233                     let id = "image-" + Math.random().toString(16).slice(2);
234                     let placeholderImage = window.baseUrl(`/loading.gif#upload${id}`);
235                     let selectedText = cm.getSelection();
236                     let placeHolderText = `![${selectedText}](${placeholderImage})`;
237                     cm.replaceSelection(placeHolderText);
238
239                     let remoteFilename = "image-" + Date.now() + "." + ext;
240                     let formData = new FormData();
241                     formData.append('file', file, remoteFilename);
242
243                     window.$http.post('/images/gallery/upload', formData).then(resp => {
244                         replaceContent(placeholderImage, resp.data.thumbs.display);
245                     }).catch(err => {
246                         events.emit('error', trans('errors.image_upload_error'));
247                         replaceContent(placeHolderText, selectedText);
248                         console.log(err);
249                     });
250                 }
251
252                 // Show the popup link selector and insert a link when finished
253                 function showLinkSelector() {
254                     let cursorPos = cm.getCursor('from');
255                     window.showEntityLinkSelector(entity => {
256                         let selectedText = cm.getSelection() || entity.name;
257                         let newText = `[${selectedText}](${entity.link})`;
258                         cm.focus();
259                         cm.replaceSelection(newText);
260                         cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
261                     });
262                 }
263
264                 function insertLink() {
265                     let cursorPos = cm.getCursor('from');
266                     let selectedText = cm.getSelection() || '';
267                     let newText = `[${selectedText}]()`;
268                     cm.focus();
269                     cm.replaceSelection(newText);
270                     let cursorPosDiff = (selectedText === '') ? -3 : -1;
271                     cm.setCursor(cursorPos.line, cursorPos.ch + newText.length+cursorPosDiff);
272                 }
273
274                 // Show the image manager and handle image insertion
275                 function showImageManager() {
276                     let cursorPos = cm.getCursor('from');
277                     window.ImageManager.show(image => {
278                         let selectedText = cm.getSelection();
279                         let newText = "![" + (selectedText || image.name) + "](" + image.thumbs.display + ")";
280                         cm.focus();
281                         cm.replaceSelection(newText);
282                         cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
283                     });
284                 }
285
286                 // Update the data models and rendered output
287                 function update(instance) {
288                     let content = instance.getValue();
289                     element.val(content);
290                     $timeout(() => {
291                         scope.mdModel = content;
292                         scope.mdChange(md.render(content));
293                     });
294                 }
295                 update(cm);
296
297                 // Listen to commands from parent scope
298                 scope.$on('md-insert-link', showLinkSelector);
299                 scope.$on('md-insert-image', showImageManager);
300                 scope.$on('markdown-update', (event, value) => {
301                     cm.setValue(value);
302                     element.val(value);
303                     scope.mdModel = value;
304                     scope.mdChange(md.render(value));
305                 });
306
307             }
308         }
309     }]);
310
311     /**
312      * Markdown Editor
313      * Handles all functionality of the markdown editor.
314      */
315     ngApp.directive('markdownEditor', ['$timeout', '$rootScope', function ($timeout, $rootScope) {
316         return {
317             restrict: 'A',
318             link: function (scope, element, attrs) {
319
320                 // Editor Elements
321                 const $display = element.find('.markdown-display').first();
322                 const $insertImage = element.find('button[data-action="insertImage"]');
323                 const $insertEntityLink = element.find('button[data-action="insertEntityLink"]');
324
325                 // Prevent markdown display link click redirect
326                 $display.on('click', 'a', function(event) {
327                     event.preventDefault();
328                     window.open(this.getAttribute('href'));
329                 });
330
331                 // Editor UI Actions
332                 $insertEntityLink.click(e => {scope.$broadcast('md-insert-link');});
333                 $insertImage.click(e => {scope.$broadcast('md-insert-image');});
334
335                 // Handle scroll sync event from editor scroll
336                 $rootScope.$on('markdown-scroll', (event, lineCount) => {
337                     let elems = $display[0].children[0].children;
338                     if (elems.length > lineCount) {
339                         let topElem = (lineCount === -1) ? elems[elems.length-1] : elems[lineCount];
340                         $display.animate({
341                             scrollTop: topElem.offsetTop
342                         }, {queue: false, duration: 200, easing: 'linear'});
343                     }
344                 });
345             }
346         }
347     }]);
348
349     /**
350      * Page Editor Toolbox
351      * Controls all functionality for the sliding toolbox
352      * on the page edit view.
353      */
354     ngApp.directive('toolbox', [function () {
355         return {
356             restrict: 'A',
357             link: function (scope, elem, attrs) {
358
359                 // Get common elements
360                 const $buttons = elem.find('[toolbox-tab-button]');
361                 const $content = elem.find('[toolbox-tab-content]');
362                 const $toggle = elem.find('[toolbox-toggle]');
363
364                 // Handle toolbox toggle click
365                 $toggle.click((e) => {
366                     elem.toggleClass('open');
367                 });
368
369                 // Set an active tab/content by name
370                 function setActive(tabName, openToolbox) {
371                     $buttons.removeClass('active');
372                     $content.hide();
373                     $buttons.filter(`[toolbox-tab-button="${tabName}"]`).addClass('active');
374                     $content.filter(`[toolbox-tab-content="${tabName}"]`).show();
375                     if (openToolbox) elem.addClass('open');
376                 }
377
378                 // Set the first tab content active on load
379                 setActive($content.first().attr('toolbox-tab-content'), false);
380
381                 // Handle tab button click
382                 $buttons.click(function (e) {
383                     let name = $(this).attr('toolbox-tab-button');
384                     setActive(name, true);
385                 });
386             }
387         }
388     }]);
389
390     ngApp.directive('entityLinkSelector', [function($http) {
391         return {
392             restrict: 'A',
393             link: function(scope, element, attrs) {
394
395                 const selectButton = element.find('.entity-link-selector-confirm');
396                 let callback = false;
397                 let entitySelection = null;
398
399                 // Handle entity selection change, Stores the selected entity locally
400                 function entitySelectionChange(entity) {
401                     entitySelection = entity;
402                     if (entity === null) {
403                         selectButton.attr('disabled', 'true');
404                     } else {
405                         selectButton.removeAttr('disabled');
406                     }
407                 }
408                 events.listen('entity-select-change', entitySelectionChange);
409
410                 // Handle selection confirm button click
411                 selectButton.click(event => {
412                     hide();
413                     if (entitySelection !== null) callback(entitySelection);
414                 });
415
416                 // Show selector interface
417                 function show() {
418                     element.fadeIn(240);
419                 }
420
421                 // Hide selector interface
422                 function hide() {
423                     element.fadeOut(240);
424                 }
425                 scope.hide = hide;
426
427                 // Listen to confirmation of entity selections (doubleclick)
428                 events.listen('entity-select-confirm', entity => {
429                     hide();
430                     callback(entity);
431                 });
432
433                 // Show entity selector, Accessible globally, and store the callback
434                 window.showEntityLinkSelector = function(passedCallback) {
435                     show();
436                     callback = passedCallback;
437                 };
438
439             }
440         };
441     }]);
442
443
444     ngApp.directive('entitySelector', ['$http', '$sce', function ($http, $sce) {
445         return {
446             restrict: 'A',
447             scope: true,
448             link: function (scope, element, attrs) {
449                 scope.loading = true;
450                 scope.entityResults = false;
451                 scope.search = '';
452
453                 // Add input for forms
454                 const input = element.find('[entity-selector-input]').first();
455
456                 // Detect double click events
457                 let lastClick = 0;
458                 function isDoubleClick() {
459                     let now = Date.now();
460                     let answer = now - lastClick < 300;
461                     lastClick = now;
462                     return answer;
463                 }
464
465                 // Listen to entity item clicks
466                 element.on('click', '.entity-list a', function(event) {
467                     event.preventDefault();
468                     event.stopPropagation();
469                     let item = $(this).closest('[data-entity-type]');
470                     itemSelect(item, isDoubleClick());
471                 });
472                 element.on('click', '[data-entity-type]', function(event) {
473                     itemSelect($(this), isDoubleClick());
474                 });
475
476                 // Select entity action
477                 function itemSelect(item, doubleClick) {
478                     let entityType = item.attr('data-entity-type');
479                     let entityId = item.attr('data-entity-id');
480                     let isSelected = !item.hasClass('selected') || doubleClick;
481                     element.find('.selected').removeClass('selected').removeClass('primary-background');
482                     if (isSelected) item.addClass('selected').addClass('primary-background');
483                     let newVal = isSelected ? `${entityType}:${entityId}` : '';
484                     input.val(newVal);
485
486                     if (!isSelected) {
487                         events.emit('entity-select-change', null);
488                     }
489
490                     if (!doubleClick && !isSelected) return;
491
492                     let link = item.find('.entity-list-item-link').attr('href');
493                     let name = item.find('.entity-list-item-name').text();
494
495                     if (doubleClick) {
496                         events.emit('entity-select-confirm', {
497                             id: Number(entityId),
498                             name: name,
499                             link: link
500                         });
501                     }
502
503                     if (isSelected) {
504                         events.emit('entity-select-change', {
505                             id: Number(entityId),
506                             name: name,
507                             link: link
508                         });
509                     }
510                 }
511
512                 // Get search url with correct types
513                 function getSearchUrl() {
514                     let types = (attrs.entityTypes) ? encodeURIComponent(attrs.entityTypes) : encodeURIComponent('page,book,chapter');
515                     return window.baseUrl(`/ajax/search/entities?types=${types}`);
516                 }
517
518                 // Get initial contents
519                 $http.get(getSearchUrl()).then(resp => {
520                     scope.entityResults = $sce.trustAsHtml(resp.data);
521                     scope.loading = false;
522                 });
523
524                 // Search when typing
525                 scope.searchEntities = function() {
526                     scope.loading = true;
527                     input.val('');
528                     let url = getSearchUrl() + '&term=' + encodeURIComponent(scope.search);
529                     $http.get(url).then(resp => {
530                         scope.entityResults = $sce.trustAsHtml(resp.data);
531                         scope.loading = false;
532                     });
533                 };
534             }
535         };
536     }]);
537 };