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') this.actionStartDrawing();
58 window.$events.listen('editor-markdown-update', value => {
59 this.cm.setValue(value);
60 this.updateAndRender();
63 this.codeMirrorSetup();
66 // Update the input content and render the display.
68 let content = this.cm.getValue();
69 this.input.value = content;
70 let html = this.markdown.render(content);
71 window.$events.emit('editor-html-change', html);
72 window.$events.emit('editor-markdown-change', content);
73 this.display.innerHTML = html;
74 this.htmlInput.value = html;
77 onMarkdownScroll(lineCount) {
78 let elems = this.display.children;
79 if (elems.length <= lineCount) return;
81 let topElem = (lineCount === -1) ? elems[elems.length-1] : elems[lineCount];
82 // TODO - Replace jQuery
83 $(this.display).animate({
84 scrollTop: topElem.offsetTop
85 }, {queue: false, duration: 200, easing: 'linear'});
90 // Custom key commands
91 let metaKey = code.getMetaKey();
93 // Insert Image shortcut
94 extraKeys[`${metaKey}-Alt-I`] = function(cm) {
95 let selectedText = cm.getSelection();
96 let newText = ``;
97 let cursorPos = cm.getCursor('from');
98 cm.replaceSelection(newText);
99 cm.setCursor(cursorPos.line, cursorPos.ch + newText.length -1);
102 extraKeys[`${metaKey}-S`] = cm => {window.$events.emit('editor-save-draft')};
104 extraKeys[`${metaKey}-Enter`] = cm => {window.$events.emit('editor-save-page')};
105 // Show link selector
106 extraKeys[`Shift-${metaKey}-K`] = cm => {this.actionShowLinkSelector()};
108 extraKeys[`${metaKey}-K`] = cm => {insertLink()};
110 extraKeys[`${metaKey}-1`] = cm => {replaceLineStart('##');};
111 extraKeys[`${metaKey}-2`] = cm => {replaceLineStart('###');};
112 extraKeys[`${metaKey}-3`] = cm => {replaceLineStart('####');};
113 extraKeys[`${metaKey}-4`] = cm => {replaceLineStart('#####');};
114 extraKeys[`${metaKey}-5`] = cm => {replaceLineStart('');};
115 extraKeys[`${metaKey}-d`] = cm => {replaceLineStart('');};
116 extraKeys[`${metaKey}-6`] = cm => {replaceLineStart('>');};
117 extraKeys[`${metaKey}-q`] = cm => {replaceLineStart('>');};
118 extraKeys[`${metaKey}-7`] = cm => {wrapSelection('\n```\n', '\n```');};
119 extraKeys[`${metaKey}-8`] = cm => {wrapSelection('`', '`');};
120 extraKeys[`Shift-${metaKey}-E`] = cm => {wrapSelection('`', '`');};
121 extraKeys[`${metaKey}-9`] = cm => {wrapSelection('<p class="callout info">', '</p>');};
122 cm.setOption('extraKeys', extraKeys);
124 // Update data on content change
125 cm.on('change', (instance, changeObj) => {
126 this.updateAndRender();
129 // Handle scroll to sync display view
130 cm.on('scroll', instance => {
131 // Thanks to http://liuhao.im/english/2015/11/10/the-sync-scroll-of-markdown-editor-in-javascript.html
132 let scroll = instance.getScrollInfo();
133 let atEnd = scroll.top + scroll.clientHeight === scroll.height;
135 this.onMarkdownScroll(-1);
139 let lineNum = instance.lineAtHeight(scroll.top, 'local');
140 let range = instance.getRange({line: 0, ch: null}, {line: lineNum, ch: null});
141 let parser = new DOMParser();
142 let doc = parser.parseFromString(this.markdown.render(range), 'text/html');
143 let totalLines = doc.documentElement.querySelectorAll('body > *');
144 this.onMarkdownScroll(totalLines.length);
147 // Handle image paste
148 cm.on('paste', (cm, event) => {
149 if (!event.clipboardData || !event.clipboardData.items) return;
150 for (let i = 0; i < event.clipboardData.items.length; i++) {
151 uploadImage(event.clipboardData.items[i].getAsFile());
155 // Handle images on drag-drop
156 cm.on('drop', (cm, event) => {
157 event.stopPropagation();
158 event.preventDefault();
159 let cursorPos = cm.coordsChar({left: event.pageX, top: event.pageY});
160 cm.setCursor(cursorPos);
161 if (!event.dataTransfer || !event.dataTransfer.files) return;
162 for (let i = 0; i < event.dataTransfer.files.length; i++) {
163 uploadImage(event.dataTransfer.files[i]);
167 // Helper to replace editor content
168 function replaceContent(search, replace) {
169 let text = cm.getValue();
170 let cursor = cm.listSelections();
171 cm.setValue(text.replace(search, replace));
172 cm.setSelections(cursor);
175 // Helper to replace the start of the line
176 function replaceLineStart(newStart) {
177 let cursor = cm.getCursor();
178 let lineContent = cm.getLine(cursor.line);
179 let lineLen = lineContent.length;
180 let lineStart = lineContent.split(' ')[0];
182 // Remove symbol if already set
183 if (lineStart === newStart) {
184 lineContent = lineContent.replace(`${newStart} `, '');
185 cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
186 cm.setCursor({line: cursor.line, ch: cursor.ch - (newStart.length + 1)});
190 let alreadySymbol = /^[#>`]/.test(lineStart);
193 posDif = newStart.length - lineStart.length;
194 lineContent = lineContent.replace(lineStart, newStart).trim();
195 } else if (newStart !== '') {
196 posDif = newStart.length + 1;
197 lineContent = newStart + ' ' + lineContent;
199 cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
200 cm.setCursor({line: cursor.line, ch: cursor.ch + posDif});
203 function wrapLine(start, end) {
204 let cursor = cm.getCursor();
205 let lineContent = cm.getLine(cursor.line);
206 let lineLen = lineContent.length;
207 let newLineContent = lineContent;
209 if (lineContent.indexOf(start) === 0 && lineContent.slice(-end.length) === end) {
210 newLineContent = lineContent.slice(start.length, lineContent.length - end.length);
212 newLineContent = `${start}${lineContent}${end}`;
215 cm.replaceRange(newLineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
216 cm.setCursor({line: cursor.line, ch: cursor.ch + start.length});
219 function wrapSelection(start, end) {
220 let selection = cm.getSelection();
221 if (selection === '') return wrapLine(start, end);
223 let newSelection = selection;
227 if (selection.indexOf(start) === 0 && selection.slice(-end.length) === end) {
228 newSelection = selection.slice(start.length, selection.length - end.length);
229 endDiff = -(end.length + start.length);
231 newSelection = `${start}${selection}${end}`;
232 endDiff = start.length + end.length;
235 let selections = cm.listSelections()[0];
236 cm.replaceSelection(newSelection);
237 let headFirst = selections.head.ch <= selections.anchor.ch;
238 selections.head.ch += headFirst ? frontDiff : endDiff;
239 selections.anchor.ch += headFirst ? endDiff : frontDiff;
240 cm.setSelections([selections]);
243 // Handle image upload and add image into markdown content
244 function uploadImage(file) {
245 if (file === null || file.type.indexOf('image') !== 0) return;
249 let fileNameMatches = file.name.match(/\.(.+)$/);
250 if (fileNameMatches.length > 1) ext = fileNameMatches[1];
253 // Insert image into markdown
254 let id = "image-" + Math.random().toString(16).slice(2);
255 let placeholderImage = window.baseUrl(`/loading.gif#upload${id}`);
256 let selectedText = cm.getSelection();
257 let placeHolderText = ``;
258 let cursor = cm.getCursor();
259 cm.replaceSelection(placeHolderText);
260 cm.setCursor({line: cursor.line, ch: cursor.ch + selectedText.length + 2});
262 let remoteFilename = "image-" + Date.now() + "." + ext;
263 let formData = new FormData();
264 formData.append('file', file, remoteFilename);
266 window.$http.post('/images/gallery/upload', formData).then(resp => {
267 replaceContent(placeholderImage, resp.data.thumbs.display);
269 window.$events.emit('error', trans('errors.image_upload_error'));
270 replaceContent(placeHolderText, selectedText);
275 function insertLink() {
276 let cursorPos = cm.getCursor('from');
277 let selectedText = cm.getSelection() || '';
278 let newText = `[${selectedText}]()`;
280 cm.replaceSelection(newText);
281 let cursorPosDiff = (selectedText === '') ? -3 : -1;
282 cm.setCursor(cursorPos.line, cursorPos.ch + newText.length+cursorPosDiff);
285 this.updateAndRender();
288 actionInsertImage() {
289 let cursorPos = this.cm.getCursor('from');
290 window.ImageManager.show(image => {
291 let selectedText = this.cm.getSelection();
292 let newText = "";
294 this.cm.replaceSelection(newText);
295 this.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
299 // Show the popup link selector and insert a link when finished
300 actionShowLinkSelector() {
301 let cursorPos = this.cm.getCursor('from');
302 window.EntitySelectorPopup.show(entity => {
303 let selectedText = this.cm.getSelection() || entity.name;
304 let newText = `[${selectedText}](${entity.link})`;
306 this.cm.replaceSelection(newText);
307 this.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
311 // Show draw.io if enabled and handle save.
312 actionStartDrawing() {
313 if (document.querySelector('[drawio-enabled]').getAttribute('drawio-enabled') !== 'true') return;
314 let cursorPos = this.cm.getCursor('from');
317 return Promise.resolve('');
319 // let id = "image-" + Math.random().toString(16).slice(2);
320 // let loadingImage = window.baseUrl('/loading.gif');
323 uploaded_to: Number(document.getElementById('page-editor').getAttribute('page-id'))
326 window.$http.post(window.baseUrl('/images/drawing/upload'), data).then(resp => {
327 let newText = `<div drawio-diagram="${resp.data.id}"><img src="${resp.data.url}"></div>`;
329 this.cm.replaceSelection(newText);
330 this.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
333 window.$events.emit('error', trans('errors.image_upload_error'));
339 // Show draw.io if enabled and handle save.
340 actionEditDrawing(imgContainer) {
341 if (document.querySelector('[drawio-enabled]').getAttribute('drawio-enabled') !== 'true') return;
342 let cursorPos = this.cm.getCursor('from');
343 let drawingId = imgContainer.getAttribute('drawio-diagram');
346 return window.$http.get(window.baseUrl(`/images/base64/${drawingId}`)).then(resp => {
347 return `data:image/png;base64,${resp.data.content}`;
353 uploaded_to: Number(document.getElementById('page-editor').getAttribute('page-id'))
356 window.$http.put(window.baseUrl(`/images/drawing/upload/${drawingId}`), data).then(resp => {
357 let newText = `<div drawio-diagram="${resp.data.id}"><img src="${resp.data.url + `?updated=${Date.now()}`}"></div>`;
358 let newContent = this.cm.getValue().split('\n').map(line => {
359 if (line.indexOf(`drawio-diagram="${drawingId}"`) !== -1) {
364 this.cm.setValue(newContent);
365 this.cm.setCursor(cursorPos);
369 window.$events.emit('error', trans('errors.image_upload_error'));
377 module.exports = MarkdownEditor ;