]> BookStack Code Mirror - bookstack/blob - resources/assets/js/directives.js
Updated italian translation
[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 input 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                         if (event.keyCode === 83 && (navigator.platform.match("Mac") ? event.metaKey : event.ctrlKey)) {
33                             event.preventDefault();
34                             scope.$emit('save-draft', event);
35                         }
36                     });
37
38                     editor.on('init', (e) => {
39                         scope.mceModel = editor.getContent();
40                     });
41
42                     scope.$on('html-update', (event, value) => {
43                         editor.setContent(value);
44                         editor.selection.select(editor.getBody(), true);
45                         editor.selection.collapse(false);
46                         scope.mceModel = editor.getContent();
47                     });
48                 }
49
50                 scope.tinymce.extraSetups.push(tinyMceSetup);
51                 tinymce.init(scope.tinymce);
52             }
53         }
54     }]);
55
56     const md = new MarkdownIt({html: true});
57     md.use(mdTasksLists, {label: true});
58
59     /**
60      * Markdown input
61      * Handles the logic for just the editor input field.
62      */
63     ngApp.directive('markdownInput', ['$timeout', function ($timeout) {
64         return {
65             restrict: 'A',
66             scope: {
67                 mdModel: '=',
68                 mdChange: '='
69             },
70             link: function (scope, element, attrs) {
71
72                 // Codemirror Setup
73                 element = element.find('textarea').first();
74                 let cm = code.markdownEditor(element[0]);
75
76                 // Custom key commands
77                 let metaKey = code.getMetaKey();
78                 const extraKeys = {};
79                 // Insert Image shortcut
80                 extraKeys[`${metaKey}-Alt-I`] = function(cm) {
81                     let selectedText = cm.getSelection();
82                     let newText = `![${selectedText}](http://)`;
83                     let cursorPos = cm.getCursor('from');
84                     cm.replaceSelection(newText);
85                     cm.setCursor(cursorPos.line, cursorPos.ch + newText.length -1);
86                 };
87                 // Save draft
88                 extraKeys[`${metaKey}-S`] = function(cm) {scope.$emit('save-draft');};
89                 // Show link selector
90                 extraKeys[`Shift-${metaKey}-K`] = function(cm) {showLinkSelector()};
91                 // Insert Link
92                 extraKeys[`${metaKey}-K`] = function(cm) {insertLink()};
93                 // FormatShortcuts
94                 extraKeys[`${metaKey}-1`] = function(cm) {replaceLineStart('##');};
95                 extraKeys[`${metaKey}-2`] = function(cm) {replaceLineStart('###');};
96                 extraKeys[`${metaKey}-3`] = function(cm) {replaceLineStart('####');};
97                 extraKeys[`${metaKey}-4`] = function(cm) {replaceLineStart('#####');};
98                 extraKeys[`${metaKey}-5`] = function(cm) {replaceLineStart('');};
99                 extraKeys[`${metaKey}-d`] = function(cm) {replaceLineStart('');};
100                 extraKeys[`${metaKey}-6`] = function(cm) {replaceLineStart('>');};
101                 extraKeys[`${metaKey}-q`] = function(cm) {replaceLineStart('>');};
102                 extraKeys[`${metaKey}-7`] = function(cm) {wrapSelection('\n```\n', '\n```');};
103                 extraKeys[`${metaKey}-8`] = function(cm) {wrapSelection('`', '`');};
104                 extraKeys[`Shift-${metaKey}-E`] = function(cm) {wrapSelection('`', '`');};
105                 extraKeys[`${metaKey}-9`] = function(cm) {wrapSelection('<p class="callout info">', '</p>');};
106                 cm.setOption('extraKeys', extraKeys);
107
108                 // Update data on content change
109                 cm.on('change', (instance, changeObj) => {
110                     update(instance);
111                 });
112
113                 // Handle scroll to sync display view
114                 cm.on('scroll', instance => {
115                     // Thanks to http://liuhao.im/english/2015/11/10/the-sync-scroll-of-markdown-editor-in-javascript.html
116                     let scroll = instance.getScrollInfo();
117                     let atEnd = scroll.top + scroll.clientHeight === scroll.height;
118                     if (atEnd) {
119                         scope.$emit('markdown-scroll', -1);
120                         return;
121                     }
122                     let lineNum = instance.lineAtHeight(scroll.top, 'local');
123                     let range = instance.getRange({line: 0, ch: null}, {line: lineNum, ch: null});
124                     let parser = new DOMParser();
125                     let doc = parser.parseFromString(md.render(range), 'text/html');
126                     let totalLines = doc.documentElement.querySelectorAll('body > *');
127                     scope.$emit('markdown-scroll', totalLines.length);
128                 });
129
130                 // Handle image paste
131                 cm.on('paste', (cm, event) => {
132                     if (!event.clipboardData || !event.clipboardData.items) return;
133                     for (let i = 0; i < event.clipboardData.items.length; i++) {
134                         uploadImage(event.clipboardData.items[i].getAsFile());
135                     }
136                 });
137
138                 // Handle images on drag-drop
139                 cm.on('drop', (cm, event) => {
140                     event.stopPropagation();
141                     event.preventDefault();
142                     let cursorPos = cm.coordsChar({left: event.pageX, top: event.pageY});
143                     cm.setCursor(cursorPos);
144                     if (!event.dataTransfer || !event.dataTransfer.files) return;
145                     for (let i = 0; i < event.dataTransfer.files.length; i++) {
146                         uploadImage(event.dataTransfer.files[i]);
147                     }
148                 });
149
150                 // Helper to replace editor content
151                 function replaceContent(search, replace) {
152                     let text = cm.getValue();
153                     let cursor = cm.listSelections();
154                     cm.setValue(text.replace(search, replace));
155                     cm.setSelections(cursor);
156                 }
157
158                 // Helper to replace the start of the line
159                 function replaceLineStart(newStart) {
160                     let cursor = cm.getCursor();
161                     let lineContent = cm.getLine(cursor.line);
162                     let lineLen = lineContent.length;
163                     let lineStart = lineContent.split(' ')[0];
164
165                     // Remove symbol if already set
166                     if (lineStart === newStart) {
167                         lineContent = lineContent.replace(`${newStart} `, '');
168                         cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
169                         cm.setCursor({line: cursor.line, ch: cursor.ch - (newStart.length + 1)});
170                         return;
171                     }
172
173                     let alreadySymbol = /^[#>`]/.test(lineStart);
174                     let posDif = 0;
175                     if (alreadySymbol) {
176                         posDif = newStart.length - lineStart.length;
177                         lineContent = lineContent.replace(lineStart, newStart).trim();
178                     } else if (newStart !== '') {
179                         posDif = newStart.length + 1;
180                         lineContent = newStart + ' ' + lineContent;
181                     }
182                     cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
183                     cm.setCursor({line: cursor.line, ch: cursor.ch + posDif});
184                 }
185
186                 function wrapLine(start, end) {
187                     let cursor = cm.getCursor();
188                     let lineContent = cm.getLine(cursor.line);
189                     let lineLen = lineContent.length;
190                     let newLineContent = lineContent;
191
192                     if (lineContent.indexOf(start) === 0 && lineContent.slice(-end.length) === end) {
193                         newLineContent = lineContent.slice(start.length, lineContent.length - end.length);
194                     } else {
195                         newLineContent = `${start}${lineContent}${end}`;
196                     }
197
198                     cm.replaceRange(newLineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
199                     cm.setCursor({line: cursor.line, ch: cursor.ch + start.length});
200                 }
201
202                 function wrapSelection(start, end) {
203                     let selection = cm.getSelection();
204                     if (selection === '') return wrapLine(start, end);
205
206                     let newSelection = selection;
207                     let frontDiff = 0;
208                     let endDiff = 0;
209
210                     if (selection.indexOf(start) === 0 && selection.slice(-end.length) === end) {
211                         newSelection = selection.slice(start.length, selection.length - end.length);
212                         endDiff = -(end.length + start.length);
213                     } else {
214                         newSelection = `${start}${selection}${end}`;
215                         endDiff = start.length + end.length;
216                     }
217
218                     let selections = cm.listSelections()[0];
219                     cm.replaceSelection(newSelection);
220                     let headFirst = selections.head.ch <= selections.anchor.ch;
221                     selections.head.ch += headFirst ? frontDiff : endDiff;
222                     selections.anchor.ch += headFirst ? endDiff : frontDiff;
223                     cm.setSelections([selections]);
224                 }
225
226                 // Handle image upload and add image into markdown content
227                 function uploadImage(file) {
228                     if (file === null || file.type.indexOf('image') !== 0) return;
229                     let ext = 'png';
230
231                     if (file.name) {
232                         let fileNameMatches = file.name.match(/\.(.+)$/);
233                         if (fileNameMatches.length > 1) ext = fileNameMatches[1];
234                     }
235
236                     // Insert image into markdown
237                     let id = "image-" + Math.random().toString(16).slice(2);
238                     let placeholderImage = window.baseUrl(`/loading.gif#upload${id}`);
239                     let selectedText = cm.getSelection();
240                     let placeHolderText = `![${selectedText}](${placeholderImage})`;
241                     cm.replaceSelection(placeHolderText);
242
243                     let remoteFilename = "image-" + Date.now() + "." + ext;
244                     let formData = new FormData();
245                     formData.append('file', file, remoteFilename);
246
247                     window.$http.post('/images/gallery/upload', formData).then(resp => {
248                         replaceContent(placeholderImage, resp.data.thumbs.display);
249                     }).catch(err => {
250                         events.emit('error', trans('errors.image_upload_error'));
251                         replaceContent(placeHolderText, selectedText);
252                         console.log(err);
253                     });
254                 }
255
256                 // Show the popup link selector and insert a link when finished
257                 function showLinkSelector() {
258                     let cursorPos = cm.getCursor('from');
259                     window.EntitySelectorPopup.show(entity => {
260                         let selectedText = cm.getSelection() || entity.name;
261                         let newText = `[${selectedText}](${entity.link})`;
262                         cm.focus();
263                         cm.replaceSelection(newText);
264                         cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
265                     });
266                 }
267
268                 function insertLink() {
269                     let cursorPos = cm.getCursor('from');
270                     let selectedText = cm.getSelection() || '';
271                     let newText = `[${selectedText}]()`;
272                     cm.focus();
273                     cm.replaceSelection(newText);
274                     let cursorPosDiff = (selectedText === '') ? -3 : -1;
275                     cm.setCursor(cursorPos.line, cursorPos.ch + newText.length+cursorPosDiff);
276                 }
277
278                 // Show the image manager and handle image insertion
279                 function showImageManager() {
280                     let cursorPos = cm.getCursor('from');
281                     window.ImageManager.show(image => {
282                         let selectedText = cm.getSelection();
283                         let newText = "![" + (selectedText || image.name) + "](" + image.thumbs.display + ")";
284                         cm.focus();
285                         cm.replaceSelection(newText);
286                         cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
287                     });
288                 }
289
290                 // Update the data models and rendered output
291                 function update(instance) {
292                     let content = instance.getValue();
293                     element.val(content);
294                     $timeout(() => {
295                         scope.mdModel = content;
296                         scope.mdChange(md.render(content));
297                     });
298                 }
299                 update(cm);
300
301                 // Listen to commands from parent scope
302                 scope.$on('md-insert-link', showLinkSelector);
303                 scope.$on('md-insert-image', showImageManager);
304                 scope.$on('markdown-update', (event, value) => {
305                     cm.setValue(value);
306                     element.val(value);
307                     scope.mdModel = value;
308                     scope.mdChange(md.render(value));
309                 });
310
311             }
312         }
313     }]);
314
315     /**
316      * Markdown Editor
317      * Handles all functionality of the markdown editor.
318      */
319     ngApp.directive('markdownEditor', ['$timeout', '$rootScope', function ($timeout, $rootScope) {
320         return {
321             restrict: 'A',
322             link: function (scope, element, attrs) {
323
324                 // Editor Elements
325                 const $display = element.find('.markdown-display').first();
326                 const $insertImage = element.find('button[data-action="insertImage"]');
327                 const $insertEntityLink = element.find('button[data-action="insertEntityLink"]');
328
329                 // Prevent markdown display link click redirect
330                 $display.on('click', 'a', function(event) {
331                     event.preventDefault();
332                     window.open(this.getAttribute('href'));
333                 });
334
335                 // Editor UI Actions
336                 $insertEntityLink.click(e => {scope.$broadcast('md-insert-link');});
337                 $insertImage.click(e => {scope.$broadcast('md-insert-image');});
338
339                 // Handle scroll sync event from editor scroll
340                 $rootScope.$on('markdown-scroll', (event, lineCount) => {
341                     let elems = $display[0].children[0].children;
342                     if (elems.length > lineCount) {
343                         let topElem = (lineCount === -1) ? elems[elems.length-1] : elems[lineCount];
344                         $display.animate({
345                             scrollTop: topElem.offsetTop
346                         }, {queue: false, duration: 200, easing: 'linear'});
347                     }
348                 });
349             }
350         }
351     }]);
352
353     /**
354      * Page Editor Toolbox
355      * Controls all functionality for the sliding toolbox
356      * on the page edit view.
357      */
358     ngApp.directive('toolbox', [function () {
359         return {
360             restrict: 'A',
361             link: function (scope, elem, attrs) {
362
363                 // Get common elements
364                 const $buttons = elem.find('[toolbox-tab-button]');
365                 const $content = elem.find('[toolbox-tab-content]');
366                 const $toggle = elem.find('[toolbox-toggle]');
367
368                 // Handle toolbox toggle click
369                 $toggle.click((e) => {
370                     elem.toggleClass('open');
371                 });
372
373                 // Set an active tab/content by name
374                 function setActive(tabName, openToolbox) {
375                     $buttons.removeClass('active');
376                     $content.hide();
377                     $buttons.filter(`[toolbox-tab-button="${tabName}"]`).addClass('active');
378                     $content.filter(`[toolbox-tab-content="${tabName}"]`).show();
379                     if (openToolbox) elem.addClass('open');
380                 }
381
382                 // Set the first tab content active on load
383                 setActive($content.first().attr('toolbox-tab-content'), false);
384
385                 // Handle tab button click
386                 $buttons.click(function (e) {
387                     let name = $(this).attr('toolbox-tab-button');
388                     setActive(name, true);
389                 });
390             }
391         }
392     }]);
393 };