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 || event.metaKey)) {
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 const clipboardItems = event.clipboardData.items;
184 if (!event.clipboardData || !clipboardItems) return;
186 // Don't handle if clipboard includes text content
187 for (let clipboardItem of clipboardItems) {
188 if (clipboardItem.type.includes('text/')) {
193 for (let clipboardItem of clipboardItems) {
194 if (clipboardItem.type.includes("image")) {
195 uploadImage(clipboardItem.getAsFile());
200 // Handle images on drag-drop
201 cm.on('drop', (cm, event) => {
202 event.stopPropagation();
203 event.preventDefault();
204 let cursorPos = cm.coordsChar({left: event.pageX, top: event.pageY});
205 cm.setCursor(cursorPos);
206 if (!event.dataTransfer || !event.dataTransfer.files) return;
207 for (let i = 0; i < event.dataTransfer.files.length; i++) {
208 uploadImage(event.dataTransfer.files[i]);
212 // Helper to replace editor content
213 function replaceContent(search, replace) {
214 let text = cm.getValue();
215 let cursor = cm.listSelections();
216 cm.setValue(text.replace(search, replace));
217 cm.setSelections(cursor);
220 // Helper to replace the start of the line
221 function replaceLineStart(newStart) {
222 let cursor = cm.getCursor();
223 let lineContent = cm.getLine(cursor.line);
224 let lineLen = lineContent.length;
225 let lineStart = lineContent.split(' ')[0];
227 // Remove symbol if already set
228 if (lineStart === newStart) {
229 lineContent = lineContent.replace(`${newStart} `, '');
230 cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
231 cm.setCursor({line: cursor.line, ch: cursor.ch - (newStart.length + 1)});
235 let alreadySymbol = /^[#>`]/.test(lineStart);
238 posDif = newStart.length - lineStart.length;
239 lineContent = lineContent.replace(lineStart, newStart).trim();
240 } else if (newStart !== '') {
241 posDif = newStart.length + 1;
242 lineContent = newStart + ' ' + lineContent;
244 cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
245 cm.setCursor({line: cursor.line, ch: cursor.ch + posDif});
248 function wrapLine(start, end) {
249 let cursor = cm.getCursor();
250 let lineContent = cm.getLine(cursor.line);
251 let lineLen = lineContent.length;
252 let newLineContent = lineContent;
254 if (lineContent.indexOf(start) === 0 && lineContent.slice(-end.length) === end) {
255 newLineContent = lineContent.slice(start.length, lineContent.length - end.length);
257 newLineContent = `${start}${lineContent}${end}`;
260 cm.replaceRange(newLineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
261 cm.setCursor({line: cursor.line, ch: cursor.ch + start.length});
264 function wrapSelection(start, end) {
265 let selection = cm.getSelection();
266 if (selection === '') return wrapLine(start, end);
268 let newSelection = selection;
272 if (selection.indexOf(start) === 0 && selection.slice(-end.length) === end) {
273 newSelection = selection.slice(start.length, selection.length - end.length);
274 endDiff = -(end.length + start.length);
276 newSelection = `${start}${selection}${end}`;
277 endDiff = start.length + end.length;
280 let selections = cm.listSelections()[0];
281 cm.replaceSelection(newSelection);
282 let headFirst = selections.head.ch <= selections.anchor.ch;
283 selections.head.ch += headFirst ? frontDiff : endDiff;
284 selections.anchor.ch += headFirst ? endDiff : frontDiff;
285 cm.setSelections([selections]);
288 // Handle image upload and add image into markdown content
289 function uploadImage(file) {
290 if (file === null || file.type.indexOf('image') !== 0) return;
294 let fileNameMatches = file.name.match(/\.(.+)$/);
295 if (fileNameMatches.length > 1) ext = fileNameMatches[1];
298 // Insert image into markdown
299 const id = "image-" + Math.random().toString(16).slice(2);
300 const placeholderImage = window.baseUrl(`/loading.gif#upload${id}`);
301 const selectedText = cm.getSelection();
302 const placeHolderText = ``;
303 const cursor = cm.getCursor();
304 cm.replaceSelection(placeHolderText);
305 cm.setCursor({line: cursor.line, ch: cursor.ch + selectedText.length + 3});
307 const remoteFilename = "image-" + Date.now() + "." + ext;
308 const formData = new FormData();
309 formData.append('file', file, remoteFilename);
310 formData.append('uploaded_to', context.pageId);
312 window.$http.post('/images/gallery', formData).then(resp => {
313 const newContent = `[](${resp.data.url})`;
314 replaceContent(placeHolderText, newContent);
316 window.$events.emit('error', trans('errors.image_upload_error'));
317 replaceContent(placeHolderText, selectedText);
322 function insertLink() {
323 let cursorPos = cm.getCursor('from');
324 let selectedText = cm.getSelection() || '';
325 let newText = `[${selectedText}]()`;
327 cm.replaceSelection(newText);
328 let cursorPosDiff = (selectedText === '') ? -3 : -1;
329 cm.setCursor(cursorPos.line, cursorPos.ch + newText.length+cursorPosDiff);
332 this.updateAndRender();
335 actionInsertImage() {
336 const cursorPos = this.cm.getCursor('from');
337 window.ImageManager.show(image => {
338 let selectedText = this.cm.getSelection();
339 let newText = "[](" + image.url + ")";
341 this.cm.replaceSelection(newText);
342 this.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
346 actionShowImageManager() {
347 const cursorPos = this.cm.getCursor('from');
348 window.ImageManager.show(image => {
349 this.insertDrawing(image, cursorPos);
353 // Show the popup link selector and insert a link when finished
354 actionShowLinkSelector() {
355 const cursorPos = this.cm.getCursor('from');
356 window.EntitySelectorPopup.show(entity => {
357 let selectedText = this.cm.getSelection() || entity.name;
358 let newText = `[${selectedText}](${entity.link})`;
360 this.cm.replaceSelection(newText);
361 this.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
365 // Show draw.io if enabled and handle save.
366 actionStartDrawing() {
367 if (document.querySelector('[drawio-enabled]').getAttribute('drawio-enabled') !== 'true') return;
368 let cursorPos = this.cm.getCursor('from');
371 return Promise.resolve('');
373 // let id = "image-" + Math.random().toString(16).slice(2);
374 // let loadingImage = window.baseUrl('/loading.gif');
377 uploaded_to: Number(document.getElementById('page-editor').getAttribute('page-id'))
380 window.$http.post(window.baseUrl('/images/drawio'), data).then(resp => {
381 this.insertDrawing(resp.data, cursorPos);
384 window.$events.emit('error', trans('errors.image_upload_error'));
390 insertDrawing(image, originalCursor) {
391 const newText = `<div drawio-diagram="${image.id}"><img src="${image.url}"></div>`;
393 this.cm.replaceSelection(newText);
394 this.cm.setCursor(originalCursor.line, originalCursor.ch + newText.length);
397 // Show draw.io if enabled and handle save.
398 actionEditDrawing(imgContainer) {
399 const drawingDisabled = document.querySelector('[drawio-enabled]').getAttribute('drawio-enabled') !== 'true';
400 if (drawingDisabled) {
404 const cursorPos = this.cm.getCursor('from');
405 const drawingId = imgContainer.getAttribute('drawio-diagram');
408 return DrawIO.load(drawingId);
413 uploaded_to: Number(document.getElementById('page-editor').getAttribute('page-id'))
416 window.$http.post(window.baseUrl(`/images/drawio`), data).then(resp => {
417 let newText = `<div drawio-diagram="${resp.data.id}"><img src="${resp.data.url}"></div>`;
418 let newContent = this.cm.getValue().split('\n').map(line => {
419 if (line.indexOf(`drawio-diagram="${drawingId}"`) !== -1) {
424 this.cm.setValue(newContent);
425 this.cm.setCursor(cursorPos);
429 window.$events.emit('error', trans('errors.image_upload_error'));
435 // Scroll to a specified text
436 scrollToText(searchText) {
441 const content = this.cm.getValue();
442 const lines = content.split(/\r?\n/);
443 let lineNumber = lines.findIndex(line => {
444 return line && line.indexOf(searchText) !== -1;
447 if (lineNumber === -1) {
451 this.cm.scrollIntoView({
455 // set the cursor location.
458 char: lines[lineNumber].length
464 export default MarkdownEditor ;