]> BookStack Code Mirror - bookstack/blob - resources/assets/js/directives.js
Merge branch 'master' of git://github.com/Abijeet/BookStack into Abijeet-master
[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.EntitySelectorPopup.show(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 };