1 import MarkdownIt from "markdown-it";
2 import mdTasksLists from 'markdown-it-task-lists';
3 import code from '../services/code';
5 import DrawIO from "../services/drawio";
12 const pageEditor = document.getElementById('page-editor');
13 this.pageId = pageEditor.getAttribute('page-id');
14 this.textDirection = pageEditor.getAttribute('text-direction');
16 this.markdown = new MarkdownIt({html: true});
17 this.markdown.use(mdTasksLists, {label: true});
19 this.display = this.elem.querySelector('.markdown-display');
20 this.input = this.elem.querySelector('textarea');
21 this.htmlInput = this.elem.querySelector('input[name=html]');
22 this.cm = code.markdownEditor(this.input);
24 this.onMarkdownScroll = this.onMarkdownScroll.bind(this);
27 // Scroll to text if needed.
28 const queryParams = (new URL(window.location)).searchParams;
29 const scrollText = queryParams.get('content-text');
31 this.scrollToText(scrollText);
39 // Prevent markdown display link click redirect
40 this.display.addEventListener('click', event => {
41 let isDblClick = Date.now() - lastClick < 300;
43 let link = event.target.closest('a');
45 event.preventDefault();
46 window.open(link.getAttribute('href'));
50 let drawing = event.target.closest('[drawio-diagram]');
51 if (drawing !== null && isDblClick) {
52 this.actionEditDrawing(drawing);
56 lastClick = Date.now();
60 this.elem.addEventListener('click', event => {
61 let button = event.target.closest('button[data-action]');
62 if (button === null) return;
64 let action = button.getAttribute('data-action');
65 if (action === 'insertImage') this.actionInsertImage();
66 if (action === 'insertLink') this.actionShowLinkSelector();
67 if (action === 'insertDrawing' && event.ctrlKey) {
68 this.actionShowImageManager();
71 if (action === 'insertDrawing') this.actionStartDrawing();
74 // Mobile section toggling
75 this.elem.addEventListener('click', event => {
76 const toolbarLabel = event.target.closest('.editor-toolbar-label');
77 if (!toolbarLabel) return;
79 const currentActiveSections = this.elem.querySelectorAll('.markdown-editor-wrap');
80 for (let activeElem of currentActiveSections) {
81 activeElem.classList.remove('active');
84 toolbarLabel.closest('.markdown-editor-wrap').classList.add('active');
87 window.$events.listen('editor-markdown-update', value => {
88 this.cm.setValue(value);
89 this.updateAndRender();
92 this.codeMirrorSetup();
95 // Update the input content and render the display.
97 let content = this.cm.getValue();
98 this.input.value = content;
99 let html = this.markdown.render(content);
100 window.$events.emit('editor-html-change', html);
101 window.$events.emit('editor-markdown-change', content);
102 this.display.innerHTML = html;
103 this.htmlInput.value = html;
106 onMarkdownScroll(lineCount) {
107 let elems = this.display.children;
108 if (elems.length <= lineCount) return;
110 let topElem = (lineCount === -1) ? elems[elems.length-1] : elems[lineCount];
111 // TODO - Replace jQuery
112 $(this.display).animate({
113 scrollTop: topElem.offsetTop
114 }, {queue: false, duration: 200, easing: 'linear'});
119 const context = this;
122 // cm.setOption('direction', this.textDirection);
123 cm.setOption('direction', 'ltr'); // Will force to remain as ltr for now due to issues when HTML is in editor.
124 // Custom key commands
125 let metaKey = code.getMetaKey();
126 const extraKeys = {};
127 // Insert Image shortcut
128 extraKeys[`${metaKey}-Alt-I`] = function(cm) {
129 let selectedText = cm.getSelection();
130 let newText = ``;
131 let cursorPos = cm.getCursor('from');
132 cm.replaceSelection(newText);
133 cm.setCursor(cursorPos.line, cursorPos.ch + newText.length -1);
136 extraKeys[`${metaKey}-S`] = cm => {window.$events.emit('editor-save-draft')};
138 extraKeys[`${metaKey}-Enter`] = cm => {window.$events.emit('editor-save-page')};
139 // Show link selector
140 extraKeys[`Shift-${metaKey}-K`] = cm => {this.actionShowLinkSelector()};
142 extraKeys[`${metaKey}-K`] = cm => {insertLink()};
144 extraKeys[`${metaKey}-1`] = cm => {replaceLineStart('##');};
145 extraKeys[`${metaKey}-2`] = cm => {replaceLineStart('###');};
146 extraKeys[`${metaKey}-3`] = cm => {replaceLineStart('####');};
147 extraKeys[`${metaKey}-4`] = cm => {replaceLineStart('#####');};
148 extraKeys[`${metaKey}-5`] = cm => {replaceLineStart('');};
149 extraKeys[`${metaKey}-d`] = cm => {replaceLineStart('');};
150 extraKeys[`${metaKey}-6`] = cm => {replaceLineStart('>');};
151 extraKeys[`${metaKey}-q`] = cm => {replaceLineStart('>');};
152 extraKeys[`${metaKey}-7`] = cm => {wrapSelection('\n```\n', '\n```');};
153 extraKeys[`${metaKey}-8`] = cm => {wrapSelection('`', '`');};
154 extraKeys[`Shift-${metaKey}-E`] = cm => {wrapSelection('`', '`');};
155 extraKeys[`${metaKey}-9`] = cm => {wrapSelection('<p class="callout info">', '</p>');};
156 cm.setOption('extraKeys', extraKeys);
158 // Update data on content change
159 cm.on('change', (instance, changeObj) => {
160 this.updateAndRender();
163 // Handle scroll to sync display view
164 cm.on('scroll', instance => {
165 // Thanks to http://liuhao.im/english/2015/11/10/the-sync-scroll-of-markdown-editor-in-javascript.html
166 let scroll = instance.getScrollInfo();
167 let atEnd = scroll.top + scroll.clientHeight === scroll.height;
169 this.onMarkdownScroll(-1);
173 let lineNum = instance.lineAtHeight(scroll.top, 'local');
174 let range = instance.getRange({line: 0, ch: null}, {line: lineNum, ch: null});
175 let parser = new DOMParser();
176 let doc = parser.parseFromString(this.markdown.render(range), 'text/html');
177 let totalLines = doc.documentElement.querySelectorAll('body > *');
178 this.onMarkdownScroll(totalLines.length);
181 // Handle image paste
182 cm.on('paste', (cm, event) => {
183 if (!event.clipboardData || !event.clipboardData.items) return;
184 for (let i = 0; i < event.clipboardData.items.length; i++) {
185 uploadImage(event.clipboardData.items[i].getAsFile());
189 // Handle images on drag-drop
190 cm.on('drop', (cm, event) => {
191 event.stopPropagation();
192 event.preventDefault();
193 let cursorPos = cm.coordsChar({left: event.pageX, top: event.pageY});
194 cm.setCursor(cursorPos);
195 if (!event.dataTransfer || !event.dataTransfer.files) return;
196 for (let i = 0; i < event.dataTransfer.files.length; i++) {
197 uploadImage(event.dataTransfer.files[i]);
201 // Helper to replace editor content
202 function replaceContent(search, replace) {
203 let text = cm.getValue();
204 let cursor = cm.listSelections();
205 cm.setValue(text.replace(search, replace));
206 cm.setSelections(cursor);
209 // Helper to replace the start of the line
210 function replaceLineStart(newStart) {
211 let cursor = cm.getCursor();
212 let lineContent = cm.getLine(cursor.line);
213 let lineLen = lineContent.length;
214 let lineStart = lineContent.split(' ')[0];
216 // Remove symbol if already set
217 if (lineStart === newStart) {
218 lineContent = lineContent.replace(`${newStart} `, '');
219 cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
220 cm.setCursor({line: cursor.line, ch: cursor.ch - (newStart.length + 1)});
224 let alreadySymbol = /^[#>`]/.test(lineStart);
227 posDif = newStart.length - lineStart.length;
228 lineContent = lineContent.replace(lineStart, newStart).trim();
229 } else if (newStart !== '') {
230 posDif = newStart.length + 1;
231 lineContent = newStart + ' ' + lineContent;
233 cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
234 cm.setCursor({line: cursor.line, ch: cursor.ch + posDif});
237 function wrapLine(start, end) {
238 let cursor = cm.getCursor();
239 let lineContent = cm.getLine(cursor.line);
240 let lineLen = lineContent.length;
241 let newLineContent = lineContent;
243 if (lineContent.indexOf(start) === 0 && lineContent.slice(-end.length) === end) {
244 newLineContent = lineContent.slice(start.length, lineContent.length - end.length);
246 newLineContent = `${start}${lineContent}${end}`;
249 cm.replaceRange(newLineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
250 cm.setCursor({line: cursor.line, ch: cursor.ch + start.length});
253 function wrapSelection(start, end) {
254 let selection = cm.getSelection();
255 if (selection === '') return wrapLine(start, end);
257 let newSelection = selection;
261 if (selection.indexOf(start) === 0 && selection.slice(-end.length) === end) {
262 newSelection = selection.slice(start.length, selection.length - end.length);
263 endDiff = -(end.length + start.length);
265 newSelection = `${start}${selection}${end}`;
266 endDiff = start.length + end.length;
269 let selections = cm.listSelections()[0];
270 cm.replaceSelection(newSelection);
271 let headFirst = selections.head.ch <= selections.anchor.ch;
272 selections.head.ch += headFirst ? frontDiff : endDiff;
273 selections.anchor.ch += headFirst ? endDiff : frontDiff;
274 cm.setSelections([selections]);
277 // Handle image upload and add image into markdown content
278 function uploadImage(file) {
279 if (file === null || file.type.indexOf('image') !== 0) return;
283 let fileNameMatches = file.name.match(/\.(.+)$/);
284 if (fileNameMatches.length > 1) ext = fileNameMatches[1];
287 // Insert image into markdown
288 const id = "image-" + Math.random().toString(16).slice(2);
289 const placeholderImage = window.baseUrl(`/loading.gif#upload${id}`);
290 const selectedText = cm.getSelection();
291 const placeHolderText = ``;
292 const cursor = cm.getCursor();
293 cm.replaceSelection(placeHolderText);
294 cm.setCursor({line: cursor.line, ch: cursor.ch + selectedText.length + 3});
296 const remoteFilename = "image-" + Date.now() + "." + ext;
297 const formData = new FormData();
298 formData.append('file', file, remoteFilename);
299 formData.append('uploaded_to', context.pageId);
301 window.$http.post('/images/gallery/upload', formData).then(resp => {
302 const newContent = `[](${resp.data.url})`;
303 replaceContent(placeHolderText, newContent);
305 window.$events.emit('error', trans('errors.image_upload_error'));
306 replaceContent(placeHolderText, selectedText);
311 function insertLink() {
312 let cursorPos = cm.getCursor('from');
313 let selectedText = cm.getSelection() || '';
314 let newText = `[${selectedText}]()`;
316 cm.replaceSelection(newText);
317 let cursorPosDiff = (selectedText === '') ? -3 : -1;
318 cm.setCursor(cursorPos.line, cursorPos.ch + newText.length+cursorPosDiff);
321 this.updateAndRender();
324 actionInsertImage() {
325 const cursorPos = this.cm.getCursor('from');
326 window.ImageManager.show(image => {
327 let selectedText = this.cm.getSelection();
328 let newText = "[](" + image.url + ")";
330 this.cm.replaceSelection(newText);
331 this.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
335 actionShowImageManager() {
336 const cursorPos = this.cm.getCursor('from');
337 window.ImageManager.show(image => {
338 this.insertDrawing(image, cursorPos);
342 // Show the popup link selector and insert a link when finished
343 actionShowLinkSelector() {
344 const cursorPos = this.cm.getCursor('from');
345 window.EntitySelectorPopup.show(entity => {
346 let selectedText = this.cm.getSelection() || entity.name;
347 let newText = `[${selectedText}](${entity.link})`;
349 this.cm.replaceSelection(newText);
350 this.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
354 // Show draw.io if enabled and handle save.
355 actionStartDrawing() {
356 if (document.querySelector('[drawio-enabled]').getAttribute('drawio-enabled') !== 'true') return;
357 let cursorPos = this.cm.getCursor('from');
360 return Promise.resolve('');
362 // let id = "image-" + Math.random().toString(16).slice(2);
363 // let loadingImage = window.baseUrl('/loading.gif');
366 uploaded_to: Number(document.getElementById('page-editor').getAttribute('page-id'))
369 window.$http.post(window.baseUrl('/images/drawing/upload'), data).then(resp => {
370 this.insertDrawing(resp.data, cursorPos);
373 window.$events.emit('error', trans('errors.image_upload_error'));
379 insertDrawing(image, originalCursor) {
380 const newText = `<div drawio-diagram="${image.id}"><img src="${image.url}"></div>`;
382 this.cm.replaceSelection(newText);
383 this.cm.setCursor(originalCursor.line, originalCursor.ch + newText.length);
386 // Show draw.io if enabled and handle save.
387 actionEditDrawing(imgContainer) {
388 const drawingDisabled = document.querySelector('[drawio-enabled]').getAttribute('drawio-enabled') !== 'true';
389 if (drawingDisabled) {
393 const cursorPos = this.cm.getCursor('from');
394 const drawingId = imgContainer.getAttribute('drawio-diagram');
397 return window.$http.get(window.baseUrl(`/images/base64/${drawingId}`)).then(resp => {
398 return `data:image/png;base64,${resp.data.content}`;
404 uploaded_to: Number(document.getElementById('page-editor').getAttribute('page-id'))
407 window.$http.post(window.baseUrl(`/images/drawing/upload`), data).then(resp => {
408 let newText = `<div drawio-diagram="${resp.data.id}"><img src="${resp.data.url}"></div>`;
409 let newContent = this.cm.getValue().split('\n').map(line => {
410 if (line.indexOf(`drawio-diagram="${drawingId}"`) !== -1) {
415 this.cm.setValue(newContent);
416 this.cm.setCursor(cursorPos);
420 window.$events.emit('error', trans('errors.image_upload_error'));
426 // Scroll to a specified text
427 scrollToText(searchText) {
432 const content = this.cm.getValue();
433 const lines = content.split(/\r?\n/);
434 let lineNumber = lines.findIndex(line => {
435 return line && line.indexOf(searchText) !== -1;
438 if (lineNumber === -1) {
442 this.cm.scrollIntoView({
446 // set the cursor location.
449 char: lines[lineNumber].length
455 export default MarkdownEditor ;