1 const MarkdownIt = require("markdown-it");
2 const mdTasksLists = require('markdown-it-task-lists');
3 const code = require('../services/code');
5 const DrawIO = require('../services/drawio');
11 this.markdown = new MarkdownIt({html: true});
12 this.markdown.use(mdTasksLists, {label: true});
14 this.display = this.elem.querySelector('.markdown-display');
15 this.input = this.elem.querySelector('textarea');
16 this.htmlInput = this.elem.querySelector('input[name=html]');
17 this.cm = code.markdownEditor(this.input);
19 this.onMarkdownScroll = this.onMarkdownScroll.bind(this);
27 // Prevent markdown display link click redirect
28 this.display.addEventListener('click', event => {
29 let isDblClick = Date.now() - lastClick < 300;
31 let link = event.target.closest('a');
33 event.preventDefault();
34 window.open(link.getAttribute('href'));
38 let drawing = event.target.closest('[drawio-diagram]');
39 if (drawing !== null && isDblClick) {
40 this.actionEditDrawing(drawing);
44 lastClick = Date.now();
48 this.elem.addEventListener('click', event => {
49 let button = event.target.closest('button[data-action]');
50 if (button === null) return;
52 let action = button.getAttribute('data-action');
53 if (action === 'insertImage') this.actionInsertImage();
54 if (action === 'insertLink') this.actionShowLinkSelector();
55 if (action === 'insertDrawing' && event.ctrlKey) {
56 this.actionShowImageManager();
59 if (action === 'insertDrawing') this.actionStartDrawing();
62 window.$events.listen('editor-markdown-update', value => {
63 this.cm.setValue(value);
64 this.updateAndRender();
67 this.codeMirrorSetup();
70 // Update the input content and render the display.
72 let content = this.cm.getValue();
73 this.input.value = content;
74 let html = this.markdown.render(content);
75 window.$events.emit('editor-html-change', html);
76 window.$events.emit('editor-markdown-change', content);
77 this.display.innerHTML = html;
78 this.htmlInput.value = html;
81 onMarkdownScroll(lineCount) {
82 let elems = this.display.children;
83 if (elems.length <= lineCount) return;
85 let topElem = (lineCount === -1) ? elems[elems.length-1] : elems[lineCount];
86 // TODO - Replace jQuery
87 $(this.display).animate({
88 scrollTop: topElem.offsetTop
89 }, {queue: false, duration: 200, easing: 'linear'});
94 // Custom key commands
95 let metaKey = code.getMetaKey();
97 // Insert Image shortcut
98 extraKeys[`${metaKey}-Alt-I`] = function(cm) {
99 let selectedText = cm.getSelection();
100 let newText = ``;
101 let cursorPos = cm.getCursor('from');
102 cm.replaceSelection(newText);
103 cm.setCursor(cursorPos.line, cursorPos.ch + newText.length -1);
106 extraKeys[`${metaKey}-S`] = cm => {window.$events.emit('editor-save-draft')};
108 extraKeys[`${metaKey}-Enter`] = cm => {window.$events.emit('editor-save-page')};
109 // Show link selector
110 extraKeys[`Shift-${metaKey}-K`] = cm => {this.actionShowLinkSelector()};
112 extraKeys[`${metaKey}-K`] = cm => {insertLink()};
114 extraKeys[`${metaKey}-1`] = cm => {replaceLineStart('##');};
115 extraKeys[`${metaKey}-2`] = cm => {replaceLineStart('###');};
116 extraKeys[`${metaKey}-3`] = cm => {replaceLineStart('####');};
117 extraKeys[`${metaKey}-4`] = cm => {replaceLineStart('#####');};
118 extraKeys[`${metaKey}-5`] = cm => {replaceLineStart('');};
119 extraKeys[`${metaKey}-d`] = cm => {replaceLineStart('');};
120 extraKeys[`${metaKey}-6`] = cm => {replaceLineStart('>');};
121 extraKeys[`${metaKey}-q`] = cm => {replaceLineStart('>');};
122 extraKeys[`${metaKey}-7`] = cm => {wrapSelection('\n```\n', '\n```');};
123 extraKeys[`${metaKey}-8`] = cm => {wrapSelection('`', '`');};
124 extraKeys[`Shift-${metaKey}-E`] = cm => {wrapSelection('`', '`');};
125 extraKeys[`${metaKey}-9`] = cm => {wrapSelection('<p class="callout info">', '</p>');};
126 cm.setOption('extraKeys', extraKeys);
128 // Update data on content change
129 cm.on('change', (instance, changeObj) => {
130 this.updateAndRender();
133 // Handle scroll to sync display view
134 cm.on('scroll', instance => {
135 // Thanks to http://liuhao.im/english/2015/11/10/the-sync-scroll-of-markdown-editor-in-javascript.html
136 let scroll = instance.getScrollInfo();
137 let atEnd = scroll.top + scroll.clientHeight === scroll.height;
139 this.onMarkdownScroll(-1);
143 let lineNum = instance.lineAtHeight(scroll.top, 'local');
144 let range = instance.getRange({line: 0, ch: null}, {line: lineNum, ch: null});
145 let parser = new DOMParser();
146 let doc = parser.parseFromString(this.markdown.render(range), 'text/html');
147 let totalLines = doc.documentElement.querySelectorAll('body > *');
148 this.onMarkdownScroll(totalLines.length);
151 // Handle image paste
152 cm.on('paste', (cm, event) => {
153 if (!event.clipboardData || !event.clipboardData.items) return;
154 for (let i = 0; i < event.clipboardData.items.length; i++) {
155 uploadImage(event.clipboardData.items[i].getAsFile());
159 // Handle images on drag-drop
160 cm.on('drop', (cm, event) => {
161 event.stopPropagation();
162 event.preventDefault();
163 let cursorPos = cm.coordsChar({left: event.pageX, top: event.pageY});
164 cm.setCursor(cursorPos);
165 if (!event.dataTransfer || !event.dataTransfer.files) return;
166 for (let i = 0; i < event.dataTransfer.files.length; i++) {
167 uploadImage(event.dataTransfer.files[i]);
171 // Helper to replace editor content
172 function replaceContent(search, replace) {
173 let text = cm.getValue();
174 let cursor = cm.listSelections();
175 cm.setValue(text.replace(search, replace));
176 cm.setSelections(cursor);
179 // Helper to replace the start of the line
180 function replaceLineStart(newStart) {
181 let cursor = cm.getCursor();
182 let lineContent = cm.getLine(cursor.line);
183 let lineLen = lineContent.length;
184 let lineStart = lineContent.split(' ')[0];
186 // Remove symbol if already set
187 if (lineStart === newStart) {
188 lineContent = lineContent.replace(`${newStart} `, '');
189 cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
190 cm.setCursor({line: cursor.line, ch: cursor.ch - (newStart.length + 1)});
194 let alreadySymbol = /^[#>`]/.test(lineStart);
197 posDif = newStart.length - lineStart.length;
198 lineContent = lineContent.replace(lineStart, newStart).trim();
199 } else if (newStart !== '') {
200 posDif = newStart.length + 1;
201 lineContent = newStart + ' ' + lineContent;
203 cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
204 cm.setCursor({line: cursor.line, ch: cursor.ch + posDif});
207 function wrapLine(start, end) {
208 let cursor = cm.getCursor();
209 let lineContent = cm.getLine(cursor.line);
210 let lineLen = lineContent.length;
211 let newLineContent = lineContent;
213 if (lineContent.indexOf(start) === 0 && lineContent.slice(-end.length) === end) {
214 newLineContent = lineContent.slice(start.length, lineContent.length - end.length);
216 newLineContent = `${start}${lineContent}${end}`;
219 cm.replaceRange(newLineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
220 cm.setCursor({line: cursor.line, ch: cursor.ch + start.length});
223 function wrapSelection(start, end) {
224 let selection = cm.getSelection();
225 if (selection === '') return wrapLine(start, end);
227 let newSelection = selection;
231 if (selection.indexOf(start) === 0 && selection.slice(-end.length) === end) {
232 newSelection = selection.slice(start.length, selection.length - end.length);
233 endDiff = -(end.length + start.length);
235 newSelection = `${start}${selection}${end}`;
236 endDiff = start.length + end.length;
239 let selections = cm.listSelections()[0];
240 cm.replaceSelection(newSelection);
241 let headFirst = selections.head.ch <= selections.anchor.ch;
242 selections.head.ch += headFirst ? frontDiff : endDiff;
243 selections.anchor.ch += headFirst ? endDiff : frontDiff;
244 cm.setSelections([selections]);
247 // Handle image upload and add image into markdown content
248 function uploadImage(file) {
249 if (file === null || file.type.indexOf('image') !== 0) return;
253 let fileNameMatches = file.name.match(/\.(.+)$/);
254 if (fileNameMatches.length > 1) ext = fileNameMatches[1];
257 // Insert image into markdown
258 let id = "image-" + Math.random().toString(16).slice(2);
259 let placeholderImage = window.baseUrl(`/loading.gif#upload${id}`);
260 let selectedText = cm.getSelection();
261 let placeHolderText = ``;
262 let cursor = cm.getCursor();
263 cm.replaceSelection(placeHolderText);
264 cm.setCursor({line: cursor.line, ch: cursor.ch + selectedText.length + 2});
266 let remoteFilename = "image-" + Date.now() + "." + ext;
267 let formData = new FormData();
268 formData.append('file', file, remoteFilename);
270 window.$http.post('/images/gallery/upload', formData).then(resp => {
271 replaceContent(placeholderImage, resp.data.thumbs.display);
273 window.$events.emit('error', trans('errors.image_upload_error'));
274 replaceContent(placeHolderText, selectedText);
279 function insertLink() {
280 let cursorPos = cm.getCursor('from');
281 let selectedText = cm.getSelection() || '';
282 let newText = `[${selectedText}]()`;
284 cm.replaceSelection(newText);
285 let cursorPosDiff = (selectedText === '') ? -3 : -1;
286 cm.setCursor(cursorPos.line, cursorPos.ch + newText.length+cursorPosDiff);
289 this.updateAndRender();
292 actionInsertImage() {
293 let cursorPos = this.cm.getCursor('from');
294 window.ImageManager.show(image => {
295 let selectedText = this.cm.getSelection();
296 let newText = "";
298 this.cm.replaceSelection(newText);
299 this.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
303 actionShowImageManager() {
304 let cursorPos = this.cm.getCursor('from');
305 window.ImageManager.show(image => {
306 this.insertDrawing(image, cursorPos);
310 // Show the popup link selector and insert a link when finished
311 actionShowLinkSelector() {
312 let cursorPos = this.cm.getCursor('from');
313 window.EntitySelectorPopup.show(entity => {
314 let selectedText = this.cm.getSelection() || entity.name;
315 let newText = `[${selectedText}](${entity.link})`;
317 this.cm.replaceSelection(newText);
318 this.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
322 // Show draw.io if enabled and handle save.
323 actionStartDrawing() {
324 if (document.querySelector('[drawio-enabled]').getAttribute('drawio-enabled') !== 'true') return;
325 let cursorPos = this.cm.getCursor('from');
328 return Promise.resolve('');
330 // let id = "image-" + Math.random().toString(16).slice(2);
331 // let loadingImage = window.baseUrl('/loading.gif');
334 uploaded_to: Number(document.getElementById('page-editor').getAttribute('page-id'))
337 window.$http.post(window.baseUrl('/images/drawing/upload'), data).then(resp => {
338 this.insertDrawing(resp.data, cursorPos);
341 window.$events.emit('error', trans('errors.image_upload_error'));
347 insertDrawing(image, originalCursor) {
348 let newText = `<div drawio-diagram="${image.id}"><img src="${image.url}"></div>`;
350 this.cm.replaceSelection(newText);
351 this.cm.setCursor(originalCursor.line, originalCursor.ch + newText.length);
354 // Show draw.io if enabled and handle save.
355 actionEditDrawing(imgContainer) {
356 if (document.querySelector('[drawio-enabled]').getAttribute('drawio-enabled') !== 'true') return;
357 let cursorPos = this.cm.getCursor('from');
358 let drawingId = imgContainer.getAttribute('drawio-diagram');
361 return window.$http.get(window.baseUrl(`/images/base64/${drawingId}`)).then(resp => {
362 return `data:image/png;base64,${resp.data.content}`;
368 uploaded_to: Number(document.getElementById('page-editor').getAttribute('page-id'))
371 window.$http.post(window.baseUrl(`/images/drawing/upload`), data).then(resp => {
372 let newText = `<div drawio-diagram="${resp.data.id}"><img src="${resp.data.url}"></div>`;
373 let newContent = this.cm.getValue().split('\n').map(line => {
374 if (line.indexOf(`drawio-diagram="${drawingId}"`) !== -1) {
379 this.cm.setValue(newContent);
380 this.cm.setCursor(cursorPos);
384 window.$events.emit('error', trans('errors.image_upload_error'));
392 module.exports = MarkdownEditor ;