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);
22 // Scroll to text if needed.
23 const queryParams = (new URL(window.location)).searchParams;
24 const scrollText = queryParams.get('content-text');
26 this.scrollToText(scrollText);
34 // Prevent markdown display link click redirect
35 this.display.addEventListener('click', event => {
36 let isDblClick = Date.now() - lastClick < 300;
38 let link = event.target.closest('a');
40 event.preventDefault();
41 window.open(link.getAttribute('href'));
45 let drawing = event.target.closest('[drawio-diagram]');
46 if (drawing !== null && isDblClick) {
47 this.actionEditDrawing(drawing);
51 lastClick = Date.now();
55 this.elem.addEventListener('click', event => {
56 let button = event.target.closest('button[data-action]');
57 if (button === null) return;
59 let action = button.getAttribute('data-action');
60 if (action === 'insertImage') this.actionInsertImage();
61 if (action === 'insertLink') this.actionShowLinkSelector();
62 if (action === 'insertDrawing' && event.ctrlKey) {
63 this.actionShowImageManager();
66 if (action === 'insertDrawing') this.actionStartDrawing();
69 window.$events.listen('editor-markdown-update', value => {
70 this.cm.setValue(value);
71 this.updateAndRender();
74 this.codeMirrorSetup();
77 // Update the input content and render the display.
79 let content = this.cm.getValue();
80 this.input.value = content;
81 let html = this.markdown.render(content);
82 window.$events.emit('editor-html-change', html);
83 window.$events.emit('editor-markdown-change', content);
84 this.display.innerHTML = html;
85 this.htmlInput.value = html;
88 onMarkdownScroll(lineCount) {
89 let elems = this.display.children;
90 if (elems.length <= lineCount) return;
92 let topElem = (lineCount === -1) ? elems[elems.length-1] : elems[lineCount];
93 // TODO - Replace jQuery
94 $(this.display).animate({
95 scrollTop: topElem.offsetTop
96 }, {queue: false, duration: 200, easing: 'linear'});
101 // Custom key commands
102 let metaKey = code.getMetaKey();
103 const extraKeys = {};
104 // Insert Image shortcut
105 extraKeys[`${metaKey}-Alt-I`] = function(cm) {
106 let selectedText = cm.getSelection();
107 let newText = ``;
108 let cursorPos = cm.getCursor('from');
109 cm.replaceSelection(newText);
110 cm.setCursor(cursorPos.line, cursorPos.ch + newText.length -1);
113 extraKeys[`${metaKey}-S`] = cm => {window.$events.emit('editor-save-draft')};
115 extraKeys[`${metaKey}-Enter`] = cm => {window.$events.emit('editor-save-page')};
116 // Show link selector
117 extraKeys[`Shift-${metaKey}-K`] = cm => {this.actionShowLinkSelector()};
119 extraKeys[`${metaKey}-K`] = cm => {insertLink()};
121 extraKeys[`${metaKey}-1`] = cm => {replaceLineStart('##');};
122 extraKeys[`${metaKey}-2`] = cm => {replaceLineStart('###');};
123 extraKeys[`${metaKey}-3`] = cm => {replaceLineStart('####');};
124 extraKeys[`${metaKey}-4`] = cm => {replaceLineStart('#####');};
125 extraKeys[`${metaKey}-5`] = cm => {replaceLineStart('');};
126 extraKeys[`${metaKey}-d`] = cm => {replaceLineStart('');};
127 extraKeys[`${metaKey}-6`] = cm => {replaceLineStart('>');};
128 extraKeys[`${metaKey}-q`] = cm => {replaceLineStart('>');};
129 extraKeys[`${metaKey}-7`] = cm => {wrapSelection('\n```\n', '\n```');};
130 extraKeys[`${metaKey}-8`] = cm => {wrapSelection('`', '`');};
131 extraKeys[`Shift-${metaKey}-E`] = cm => {wrapSelection('`', '`');};
132 extraKeys[`${metaKey}-9`] = cm => {wrapSelection('<p class="callout info">', '</p>');};
133 cm.setOption('extraKeys', extraKeys);
135 // Update data on content change
136 cm.on('change', (instance, changeObj) => {
137 this.updateAndRender();
140 // Handle scroll to sync display view
141 cm.on('scroll', instance => {
142 // Thanks to http://liuhao.im/english/2015/11/10/the-sync-scroll-of-markdown-editor-in-javascript.html
143 let scroll = instance.getScrollInfo();
144 let atEnd = scroll.top + scroll.clientHeight === scroll.height;
146 this.onMarkdownScroll(-1);
150 let lineNum = instance.lineAtHeight(scroll.top, 'local');
151 let range = instance.getRange({line: 0, ch: null}, {line: lineNum, ch: null});
152 let parser = new DOMParser();
153 let doc = parser.parseFromString(this.markdown.render(range), 'text/html');
154 let totalLines = doc.documentElement.querySelectorAll('body > *');
155 this.onMarkdownScroll(totalLines.length);
158 // Handle image paste
159 cm.on('paste', (cm, event) => {
160 if (!event.clipboardData || !event.clipboardData.items) return;
161 for (let i = 0; i < event.clipboardData.items.length; i++) {
162 uploadImage(event.clipboardData.items[i].getAsFile());
166 // Handle images on drag-drop
167 cm.on('drop', (cm, event) => {
168 event.stopPropagation();
169 event.preventDefault();
170 let cursorPos = cm.coordsChar({left: event.pageX, top: event.pageY});
171 cm.setCursor(cursorPos);
172 if (!event.dataTransfer || !event.dataTransfer.files) return;
173 for (let i = 0; i < event.dataTransfer.files.length; i++) {
174 uploadImage(event.dataTransfer.files[i]);
178 // Helper to replace editor content
179 function replaceContent(search, replace) {
180 let text = cm.getValue();
181 let cursor = cm.listSelections();
182 cm.setValue(text.replace(search, replace));
183 cm.setSelections(cursor);
186 // Helper to replace the start of the line
187 function replaceLineStart(newStart) {
188 let cursor = cm.getCursor();
189 let lineContent = cm.getLine(cursor.line);
190 let lineLen = lineContent.length;
191 let lineStart = lineContent.split(' ')[0];
193 // Remove symbol if already set
194 if (lineStart === newStart) {
195 lineContent = lineContent.replace(`${newStart} `, '');
196 cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
197 cm.setCursor({line: cursor.line, ch: cursor.ch - (newStart.length + 1)});
201 let alreadySymbol = /^[#>`]/.test(lineStart);
204 posDif = newStart.length - lineStart.length;
205 lineContent = lineContent.replace(lineStart, newStart).trim();
206 } else if (newStart !== '') {
207 posDif = newStart.length + 1;
208 lineContent = newStart + ' ' + lineContent;
210 cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
211 cm.setCursor({line: cursor.line, ch: cursor.ch + posDif});
214 function wrapLine(start, end) {
215 let cursor = cm.getCursor();
216 let lineContent = cm.getLine(cursor.line);
217 let lineLen = lineContent.length;
218 let newLineContent = lineContent;
220 if (lineContent.indexOf(start) === 0 && lineContent.slice(-end.length) === end) {
221 newLineContent = lineContent.slice(start.length, lineContent.length - end.length);
223 newLineContent = `${start}${lineContent}${end}`;
226 cm.replaceRange(newLineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
227 cm.setCursor({line: cursor.line, ch: cursor.ch + start.length});
230 function wrapSelection(start, end) {
231 let selection = cm.getSelection();
232 if (selection === '') return wrapLine(start, end);
234 let newSelection = selection;
238 if (selection.indexOf(start) === 0 && selection.slice(-end.length) === end) {
239 newSelection = selection.slice(start.length, selection.length - end.length);
240 endDiff = -(end.length + start.length);
242 newSelection = `${start}${selection}${end}`;
243 endDiff = start.length + end.length;
246 let selections = cm.listSelections()[0];
247 cm.replaceSelection(newSelection);
248 let headFirst = selections.head.ch <= selections.anchor.ch;
249 selections.head.ch += headFirst ? frontDiff : endDiff;
250 selections.anchor.ch += headFirst ? endDiff : frontDiff;
251 cm.setSelections([selections]);
254 // Handle image upload and add image into markdown content
255 function uploadImage(file) {
256 if (file === null || file.type.indexOf('image') !== 0) return;
260 let fileNameMatches = file.name.match(/\.(.+)$/);
261 if (fileNameMatches.length > 1) ext = fileNameMatches[1];
264 // Insert image into markdown
265 let id = "image-" + Math.random().toString(16).slice(2);
266 let placeholderImage = window.baseUrl(`/loading.gif#upload${id}`);
267 let selectedText = cm.getSelection();
268 let placeHolderText = ``;
269 let cursor = cm.getCursor();
270 cm.replaceSelection(placeHolderText);
271 cm.setCursor({line: cursor.line, ch: cursor.ch + selectedText.length + 2});
273 let remoteFilename = "image-" + Date.now() + "." + ext;
274 let formData = new FormData();
275 formData.append('file', file, remoteFilename);
277 window.$http.post('/images/gallery/upload', formData).then(resp => {
278 replaceContent(placeholderImage, resp.data.thumbs.display);
280 window.$events.emit('error', trans('errors.image_upload_error'));
281 replaceContent(placeHolderText, selectedText);
286 function insertLink() {
287 let cursorPos = cm.getCursor('from');
288 let selectedText = cm.getSelection() || '';
289 let newText = `[${selectedText}]()`;
291 cm.replaceSelection(newText);
292 let cursorPosDiff = (selectedText === '') ? -3 : -1;
293 cm.setCursor(cursorPos.line, cursorPos.ch + newText.length+cursorPosDiff);
296 this.updateAndRender();
299 actionInsertImage() {
300 let cursorPos = this.cm.getCursor('from');
301 window.ImageManager.show(image => {
302 let selectedText = this.cm.getSelection();
303 let newText = "";
305 this.cm.replaceSelection(newText);
306 this.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
310 actionShowImageManager() {
311 let cursorPos = this.cm.getCursor('from');
312 window.ImageManager.show(image => {
313 this.insertDrawing(image, cursorPos);
317 // Show the popup link selector and insert a link when finished
318 actionShowLinkSelector() {
319 let cursorPos = this.cm.getCursor('from');
320 window.EntitySelectorPopup.show(entity => {
321 let selectedText = this.cm.getSelection() || entity.name;
322 let newText = `[${selectedText}](${entity.link})`;
324 this.cm.replaceSelection(newText);
325 this.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
329 // Show draw.io if enabled and handle save.
330 actionStartDrawing() {
331 if (document.querySelector('[drawio-enabled]').getAttribute('drawio-enabled') !== 'true') return;
332 let cursorPos = this.cm.getCursor('from');
335 return Promise.resolve('');
337 // let id = "image-" + Math.random().toString(16).slice(2);
338 // let loadingImage = window.baseUrl('/loading.gif');
341 uploaded_to: Number(document.getElementById('page-editor').getAttribute('page-id'))
344 window.$http.post(window.baseUrl('/images/drawing/upload'), data).then(resp => {
345 this.insertDrawing(resp.data, cursorPos);
348 window.$events.emit('error', trans('errors.image_upload_error'));
354 insertDrawing(image, originalCursor) {
355 let newText = `<div drawio-diagram="${image.id}"><img src="${image.url}"></div>`;
357 this.cm.replaceSelection(newText);
358 this.cm.setCursor(originalCursor.line, originalCursor.ch + newText.length);
361 // Show draw.io if enabled and handle save.
362 actionEditDrawing(imgContainer) {
363 if (document.querySelector('[drawio-enabled]').getAttribute('drawio-enabled') !== 'true') return;
364 let cursorPos = this.cm.getCursor('from');
365 let drawingId = imgContainer.getAttribute('drawio-diagram');
368 return window.$http.get(window.baseUrl(`/images/base64/${drawingId}`)).then(resp => {
369 return `data:image/png;base64,${resp.data.content}`;
375 uploaded_to: Number(document.getElementById('page-editor').getAttribute('page-id'))
378 window.$http.post(window.baseUrl(`/images/drawing/upload`), data).then(resp => {
379 let newText = `<div drawio-diagram="${resp.data.id}"><img src="${resp.data.url}"></div>`;
380 let newContent = this.cm.getValue().split('\n').map(line => {
381 if (line.indexOf(`drawio-diagram="${drawingId}"`) !== -1) {
386 this.cm.setValue(newContent);
387 this.cm.setCursor(cursorPos);
391 window.$events.emit('error', trans('errors.image_upload_error'));
397 // Scroll to a specified text
398 scrollToText(searchText) {
403 const content = this.cm.getValue();
404 const lines = content.split(/\r?\n/);
405 let lineNumber = lines.findIndex(line => {
406 return line && line.indexOf(searchText) !== -1;
409 if (lineNumber === -1) {
413 this.cm.scrollIntoView({
417 // set the cursor location.
420 char: lines[lineNumber].length
426 module.exports = MarkdownEditor ;