1 const MarkdownIt = require("markdown-it");
2 const mdTasksLists = require('markdown-it-task-lists');
3 const code = require('../libs/code');
5 const DrawIO = require('../libs/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 cm.replaceSelection(placeHolderText);
260 let remoteFilename = "image-" + Date.now() + "." + ext;
261 let formData = new FormData();
262 formData.append('file', file, remoteFilename);
264 window.$http.post('/images/gallery/upload', formData).then(resp => {
265 replaceContent(placeholderImage, resp.data.thumbs.display);
267 events.emit('error', trans('errors.image_upload_error'));
268 replaceContent(placeHolderText, selectedText);
273 function insertLink() {
274 let cursorPos = cm.getCursor('from');
275 let selectedText = cm.getSelection() || '';
276 let newText = `[${selectedText}]()`;
278 cm.replaceSelection(newText);
279 let cursorPosDiff = (selectedText === '') ? -3 : -1;
280 cm.setCursor(cursorPos.line, cursorPos.ch + newText.length+cursorPosDiff);
283 this.updateAndRender();
286 actionInsertImage() {
287 let cursorPos = this.cm.getCursor('from');
288 window.ImageManager.show(image => {
289 let selectedText = this.cm.getSelection();
290 let newText = "";
292 this.cm.replaceSelection(newText);
293 this.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
297 // Show the popup link selector and insert a link when finished
298 actionShowLinkSelector() {
299 let cursorPos = this.cm.getCursor('from');
300 window.EntitySelectorPopup.show(entity => {
301 let selectedText = this.cm.getSelection() || entity.name;
302 let newText = `[${selectedText}](${entity.link})`;
304 this.cm.replaceSelection(newText);
305 this.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
309 // Show draw.io if enabled and handle save.
310 actionStartDrawing() {
311 if (document.querySelector('[drawio-enabled]').getAttribute('drawio-enabled') !== 'true') return;
312 let cursorPos = this.cm.getCursor('from');
315 return Promise.resolve('');
317 // let id = "image-" + Math.random().toString(16).slice(2);
318 // let loadingImage = window.baseUrl('/loading.gif');
321 uploaded_to: Number(document.getElementById('page-editor').getAttribute('page-id'))
324 window.$http.post(window.baseUrl('/images/drawing/upload'), data).then(resp => {
325 let newText = `<div drawio-diagram="${resp.data.id}"><img src="${resp.data.url}"></div>`;
327 this.cm.replaceSelection(newText);
328 this.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
331 window.$events.emit('error', trans('errors.image_upload_error'));
337 // Show draw.io if enabled and handle save.
338 actionEditDrawing(imgContainer) {
339 if (document.querySelector('[drawio-enabled]').getAttribute('drawio-enabled') !== 'true') return;
340 let cursorPos = this.cm.getCursor('from');
341 let drawingId = imgContainer.getAttribute('drawio-diagram');
344 return window.$http.get(window.baseUrl(`/images/base64/${drawingId}`)).then(resp => {
345 return `data:image/png;base64,${resp.data.content}`;
351 uploaded_to: Number(document.getElementById('page-editor').getAttribute('page-id'))
354 window.$http.put(window.baseUrl(`/images/drawing/upload/${drawingId}`), data).then(resp => {
355 let newText = `<div drawio-diagram="${resp.data.id}"><img src="${resp.data.url + `?updated=${Date.now()}`}"></div>`;
356 let newContent = this.cm.getValue().split('\n').map(line => {
357 if (line.indexOf(`drawio-diagram="${drawingId}"`) !== -1) {
362 this.cm.setValue(newContent);
363 this.cm.setCursor(cursorPos);
367 window.$events.emit('error', trans('errors.image_upload_error'));
375 module.exports = MarkdownEditor ;