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";
11 this.textDirection = document.getElementById('page-editor').getAttribute('text-direction');
12 this.markdown = new MarkdownIt({html: true});
13 this.markdown.use(mdTasksLists, {label: true});
15 this.display = this.elem.querySelector('.markdown-display');
16 this.input = this.elem.querySelector('textarea');
17 this.htmlInput = this.elem.querySelector('input[name=html]');
18 this.cm = code.markdownEditor(this.input);
20 this.onMarkdownScroll = this.onMarkdownScroll.bind(this);
23 // Scroll to text if needed.
24 const queryParams = (new URL(window.location)).searchParams;
25 const scrollText = queryParams.get('content-text');
27 this.scrollToText(scrollText);
35 // Prevent markdown display link click redirect
36 this.display.addEventListener('click', event => {
37 let isDblClick = Date.now() - lastClick < 300;
39 let link = event.target.closest('a');
41 event.preventDefault();
42 window.open(link.getAttribute('href'));
46 let drawing = event.target.closest('[drawio-diagram]');
47 if (drawing !== null && isDblClick) {
48 this.actionEditDrawing(drawing);
52 lastClick = Date.now();
56 this.elem.addEventListener('click', event => {
57 let button = event.target.closest('button[data-action]');
58 if (button === null) return;
60 let action = button.getAttribute('data-action');
61 if (action === 'insertImage') this.actionInsertImage();
62 if (action === 'insertLink') this.actionShowLinkSelector();
63 if (action === 'insertDrawing' && event.ctrlKey) {
64 this.actionShowImageManager();
67 if (action === 'insertDrawing') this.actionStartDrawing();
70 window.$events.listen('editor-markdown-update', value => {
71 this.cm.setValue(value);
72 this.updateAndRender();
75 this.codeMirrorSetup();
78 // Update the input content and render the display.
80 let content = this.cm.getValue();
81 this.input.value = content;
82 let html = this.markdown.render(content);
83 window.$events.emit('editor-html-change', html);
84 window.$events.emit('editor-markdown-change', content);
85 this.display.innerHTML = html;
86 this.htmlInput.value = html;
89 onMarkdownScroll(lineCount) {
90 let elems = this.display.children;
91 if (elems.length <= lineCount) return;
93 let topElem = (lineCount === -1) ? elems[elems.length-1] : elems[lineCount];
94 // TODO - Replace jQuery
95 $(this.display).animate({
96 scrollTop: topElem.offsetTop
97 }, {queue: false, duration: 200, easing: 'linear'});
103 // cm.setOption('direction', this.textDirection);
104 cm.setOption('direction', 'ltr'); // Will force to remain as ltr for now due to issues when HTML is in editor.
105 // Custom key commands
106 let metaKey = code.getMetaKey();
107 const extraKeys = {};
108 // Insert Image shortcut
109 extraKeys[`${metaKey}-Alt-I`] = function(cm) {
110 let selectedText = cm.getSelection();
111 let newText = ``;
112 let cursorPos = cm.getCursor('from');
113 cm.replaceSelection(newText);
114 cm.setCursor(cursorPos.line, cursorPos.ch + newText.length -1);
117 extraKeys[`${metaKey}-S`] = cm => {window.$events.emit('editor-save-draft')};
119 extraKeys[`${metaKey}-Enter`] = cm => {window.$events.emit('editor-save-page')};
120 // Show link selector
121 extraKeys[`Shift-${metaKey}-K`] = cm => {this.actionShowLinkSelector()};
123 extraKeys[`${metaKey}-K`] = cm => {insertLink()};
125 extraKeys[`${metaKey}-1`] = cm => {replaceLineStart('##');};
126 extraKeys[`${metaKey}-2`] = cm => {replaceLineStart('###');};
127 extraKeys[`${metaKey}-3`] = cm => {replaceLineStart('####');};
128 extraKeys[`${metaKey}-4`] = cm => {replaceLineStart('#####');};
129 extraKeys[`${metaKey}-5`] = cm => {replaceLineStart('');};
130 extraKeys[`${metaKey}-d`] = cm => {replaceLineStart('');};
131 extraKeys[`${metaKey}-6`] = cm => {replaceLineStart('>');};
132 extraKeys[`${metaKey}-q`] = cm => {replaceLineStart('>');};
133 extraKeys[`${metaKey}-7`] = cm => {wrapSelection('\n```\n', '\n```');};
134 extraKeys[`${metaKey}-8`] = cm => {wrapSelection('`', '`');};
135 extraKeys[`Shift-${metaKey}-E`] = cm => {wrapSelection('`', '`');};
136 extraKeys[`${metaKey}-9`] = cm => {wrapSelection('<p class="callout info">', '</p>');};
137 cm.setOption('extraKeys', extraKeys);
139 // Update data on content change
140 cm.on('change', (instance, changeObj) => {
141 this.updateAndRender();
144 // Handle scroll to sync display view
145 cm.on('scroll', instance => {
146 // Thanks to http://liuhao.im/english/2015/11/10/the-sync-scroll-of-markdown-editor-in-javascript.html
147 let scroll = instance.getScrollInfo();
148 let atEnd = scroll.top + scroll.clientHeight === scroll.height;
150 this.onMarkdownScroll(-1);
154 let lineNum = instance.lineAtHeight(scroll.top, 'local');
155 let range = instance.getRange({line: 0, ch: null}, {line: lineNum, ch: null});
156 let parser = new DOMParser();
157 let doc = parser.parseFromString(this.markdown.render(range), 'text/html');
158 let totalLines = doc.documentElement.querySelectorAll('body > *');
159 this.onMarkdownScroll(totalLines.length);
162 // Handle image paste
163 cm.on('paste', (cm, event) => {
164 if (!event.clipboardData || !event.clipboardData.items) return;
165 for (let i = 0; i < event.clipboardData.items.length; i++) {
166 uploadImage(event.clipboardData.items[i].getAsFile());
170 // Handle images on drag-drop
171 cm.on('drop', (cm, event) => {
172 event.stopPropagation();
173 event.preventDefault();
174 let cursorPos = cm.coordsChar({left: event.pageX, top: event.pageY});
175 cm.setCursor(cursorPos);
176 if (!event.dataTransfer || !event.dataTransfer.files) return;
177 for (let i = 0; i < event.dataTransfer.files.length; i++) {
178 uploadImage(event.dataTransfer.files[i]);
182 // Helper to replace editor content
183 function replaceContent(search, replace) {
184 let text = cm.getValue();
185 let cursor = cm.listSelections();
186 cm.setValue(text.replace(search, replace));
187 cm.setSelections(cursor);
190 // Helper to replace the start of the line
191 function replaceLineStart(newStart) {
192 let cursor = cm.getCursor();
193 let lineContent = cm.getLine(cursor.line);
194 let lineLen = lineContent.length;
195 let lineStart = lineContent.split(' ')[0];
197 // Remove symbol if already set
198 if (lineStart === newStart) {
199 lineContent = lineContent.replace(`${newStart} `, '');
200 cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
201 cm.setCursor({line: cursor.line, ch: cursor.ch - (newStart.length + 1)});
205 let alreadySymbol = /^[#>`]/.test(lineStart);
208 posDif = newStart.length - lineStart.length;
209 lineContent = lineContent.replace(lineStart, newStart).trim();
210 } else if (newStart !== '') {
211 posDif = newStart.length + 1;
212 lineContent = newStart + ' ' + lineContent;
214 cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
215 cm.setCursor({line: cursor.line, ch: cursor.ch + posDif});
218 function wrapLine(start, end) {
219 let cursor = cm.getCursor();
220 let lineContent = cm.getLine(cursor.line);
221 let lineLen = lineContent.length;
222 let newLineContent = lineContent;
224 if (lineContent.indexOf(start) === 0 && lineContent.slice(-end.length) === end) {
225 newLineContent = lineContent.slice(start.length, lineContent.length - end.length);
227 newLineContent = `${start}${lineContent}${end}`;
230 cm.replaceRange(newLineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
231 cm.setCursor({line: cursor.line, ch: cursor.ch + start.length});
234 function wrapSelection(start, end) {
235 let selection = cm.getSelection();
236 if (selection === '') return wrapLine(start, end);
238 let newSelection = selection;
242 if (selection.indexOf(start) === 0 && selection.slice(-end.length) === end) {
243 newSelection = selection.slice(start.length, selection.length - end.length);
244 endDiff = -(end.length + start.length);
246 newSelection = `${start}${selection}${end}`;
247 endDiff = start.length + end.length;
250 let selections = cm.listSelections()[0];
251 cm.replaceSelection(newSelection);
252 let headFirst = selections.head.ch <= selections.anchor.ch;
253 selections.head.ch += headFirst ? frontDiff : endDiff;
254 selections.anchor.ch += headFirst ? endDiff : frontDiff;
255 cm.setSelections([selections]);
258 // Handle image upload and add image into markdown content
259 function uploadImage(file) {
260 if (file === null || file.type.indexOf('image') !== 0) return;
264 let fileNameMatches = file.name.match(/\.(.+)$/);
265 if (fileNameMatches.length > 1) ext = fileNameMatches[1];
268 // Insert image into markdown
269 let id = "image-" + Math.random().toString(16).slice(2);
270 let placeholderImage = window.baseUrl(`/loading.gif#upload${id}`);
271 let selectedText = cm.getSelection();
272 let placeHolderText = ``;
273 let cursor = cm.getCursor();
274 cm.replaceSelection(placeHolderText);
275 cm.setCursor({line: cursor.line, ch: cursor.ch + selectedText.length + 2});
277 let remoteFilename = "image-" + Date.now() + "." + ext;
278 let formData = new FormData();
279 formData.append('file', file, remoteFilename);
281 window.$http.post('/images/gallery/upload', formData).then(resp => {
282 replaceContent(placeholderImage, resp.data.thumbs.display);
284 window.$events.emit('error', trans('errors.image_upload_error'));
285 replaceContent(placeHolderText, selectedText);
290 function insertLink() {
291 let cursorPos = cm.getCursor('from');
292 let selectedText = cm.getSelection() || '';
293 let newText = `[${selectedText}]()`;
295 cm.replaceSelection(newText);
296 let cursorPosDiff = (selectedText === '') ? -3 : -1;
297 cm.setCursor(cursorPos.line, cursorPos.ch + newText.length+cursorPosDiff);
300 this.updateAndRender();
303 actionInsertImage() {
304 let cursorPos = this.cm.getCursor('from');
305 window.ImageManager.show(image => {
306 let selectedText = this.cm.getSelection();
307 let newText = "[](" + image.url + ")";
309 this.cm.replaceSelection(newText);
310 this.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
314 actionShowImageManager() {
315 let cursorPos = this.cm.getCursor('from');
316 window.ImageManager.show(image => {
317 this.insertDrawing(image, cursorPos);
321 // Show the popup link selector and insert a link when finished
322 actionShowLinkSelector() {
323 let cursorPos = this.cm.getCursor('from');
324 window.EntitySelectorPopup.show(entity => {
325 let selectedText = this.cm.getSelection() || entity.name;
326 let newText = `[${selectedText}](${entity.link})`;
328 this.cm.replaceSelection(newText);
329 this.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
333 // Show draw.io if enabled and handle save.
334 actionStartDrawing() {
335 if (document.querySelector('[drawio-enabled]').getAttribute('drawio-enabled') !== 'true') return;
336 let cursorPos = this.cm.getCursor('from');
339 return Promise.resolve('');
341 // let id = "image-" + Math.random().toString(16).slice(2);
342 // let loadingImage = window.baseUrl('/loading.gif');
345 uploaded_to: Number(document.getElementById('page-editor').getAttribute('page-id'))
348 window.$http.post(window.baseUrl('/images/drawing/upload'), data).then(resp => {
349 this.insertDrawing(resp.data, cursorPos);
352 window.$events.emit('error', trans('errors.image_upload_error'));
358 insertDrawing(image, originalCursor) {
359 let newText = `<div drawio-diagram="${image.id}"><img src="${image.url}"></div>`;
361 this.cm.replaceSelection(newText);
362 this.cm.setCursor(originalCursor.line, originalCursor.ch + newText.length);
365 // Show draw.io if enabled and handle save.
366 actionEditDrawing(imgContainer) {
367 if (document.querySelector('[drawio-enabled]').getAttribute('drawio-enabled') !== 'true') return;
368 let cursorPos = this.cm.getCursor('from');
369 let drawingId = imgContainer.getAttribute('drawio-diagram');
372 return window.$http.get(window.baseUrl(`/images/base64/${drawingId}`)).then(resp => {
373 return `data:image/png;base64,${resp.data.content}`;
379 uploaded_to: Number(document.getElementById('page-editor').getAttribute('page-id'))
382 window.$http.post(window.baseUrl(`/images/drawing/upload`), data).then(resp => {
383 let newText = `<div drawio-diagram="${resp.data.id}"><img src="${resp.data.url}"></div>`;
384 let newContent = this.cm.getValue().split('\n').map(line => {
385 if (line.indexOf(`drawio-diagram="${drawingId}"`) !== -1) {
390 this.cm.setValue(newContent);
391 this.cm.setCursor(cursorPos);
395 window.$events.emit('error', trans('errors.image_upload_error'));
401 // Scroll to a specified text
402 scrollToText(searchText) {
407 const content = this.cm.getValue();
408 const lines = content.split(/\r?\n/);
409 let lineNumber = lines.findIndex(line => {
410 return line && line.indexOf(searchText) !== -1;
413 if (lineNumber === -1) {
417 this.cm.scrollIntoView({
421 // set the cursor location.
424 char: lines[lineNumber].length
430 export default MarkdownEditor ;