]> BookStack Code Mirror - bookstack/blob - resources/assets/js/directives.js
Fixed markdown callout tags and cursor pos
[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">', '</p>');};
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 + start.length});
197                 }
198
199                 function wrapSelection(start, end) {
200                     let selection = cm.getSelection();
201                     if (selection === '') return wrapLine(start, end);
202
203                     let newSelection = selection;
204                     let frontDiff = 0;
205                     let endDiff = 0;
206
207                     if (selection.indexOf(start) === 0 && selection.slice(-end.length) === end) {
208                         newSelection = selection.slice(start.length, selection.length - end.length);
209                         endDiff = -(end.length + start.length);
210                     } else {
211                         newSelection = `${start}${selection}${end}`;
212                         endDiff = start.length + end.length;
213                     }
214
215                     let selections = cm.listSelections()[0];
216                     cm.replaceSelection(newSelection);
217                     let headFirst = selections.head.ch <= selections.anchor.ch;
218                     selections.head.ch += headFirst ? frontDiff : endDiff;
219                     selections.anchor.ch += headFirst ? endDiff : frontDiff;
220                     cm.setSelections([selections]);
221                 }
222
223                 // Handle image upload and add image into markdown content
224                 function uploadImage(file) {
225                     if (file === null || file.type.indexOf('image') !== 0) return;
226                     let ext = 'png';
227
228                     if (file.name) {
229                         let fileNameMatches = file.name.match(/\.(.+)$/);
230                         if (fileNameMatches.length > 1) ext = fileNameMatches[1];
231                     }
232
233                     // Insert image into markdown
234                     let id = "image-" + Math.random().toString(16).slice(2);
235                     let placeholderImage = window.baseUrl(`/loading.gif#upload${id}`);
236                     let selectedText = cm.getSelection();
237                     let placeHolderText = `![${selectedText}](${placeholderImage})`;
238                     cm.replaceSelection(placeHolderText);
239
240                     let remoteFilename = "image-" + Date.now() + "." + ext;
241                     let formData = new FormData();
242                     formData.append('file', file, remoteFilename);
243
244                     window.$http.post('/images/gallery/upload', formData).then(resp => {
245                         replaceContent(placeholderImage, resp.data.thumbs.display);
246                     }).catch(err => {
247                         events.emit('error', trans('errors.image_upload_error'));
248                         replaceContent(placeHolderText, selectedText);
249                         console.log(err);
250                     });
251                 }
252
253                 // Show the popup link selector and insert a link when finished
254                 function showLinkSelector() {
255                     let cursorPos = cm.getCursor('from');
256                     window.EntitySelectorPopup.show(entity => {
257                         let selectedText = cm.getSelection() || entity.name;
258                         let newText = `[${selectedText}](${entity.link})`;
259                         cm.focus();
260                         cm.replaceSelection(newText);
261                         cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
262                     });
263                 }
264
265                 function insertLink() {
266                     let cursorPos = cm.getCursor('from');
267                     let selectedText = cm.getSelection() || '';
268                     let newText = `[${selectedText}]()`;
269                     cm.focus();
270                     cm.replaceSelection(newText);
271                     let cursorPosDiff = (selectedText === '') ? -3 : -1;
272                     cm.setCursor(cursorPos.line, cursorPos.ch + newText.length+cursorPosDiff);
273                 }
274
275                 // Show the image manager and handle image insertion
276                 function showImageManager() {
277                     let cursorPos = cm.getCursor('from');
278                     window.ImageManager.show(image => {
279                         let selectedText = cm.getSelection();
280                         let newText = "![" + (selectedText || image.name) + "](" + image.thumbs.display + ")";
281                         cm.focus();
282                         cm.replaceSelection(newText);
283                         cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
284                     });
285                 }
286
287                 // Update the data models and rendered output
288                 function update(instance) {
289                     let content = instance.getValue();
290                     element.val(content);
291                     $timeout(() => {
292                         scope.mdModel = content;
293                         scope.mdChange(md.render(content));
294                     });
295                 }
296                 update(cm);
297
298                 // Listen to commands from parent scope
299                 scope.$on('md-insert-link', showLinkSelector);
300                 scope.$on('md-insert-image', showImageManager);
301                 scope.$on('markdown-update', (event, value) => {
302                     cm.setValue(value);
303                     element.val(value);
304                     scope.mdModel = value;
305                     scope.mdChange(md.render(value));
306                 });
307
308             }
309         }
310     }]);
311
312     /**
313      * Markdown Editor
314      * Handles all functionality of the markdown editor.
315      */
316     ngApp.directive('markdownEditor', ['$timeout', '$rootScope', function ($timeout, $rootScope) {
317         return {
318             restrict: 'A',
319             link: function (scope, element, attrs) {
320
321                 // Editor Elements
322                 const $display = element.find('.markdown-display').first();
323                 const $insertImage = element.find('button[data-action="insertImage"]');
324                 const $insertEntityLink = element.find('button[data-action="insertEntityLink"]');
325
326                 // Prevent markdown display link click redirect
327                 $display.on('click', 'a', function(event) {
328                     event.preventDefault();
329                     window.open(this.getAttribute('href'));
330                 });
331
332                 // Editor UI Actions
333                 $insertEntityLink.click(e => {scope.$broadcast('md-insert-link');});
334                 $insertImage.click(e => {scope.$broadcast('md-insert-image');});
335
336                 // Handle scroll sync event from editor scroll
337                 $rootScope.$on('markdown-scroll', (event, lineCount) => {
338                     let elems = $display[0].children[0].children;
339                     if (elems.length > lineCount) {
340                         let topElem = (lineCount === -1) ? elems[elems.length-1] : elems[lineCount];
341                         $display.animate({
342                             scrollTop: topElem.offsetTop
343                         }, {queue: false, duration: 200, easing: 'linear'});
344                     }
345                 });
346             }
347         }
348     }]);
349
350     /**
351      * Page Editor Toolbox
352      * Controls all functionality for the sliding toolbox
353      * on the page edit view.
354      */
355     ngApp.directive('toolbox', [function () {
356         return {
357             restrict: 'A',
358             link: function (scope, elem, attrs) {
359
360                 // Get common elements
361                 const $buttons = elem.find('[toolbox-tab-button]');
362                 const $content = elem.find('[toolbox-tab-content]');
363                 const $toggle = elem.find('[toolbox-toggle]');
364
365                 // Handle toolbox toggle click
366                 $toggle.click((e) => {
367                     elem.toggleClass('open');
368                 });
369
370                 // Set an active tab/content by name
371                 function setActive(tabName, openToolbox) {
372                     $buttons.removeClass('active');
373                     $content.hide();
374                     $buttons.filter(`[toolbox-tab-button="${tabName}"]`).addClass('active');
375                     $content.filter(`[toolbox-tab-content="${tabName}"]`).show();
376                     if (openToolbox) elem.addClass('open');
377                 }
378
379                 // Set the first tab content active on load
380                 setActive($content.first().attr('toolbox-tab-content'), false);
381
382                 // Handle tab button click
383                 $buttons.click(function (e) {
384                     let name = $(this).attr('toolbox-tab-button');
385                     setActive(name, true);
386                 });
387             }
388         }
389     }]);
390 };