1 import DrawIO from "../services/drawio";
5 * @param {MarkdownEditor} editor
16 const content = this.editor.cm.state.doc.toString();
17 this.editor.config.inputEl.value = content;
19 const html = this.editor.markdown.render(content);
20 window.$events.emit('editor-html-change', '');
21 window.$events.emit('editor-markdown-change', '');
22 this.lastContent.html = html;
23 this.lastContent.markdown = content;
24 this.editor.display.patchWithHtml(html);
28 return this.lastContent;
33 const cursorPos = this.editor.cm.getCursor('from');
34 /** @type {ImageManager} **/
35 const imageManager = window.$components.first('image-manager');
36 imageManager.show(image => {
37 const imageUrl = image.thumbs.display || image.url;
38 let selectedText = this.editor.cm.getSelection();
39 let newText = "[](" + image.url + ")";
40 this.editor.cm.focus();
41 this.editor.cm.replaceSelection(newText);
42 this.editor.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
48 const selectedText = this.editor.cm.getSelection();
49 const newText = ``;
50 const cursorPos = this.editor.cm.getCursor('from');
51 this.editor.cm.replaceSelection(newText);
52 this.editor.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length -1);
57 const cursorPos = this.editor.cm.getCursor('from');
58 const selectedText = this.editor.cm.getSelection() || '';
59 const newText = `[${selectedText}]()`;
60 this.editor.cm.focus();
61 this.editor.cm.replaceSelection(newText);
62 const cursorPosDiff = (selectedText === '') ? -3 : -1;
63 this.editor.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length+cursorPosDiff);
68 const cursorPos = this.editor.cm.getCursor('from');
69 /** @type {ImageManager} **/
70 const imageManager = window.$components.first('image-manager');
71 imageManager.show(image => {
72 this.insertDrawing(image, cursorPos);
76 // Show the popup link selector and insert a link when finished
79 const cursorPos = this.editor.cm.getCursor('from');
80 /** @type {EntitySelectorPopup} **/
81 const selector = window.$components.first('entity-selector-popup');
82 selector.show(entity => {
83 let selectedText = this.editor.cm.getSelection() || entity.name;
84 let newText = `[${selectedText}](${entity.link})`;
85 this.editor.cm.focus();
86 this.editor.cm.replaceSelection(newText);
87 this.editor.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
91 // Show draw.io if enabled and handle save.
94 const url = this.editor.config.drawioUrl;
97 const cursorPos = this.editor.cm.getCursor('from');
99 DrawIO.show(url,() => {
100 return Promise.resolve('');
105 uploaded_to: Number(this.editor.config.pageId),
108 window.$http.post("/images/drawio", data).then(resp => {
109 this.insertDrawing(resp.data, cursorPos);
112 this.handleDrawingUploadError(err);
117 insertDrawing(image, originalCursor) {
119 const newText = `<div drawio-diagram="${image.id}"><img src="${image.url}"></div>`;
120 this.editor.cm.focus();
121 this.editor.cm.replaceSelection(newText);
122 this.editor.cm.setCursor(originalCursor.line, originalCursor.ch + newText.length);
125 // Show draw.io if enabled and handle save.
126 editDrawing(imgContainer) {
128 const drawioUrl = this.editor.config.drawioUrl;
133 const cursorPos = this.editor.cm.getCursor('from');
134 const drawingId = imgContainer.getAttribute('drawio-diagram');
136 DrawIO.show(drawioUrl, () => {
137 return DrawIO.load(drawingId);
142 uploaded_to: Number(this.editor.config.pageId),
145 window.$http.post("/images/drawio", data).then(resp => {
146 const newText = `<div drawio-diagram="${resp.data.id}"><img src="${resp.data.url}"></div>`;
147 const newContent = this.editor.cm.getValue().split('\n').map(line => {
148 if (line.indexOf(`drawio-diagram="${drawingId}"`) !== -1) {
153 this.editor.cm.setValue(newContent);
154 this.editor.cm.setCursor(cursorPos);
155 this.editor.cm.focus();
158 this.handleDrawingUploadError(err);
163 handleDrawingUploadError(error) {
165 if (error.status === 413) {
166 window.$events.emit('error', this.editor.config.text.serverUploadLimit);
168 window.$events.emit('error', this.editor.config.text.imageUploadError);
173 // Make the editor full screen
176 const container = this.editor.config.container;
177 const alreadyFullscreen = container.classList.contains('fullscreen');
178 container.classList.toggle('fullscreen', !alreadyFullscreen);
179 document.body.classList.toggle('markdown-fullscreen', !alreadyFullscreen);
182 // Scroll to a specified text
183 scrollToText(searchText) {
189 const content = this.editor.cm.getValue();
190 const lines = content.split(/\r?\n/);
191 let lineNumber = lines.findIndex(line => {
192 return line && line.indexOf(searchText) !== -1;
195 if (lineNumber === -1) {
199 this.editor.cm.scrollIntoView({
202 this.editor.cm.focus();
203 // set the cursor location.
204 this.editor.cm.setCursor({
206 char: lines[lineNumber].length
212 this.editor.cm.focus();
216 * Insert content into the editor.
217 * @param {String} content
219 insertContent(content) {
221 this.editor.cm.replaceSelection(content);
225 * Prepend content to the editor.
226 * @param {String} content
228 prependContent(content) {
230 const cursorPos = this.editor.cm.getCursor('from');
231 const newContent = content + '\n' + this.editor.cm.getValue();
232 this.editor.cm.setValue(newContent);
233 const prependLineCount = content.split('\n').length;
234 this.editor.cm.setCursor(cursorPos.line + prependLineCount, cursorPos.ch);
238 * Append content to the editor.
239 * @param {String} content
241 appendContent(content) {
243 const cursorPos = this.editor.cm.getCursor('from');
244 const newContent = this.editor.cm.getValue() + '\n' + content;
245 this.editor.cm.setValue(newContent);
246 this.editor.cm.setCursor(cursorPos.line, cursorPos.ch);
250 * Replace the editor's contents
251 * @param {String} content
253 replaceContent(content) {
255 this.editor.cm.setValue(content);
259 * @param {String|RegExp} search
260 * @param {String} replace
262 findAndReplaceContent(search, replace) {
264 const text = this.editor.cm.getValue();
265 const cursor = this.editor.cm.listSelections();
266 this.editor.cm.setValue(text.replace(search, replace));
267 this.editor.cm.setSelections(cursor);
271 * Replace the start of the line
272 * @param {String} newStart
274 replaceLineStart(newStart) {
276 const cursor = this.editor.cm.getCursor();
277 let lineContent = this.editor.cm.getLine(cursor.line);
278 const lineLen = lineContent.length;
279 const lineStart = lineContent.split(' ')[0];
281 // Remove symbol if already set
282 if (lineStart === newStart) {
283 lineContent = lineContent.replace(`${newStart} `, '');
284 this.editor.cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
285 this.editor.cm.setCursor({line: cursor.line, ch: cursor.ch - (newStart.length + 1)});
289 const alreadySymbol = /^[#>`]/.test(lineStart);
292 posDif = newStart.length - lineStart.length;
293 lineContent = lineContent.replace(lineStart, newStart).trim();
294 } else if (newStart !== '') {
295 posDif = newStart.length + 1;
296 lineContent = newStart + ' ' + lineContent;
298 this.editor.cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
299 this.editor.cm.setCursor({line: cursor.line, ch: cursor.ch + posDif});
303 * Wrap the line in the given start and end contents.
304 * @param {String} start
305 * @param {String} end
307 wrapLine(start, end) {
309 const cursor = this.editor.cm.getCursor();
310 const lineContent = this.editor.cm.getLine(cursor.line);
311 const lineLen = lineContent.length;
312 let newLineContent = lineContent;
314 if (lineContent.indexOf(start) === 0 && lineContent.slice(-end.length) === end) {
315 newLineContent = lineContent.slice(start.length, lineContent.length - end.length);
317 newLineContent = `${start}${lineContent}${end}`;
320 this.editor.cm.replaceRange(newLineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
321 this.editor.cm.setCursor({line: cursor.line, ch: cursor.ch + start.length});
325 * Wrap the selection in the given contents start and end contents.
326 * @param {String} start
327 * @param {String} end
329 wrapSelection(start, end) {
331 const selection = this.editor.cm.getSelection();
332 if (selection === '') return this.wrapLine(start, end);
334 let newSelection = selection;
338 if (selection.indexOf(start) === 0 && selection.slice(-end.length) === end) {
339 newSelection = selection.slice(start.length, selection.length - end.length);
340 endDiff = -(end.length + start.length);
342 newSelection = `${start}${selection}${end}`;
343 endDiff = start.length + end.length;
346 const selections = this.editor.cm.listSelections()[0];
347 this.editor.cm.replaceSelection(newSelection);
348 const headFirst = selections.head.ch <= selections.anchor.ch;
349 selections.head.ch += headFirst ? frontDiff : endDiff;
350 selections.anchor.ch += headFirst ? endDiff : frontDiff;
351 this.editor.cm.setSelections([selections]);
354 replaceLineStartForOrderedList() {
356 const cursor = this.editor.cm.getCursor();
357 const prevLineContent = this.editor.cm.getLine(cursor.line - 1) || '';
358 const listMatch = prevLineContent.match(/^(\s*)(\d)([).])\s/) || [];
360 const number = (Number(listMatch[2]) || 0) + 1;
361 const whiteSpace = listMatch[1] || '';
362 const listMark = listMatch[3] || '.'
364 const prefix = `${whiteSpace}${number}${listMark}`;
365 return this.replaceLineStart(prefix);
369 * Cycles through the type of callout block within the selection.
370 * Creates a callout block if none existing, and removes it if cycling past the danger type.
372 cycleCalloutTypeAtSelection() {
374 const selectionRange = this.editor.cm.listSelections()[0];
375 const lineContent = this.editor.cm.getLine(selectionRange.anchor.line);
376 const lineLength = lineContent.length;
377 const contentRange = {
378 anchor: {line: selectionRange.anchor.line, ch: 0},
379 head: {line: selectionRange.anchor.line, ch: lineLength},
382 const formats = ['info', 'success', 'warning', 'danger'];
383 const joint = formats.join('|');
384 const regex = new RegExp(`class="((${joint})\\s+callout|callout\\s+(${joint}))"`, 'i');
385 const matches = regex.exec(lineContent);
386 const format = (matches ? (matches[2] || matches[3]) : '').toLowerCase();
388 if (format === formats[formats.length - 1]) {
389 this.wrapLine(`<p class="callout ${formats[formats.length - 1]}">`, '</p>');
390 } else if (format === '') {
391 this.wrapLine('<p class="callout info">', '</p>');
393 const newFormatIndex = formats.indexOf(format) + 1;
394 const newFormat = formats[newFormatIndex];
395 const newContent = lineContent.replace(matches[0], matches[0].replace(format, newFormat));
396 this.editor.cm.replaceRange(newContent, contentRange.anchor, contentRange.head);
398 const chDiff = newContent.length - lineContent.length;
399 selectionRange.anchor.ch += chDiff;
400 if (selectionRange.anchor !== selectionRange.head) {
401 selectionRange.head.ch += chDiff;
403 this.editor.cm.setSelection(selectionRange.anchor, selectionRange.head);
408 * Handle image upload and add image into markdown content
413 if (file === null || file.type.indexOf('image') !== 0) return;
417 let fileNameMatches = file.name.match(/\.(.+)$/);
418 if (fileNameMatches.length > 1) ext = fileNameMatches[1];
421 // Insert image into markdown
422 const id = "image-" + Math.random().toString(16).slice(2);
423 const placeholderImage = window.baseUrl(`/loading.gif#upload${id}`);
424 const selectedText = this.editor.cm.getSelection();
425 const placeHolderText = ``;
426 const cursor = this.editor.cm.getCursor();
427 this.editor.cm.replaceSelection(placeHolderText);
428 this.editor.cm.setCursor({line: cursor.line, ch: cursor.ch + selectedText.length + 3});
430 const remoteFilename = "image-" + Date.now() + "." + ext;
431 const formData = new FormData();
432 formData.append('file', file, remoteFilename);
433 formData.append('uploaded_to', this.editor.config.pageId);
435 window.$http.post('/images/gallery', formData).then(resp => {
436 const newContent = `[](${resp.data.url})`;
437 this.findAndReplaceContent(placeHolderText, newContent);
439 window.$events.emit('error', this.editor.config.text.imageUploadError);
440 this.findAndReplaceContent(placeHolderText, selectedText);
445 syncDisplayPosition(event) {
446 // Thanks to http://liuhao.im/english/2015/11/10/the-sync-scroll-of-markdown-editor-in-javascript.html
447 const scrollEl = event.target;
448 const atEnd = Math.abs(scrollEl.scrollHeight - scrollEl.clientHeight - scrollEl.scrollTop) < 1;
450 this.editor.display.scrollToIndex(-1);
454 const blockInfo = this.editor.cm.lineBlockAtHeight(scrollEl.scrollTop);
455 const range = this.editor.cm.state.sliceDoc(0, blockInfo.from);
456 const parser = new DOMParser();
457 const doc = parser.parseFromString(this.editor.markdown.render(range), 'text/html');
458 const totalLines = doc.documentElement.querySelectorAll('body > *');
459 this.editor.display.scrollToIndex(totalLines.length);
463 * Fetch and insert the template of the given ID.
464 * The page-relative position provided can be used to determine insert location if possible.
465 * @param {String} templateId
466 * @param {Number} posX
467 * @param {Number} posY
469 insertTemplate(templateId, posX, posY) {
471 const cursorPos = this.editor.cm.coordsChar({left: posX, top: posY});
472 this.editor.cm.setCursor(cursorPos);
473 window.$http.get(`/templates/${templateId}`).then(resp => {
474 const content = resp.data.markdown || resp.data.html;
475 this.editor.cm.replaceSelection(content);
480 * Insert multiple images from the clipboard.
481 * @param {File[]} images
483 insertClipboardImages(images) {
485 const cursorPos = this.editor.cm.coordsChar({left: event.pageX, top: event.pageY});
486 this.editor.cm.setCursor(cursorPos);
487 for (const image of images) {
488 this.uploadImage(image);