1 import MarkdownIt from "markdown-it";
2 import mdTasksLists from 'markdown-it-task-lists';
3 import code from '../services/code';
4 import {debounce} from "../services/util";
6 import DrawIO from "../services/drawio";
13 const pageEditor = document.getElementById('page-editor');
14 this.pageId = pageEditor.getAttribute('page-id');
15 this.textDirection = pageEditor.getAttribute('text-direction');
17 this.markdown = new MarkdownIt({html: true});
18 this.markdown.use(mdTasksLists, {label: true});
20 this.display = this.elem.querySelector('.markdown-display');
21 this.input = this.elem.querySelector('textarea');
22 this.htmlInput = this.elem.querySelector('input[name=html]');
23 this.cm = code.markdownEditor(this.input);
25 this.onMarkdownScroll = this.onMarkdownScroll.bind(this);
28 // Scroll to text if needed.
29 const queryParams = (new URL(window.location)).searchParams;
30 const scrollText = queryParams.get('content-text');
32 this.scrollToText(scrollText);
40 // Prevent markdown display link click redirect
41 this.display.addEventListener('click', event => {
42 let isDblClick = Date.now() - lastClick < 300;
44 let link = event.target.closest('a');
46 event.preventDefault();
47 window.open(link.getAttribute('href'));
51 let drawing = event.target.closest('[drawio-diagram]');
52 if (drawing !== null && isDblClick) {
53 this.actionEditDrawing(drawing);
57 lastClick = Date.now();
61 this.elem.addEventListener('click', event => {
62 let button = event.target.closest('button[data-action]');
63 if (button === null) return;
65 let action = button.getAttribute('data-action');
66 if (action === 'insertImage') this.actionInsertImage();
67 if (action === 'insertLink') this.actionShowLinkSelector();
68 if (action === 'insertDrawing' && (event.ctrlKey || event.metaKey)) {
69 this.actionShowImageManager();
72 if (action === 'insertDrawing') this.actionStartDrawing();
75 // Mobile section toggling
76 this.elem.addEventListener('click', event => {
77 const toolbarLabel = event.target.closest('.editor-toolbar-label');
78 if (!toolbarLabel) return;
80 const currentActiveSections = this.elem.querySelectorAll('.markdown-editor-wrap');
81 for (let activeElem of currentActiveSections) {
82 activeElem.classList.remove('active');
85 toolbarLabel.closest('.markdown-editor-wrap').classList.add('active');
88 window.$events.listen('editor-markdown-update', value => {
89 this.cm.setValue(value);
90 this.updateAndRender();
93 this.codeMirrorSetup();
96 // Update the input content and render the display.
98 let content = this.cm.getValue();
99 this.input.value = content;
100 let html = this.markdown.render(content);
101 window.$events.emit('editor-html-change', html);
102 window.$events.emit('editor-markdown-change', content);
103 this.display.innerHTML = html;
104 this.htmlInput.value = html;
107 onMarkdownScroll(lineCount) {
108 const elems = this.display.children;
109 if (elems.length <= lineCount) return;
111 const topElem = (lineCount === -1) ? elems[elems.length-1] : elems[lineCount];
112 topElem.scrollIntoView({ block: 'start', inline: 'nearest', behavior: 'smooth'});
117 const context = this;
120 // cm.setOption('direction', this.textDirection);
121 cm.setOption('direction', 'ltr'); // Will force to remain as ltr for now due to issues when HTML is in editor.
122 // Custom key commands
123 let metaKey = code.getMetaKey();
124 const extraKeys = {};
125 // Insert Image shortcut
126 extraKeys[`${metaKey}-Alt-I`] = function(cm) {
127 let selectedText = cm.getSelection();
128 let newText = ``;
129 let cursorPos = cm.getCursor('from');
130 cm.replaceSelection(newText);
131 cm.setCursor(cursorPos.line, cursorPos.ch + newText.length -1);
134 extraKeys[`${metaKey}-S`] = cm => {window.$events.emit('editor-save-draft')};
136 extraKeys[`${metaKey}-Enter`] = cm => {window.$events.emit('editor-save-page')};
137 // Show link selector
138 extraKeys[`Shift-${metaKey}-K`] = cm => {this.actionShowLinkSelector()};
140 extraKeys[`${metaKey}-K`] = cm => {insertLink()};
142 extraKeys[`${metaKey}-1`] = cm => {replaceLineStart('##');};
143 extraKeys[`${metaKey}-2`] = cm => {replaceLineStart('###');};
144 extraKeys[`${metaKey}-3`] = cm => {replaceLineStart('####');};
145 extraKeys[`${metaKey}-4`] = cm => {replaceLineStart('#####');};
146 extraKeys[`${metaKey}-5`] = cm => {replaceLineStart('');};
147 extraKeys[`${metaKey}-d`] = cm => {replaceLineStart('');};
148 extraKeys[`${metaKey}-6`] = cm => {replaceLineStart('>');};
149 extraKeys[`${metaKey}-q`] = cm => {replaceLineStart('>');};
150 extraKeys[`${metaKey}-7`] = cm => {wrapSelection('\n```\n', '\n```');};
151 extraKeys[`${metaKey}-8`] = cm => {wrapSelection('`', '`');};
152 extraKeys[`Shift-${metaKey}-E`] = cm => {wrapSelection('`', '`');};
153 extraKeys[`${metaKey}-9`] = cm => {wrapSelection('<p class="callout info">', '</p>');};
154 cm.setOption('extraKeys', extraKeys);
156 // Update data on content change
157 cm.on('change', (instance, changeObj) => {
158 this.updateAndRender();
161 const onScrollDebounced = debounce((instance) => {
162 // Thanks to http://liuhao.im/english/2015/11/10/the-sync-scroll-of-markdown-editor-in-javascript.html
163 let scroll = instance.getScrollInfo();
164 let atEnd = scroll.top + scroll.clientHeight === scroll.height;
166 this.onMarkdownScroll(-1);
170 let lineNum = instance.lineAtHeight(scroll.top, 'local');
171 let range = instance.getRange({line: 0, ch: null}, {line: lineNum, ch: null});
172 let parser = new DOMParser();
173 let doc = parser.parseFromString(this.markdown.render(range), 'text/html');
174 let totalLines = doc.documentElement.querySelectorAll('body > *');
175 this.onMarkdownScroll(totalLines.length);
178 // Handle scroll to sync display view
179 cm.on('scroll', instance => {
180 onScrollDebounced(instance);
183 // Handle image paste
184 cm.on('paste', (cm, event) => {
185 const clipboardItems = event.clipboardData.items;
186 if (!event.clipboardData || !clipboardItems) return;
188 // Don't handle if clipboard includes text content
189 for (let clipboardItem of clipboardItems) {
190 if (clipboardItem.type.includes('text/')) {
195 for (let clipboardItem of clipboardItems) {
196 if (clipboardItem.type.includes("image")) {
197 uploadImage(clipboardItem.getAsFile());
202 // Handle images on drag-drop
203 cm.on('drop', (cm, event) => {
204 event.stopPropagation();
205 event.preventDefault();
206 let cursorPos = cm.coordsChar({left: event.pageX, top: event.pageY});
207 cm.setCursor(cursorPos);
208 if (!event.dataTransfer || !event.dataTransfer.files) return;
209 for (let i = 0; i < event.dataTransfer.files.length; i++) {
210 uploadImage(event.dataTransfer.files[i]);
214 // Helper to replace editor content
215 function replaceContent(search, replace) {
216 let text = cm.getValue();
217 let cursor = cm.listSelections();
218 cm.setValue(text.replace(search, replace));
219 cm.setSelections(cursor);
222 // Helper to replace the start of the line
223 function replaceLineStart(newStart) {
224 let cursor = cm.getCursor();
225 let lineContent = cm.getLine(cursor.line);
226 let lineLen = lineContent.length;
227 let lineStart = lineContent.split(' ')[0];
229 // Remove symbol if already set
230 if (lineStart === newStart) {
231 lineContent = lineContent.replace(`${newStart} `, '');
232 cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
233 cm.setCursor({line: cursor.line, ch: cursor.ch - (newStart.length + 1)});
237 let alreadySymbol = /^[#>`]/.test(lineStart);
240 posDif = newStart.length - lineStart.length;
241 lineContent = lineContent.replace(lineStart, newStart).trim();
242 } else if (newStart !== '') {
243 posDif = newStart.length + 1;
244 lineContent = newStart + ' ' + lineContent;
246 cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
247 cm.setCursor({line: cursor.line, ch: cursor.ch + posDif});
250 function wrapLine(start, end) {
251 let cursor = cm.getCursor();
252 let lineContent = cm.getLine(cursor.line);
253 let lineLen = lineContent.length;
254 let newLineContent = lineContent;
256 if (lineContent.indexOf(start) === 0 && lineContent.slice(-end.length) === end) {
257 newLineContent = lineContent.slice(start.length, lineContent.length - end.length);
259 newLineContent = `${start}${lineContent}${end}`;
262 cm.replaceRange(newLineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
263 cm.setCursor({line: cursor.line, ch: cursor.ch + start.length});
266 function wrapSelection(start, end) {
267 let selection = cm.getSelection();
268 if (selection === '') return wrapLine(start, end);
270 let newSelection = selection;
274 if (selection.indexOf(start) === 0 && selection.slice(-end.length) === end) {
275 newSelection = selection.slice(start.length, selection.length - end.length);
276 endDiff = -(end.length + start.length);
278 newSelection = `${start}${selection}${end}`;
279 endDiff = start.length + end.length;
282 let selections = cm.listSelections()[0];
283 cm.replaceSelection(newSelection);
284 let headFirst = selections.head.ch <= selections.anchor.ch;
285 selections.head.ch += headFirst ? frontDiff : endDiff;
286 selections.anchor.ch += headFirst ? endDiff : frontDiff;
287 cm.setSelections([selections]);
290 // Handle image upload and add image into markdown content
291 function uploadImage(file) {
292 if (file === null || file.type.indexOf('image') !== 0) return;
296 let fileNameMatches = file.name.match(/\.(.+)$/);
297 if (fileNameMatches.length > 1) ext = fileNameMatches[1];
300 // Insert image into markdown
301 const id = "image-" + Math.random().toString(16).slice(2);
302 const placeholderImage = window.baseUrl(`/loading.gif#upload${id}`);
303 const selectedText = cm.getSelection();
304 const placeHolderText = ``;
305 const cursor = cm.getCursor();
306 cm.replaceSelection(placeHolderText);
307 cm.setCursor({line: cursor.line, ch: cursor.ch + selectedText.length + 3});
309 const remoteFilename = "image-" + Date.now() + "." + ext;
310 const formData = new FormData();
311 formData.append('file', file, remoteFilename);
312 formData.append('uploaded_to', context.pageId);
314 window.$http.post('/images/gallery', formData).then(resp => {
315 const newContent = `[](${resp.data.url})`;
316 replaceContent(placeHolderText, newContent);
318 window.$events.emit('error', trans('errors.image_upload_error'));
319 replaceContent(placeHolderText, selectedText);
324 function insertLink() {
325 let cursorPos = cm.getCursor('from');
326 let selectedText = cm.getSelection() || '';
327 let newText = `[${selectedText}]()`;
329 cm.replaceSelection(newText);
330 let cursorPosDiff = (selectedText === '') ? -3 : -1;
331 cm.setCursor(cursorPos.line, cursorPos.ch + newText.length+cursorPosDiff);
334 this.updateAndRender();
337 actionInsertImage() {
338 const cursorPos = this.cm.getCursor('from');
339 window.ImageManager.show(image => {
340 let selectedText = this.cm.getSelection();
341 let newText = "[](" + image.url + ")";
343 this.cm.replaceSelection(newText);
344 this.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
348 actionShowImageManager() {
349 const cursorPos = this.cm.getCursor('from');
350 window.ImageManager.show(image => {
351 this.insertDrawing(image, cursorPos);
355 // Show the popup link selector and insert a link when finished
356 actionShowLinkSelector() {
357 const cursorPos = this.cm.getCursor('from');
358 window.EntitySelectorPopup.show(entity => {
359 let selectedText = this.cm.getSelection() || entity.name;
360 let newText = `[${selectedText}](${entity.link})`;
362 this.cm.replaceSelection(newText);
363 this.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
367 // Show draw.io if enabled and handle save.
368 actionStartDrawing() {
369 if (document.querySelector('[drawio-enabled]').getAttribute('drawio-enabled') !== 'true') return;
370 let cursorPos = this.cm.getCursor('from');
373 return Promise.resolve('');
375 // let id = "image-" + Math.random().toString(16).slice(2);
376 // let loadingImage = window.baseUrl('/loading.gif');
379 uploaded_to: Number(document.getElementById('page-editor').getAttribute('page-id'))
382 window.$http.post(window.baseUrl('/images/drawio'), data).then(resp => {
383 this.insertDrawing(resp.data, cursorPos);
386 window.$events.emit('error', trans('errors.image_upload_error'));
392 insertDrawing(image, originalCursor) {
393 const newText = `<div drawio-diagram="${image.id}"><img src="${image.url}"></div>`;
395 this.cm.replaceSelection(newText);
396 this.cm.setCursor(originalCursor.line, originalCursor.ch + newText.length);
399 // Show draw.io if enabled and handle save.
400 actionEditDrawing(imgContainer) {
401 const drawingDisabled = document.querySelector('[drawio-enabled]').getAttribute('drawio-enabled') !== 'true';
402 if (drawingDisabled) {
406 const cursorPos = this.cm.getCursor('from');
407 const drawingId = imgContainer.getAttribute('drawio-diagram');
410 return DrawIO.load(drawingId);
415 uploaded_to: Number(document.getElementById('page-editor').getAttribute('page-id'))
418 window.$http.post(window.baseUrl(`/images/drawio`), data).then(resp => {
419 let newText = `<div drawio-diagram="${resp.data.id}"><img src="${resp.data.url}"></div>`;
420 let newContent = this.cm.getValue().split('\n').map(line => {
421 if (line.indexOf(`drawio-diagram="${drawingId}"`) !== -1) {
426 this.cm.setValue(newContent);
427 this.cm.setCursor(cursorPos);
431 window.$events.emit('error', trans('errors.image_upload_error'));
437 // Scroll to a specified text
438 scrollToText(searchText) {
443 const content = this.cm.getValue();
444 const lines = content.split(/\r?\n/);
445 let lineNumber = lines.findIndex(line => {
446 return line && line.indexOf(searchText) !== -1;
449 if (lineNumber === -1) {
453 this.cm.scrollIntoView({
457 // set the cursor location.
460 char: lines[lineNumber].length
466 export default MarkdownEditor ;