1 import DrawIO from "../services/drawio";
5 * @param {MarkdownEditor} editor
16 const content = this.#getText();
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;
32 /** @type {ImageManager} **/
33 const imageManager = window.$components.first('image-manager');
35 imageManager.show(image => {
36 const imageUrl = image.thumbs.display || image.url;
37 const selectedText = this.#getSelectionText();
38 const newText = "[](" + image.url + ")";
39 this.#replaceSelection(newText, newText.length);
44 const newText = ``;
45 this.#replaceSelection(newText, newText.length - 1);
49 const selectedText = this.#getSelectionText();
50 const newText = `[${selectedText}]()`;
51 const cursorPosDiff = (selectedText === '') ? -3 : -1;
52 this.#replaceSelection(newText, newText.length+cursorPosDiff);
56 const selectionRange = this.#getSelectionRange();
57 /** @type {ImageManager} **/
58 const imageManager = window.$components.first('image-manager');
59 imageManager.show(image => {
60 this.#insertDrawing(image, selectionRange);
64 // Show the popup link selector and insert a link when finished
66 const selectionRange = this.#getSelectionRange();
68 /** @type {EntitySelectorPopup} **/
69 const selector = window.$components.first('entity-selector-popup');
70 selector.show(entity => {
71 const selectedText = this.#getSelectionText(selectionRange) || entity.name;
72 const newText = `[${selectedText}](${entity.link})`;
73 this.#replaceSelection(newText, newText.length, selectionRange);
77 // Show draw.io if enabled and handle save.
79 const url = this.editor.config.drawioUrl;
82 const selectionRange = this.#getSelectionRange();
84 DrawIO.show(url,() => {
85 return Promise.resolve('');
90 uploaded_to: Number(this.editor.config.pageId),
93 window.$http.post("/images/drawio", data).then(resp => {
94 this.#insertDrawing(resp.data, selectionRange);
97 this.handleDrawingUploadError(err);
102 #insertDrawing(image, originalSelectionRange) {
103 const newText = `<div drawio-diagram="${image.id}"><img src="${image.url}"></div>`;
104 this.#replaceSelection(newText, newText.length, originalSelectionRange);
107 // Show draw.io if enabled and handle save.
108 editDrawing(imgContainer) {
109 const drawioUrl = this.editor.config.drawioUrl;
114 const selectionRange = this.#getSelectionRange();
115 const drawingId = imgContainer.getAttribute('drawio-diagram');
117 DrawIO.show(drawioUrl, () => {
118 return DrawIO.load(drawingId);
123 uploaded_to: Number(this.editor.config.pageId),
126 window.$http.post("/images/drawio", data).then(resp => {
127 const newText = `<div drawio-diagram="${resp.data.id}"><img src="${resp.data.url}"></div>`;
128 const newContent = this.#getText().split('\n').map(line => {
129 if (line.indexOf(`drawio-diagram="${drawingId}"`) !== -1) {
134 this.#setText(newContent, selectionRange);
137 this.handleDrawingUploadError(err);
142 handleDrawingUploadError(error) {
143 if (error.status === 413) {
144 window.$events.emit('error', this.editor.config.text.serverUploadLimit);
146 window.$events.emit('error', this.editor.config.text.imageUploadError);
151 // Make the editor full screen
153 const container = this.editor.config.container;
154 const alreadyFullscreen = container.classList.contains('fullscreen');
155 container.classList.toggle('fullscreen', !alreadyFullscreen);
156 document.body.classList.toggle('markdown-fullscreen', !alreadyFullscreen);
159 // Scroll to a specified text
160 scrollToText(searchText) {
165 const text = this.editor.cm.state.doc;
167 let scrollToLine = -1;
168 for (const line of text.iterLines()) {
169 if (line.includes(searchText)) {
170 scrollToLine = lineCount;
176 if (scrollToLine === -1) {
180 const line = text.line(scrollToLine);
181 this.editor.cm.dispatch({
182 selection: {anchor: line.from, head: line.to},
183 scrollIntoView: true,
189 if (!this.editor.cm.hasFocus) {
190 this.editor.cm.focus();
195 * Insert content into the editor.
196 * @param {String} content
198 insertContent(content) {
199 this.#replaceSelection(content, content.length);
203 * Prepend content to the editor.
204 * @param {String} content
206 prependContent(content) {
207 content = this.#cleanTextForEditor(content);
208 const selectionRange = this.#getSelectionRange();
209 this.editor.cm.dispatch({
210 changes: {from: 0, to: 0, insert: content + '\n'},
211 selection: {anchor: selectionRange.from + content.length + 1}
217 * Append content to the editor.
218 * @param {String} content
220 appendContent(content) {
221 content = this.#cleanTextForEditor(content);
222 this.editor.cm.dispatch({
223 changes: {from: this.editor.cm.state.doc.length, insert: '\n' + content},
229 * Replace the editor's contents
230 * @param {String} content
232 replaceContent(content) {
233 this.#setText(content)
237 * Replace the start of the line
238 * @param {String} newStart
240 replaceLineStart(newStart) {
241 const selectionRange = this.#getSelectionRange();
242 const line = this.editor.cm.state.doc.lineAt(selectionRange.from);
244 const lineContent = line.text;
245 const lineStart = lineContent.split(' ')[0];
247 // Remove symbol if already set
248 if (lineStart === newStart) {
249 const newLineContent = lineContent.replace(`${newStart} `, '');
250 this.editor.cm.dispatch({
251 changes: {from: line.from, to: line.to, insert: newLineContent},
252 selection: {anchor: selectionRange.from + (newLineContent.length - lineContent.length)}
257 let newLineContent = lineContent;
258 const alreadySymbol = /^[#>`]/.test(lineStart);
260 newLineContent = lineContent.replace(lineStart, newStart).trim();
261 } else if (newStart !== '') {
262 newLineContent = newStart + ' ' + lineContent;
265 this.editor.cm.dispatch({
266 changes: {from: line.from, to: line.to, insert: newLineContent},
267 selection: {anchor: selectionRange.from + (newLineContent.length - lineContent.length)}
272 * Wrap the selection in the given contents start and end contents.
273 * @param {String} start
274 * @param {String} end
276 wrapSelection(start, end) {
277 const selectionRange = this.#getSelectionRange();
278 const selectionText = this.#getSelectionText(selectionRange);
279 if (!selectionText) return this.#wrapLine(start, end);
281 let newSelectionText = selectionText;
284 if (selectionText.startsWith(start) && selectionText.endsWith(end)) {
285 newSelectionText = selectionText.slice(start.length, selectionText.length - end.length);
286 newRange = selectionRange.extend(selectionRange.from, selectionRange.to - (start.length + end.length));
288 newSelectionText = `${start}${selectionText}${end}`;
289 newRange = selectionRange.extend(selectionRange.from, selectionRange.to + (start.length + end.length));
292 this.editor.cm.dispatch({
293 changes: {from: selectionRange.from, to: selectionRange.to, insert: newSelectionText},
294 selection: {anchor: newRange.anchor, head: newRange.head},
298 replaceLineStartForOrderedList() {
300 const cursor = this.editor.cm.getCursor();
301 const prevLineContent = this.editor.cm.getLine(cursor.line - 1) || '';
302 const listMatch = prevLineContent.match(/^(\s*)(\d)([).])\s/) || [];
304 const number = (Number(listMatch[2]) || 0) + 1;
305 const whiteSpace = listMatch[1] || '';
306 const listMark = listMatch[3] || '.'
308 const prefix = `${whiteSpace}${number}${listMark}`;
309 return this.replaceLineStart(prefix);
313 * Cycles through the type of callout block within the selection.
314 * Creates a callout block if none existing, and removes it if cycling past the danger type.
316 cycleCalloutTypeAtSelection() {
318 const selectionRange = this.editor.cm.listSelections()[0];
319 const lineContent = this.editor.cm.getLine(selectionRange.anchor.line);
320 const lineLength = lineContent.length;
321 const contentRange = {
322 anchor: {line: selectionRange.anchor.line, ch: 0},
323 head: {line: selectionRange.anchor.line, ch: lineLength},
326 const formats = ['info', 'success', 'warning', 'danger'];
327 const joint = formats.join('|');
328 const regex = new RegExp(`class="((${joint})\\s+callout|callout\\s+(${joint}))"`, 'i');
329 const matches = regex.exec(lineContent);
330 const format = (matches ? (matches[2] || matches[3]) : '').toLowerCase();
332 if (format === formats[formats.length - 1]) {
333 this.wrapLine(`<p class="callout ${formats[formats.length - 1]}">`, '</p>');
334 } else if (format === '') {
335 this.wrapLine('<p class="callout info">', '</p>');
337 const newFormatIndex = formats.indexOf(format) + 1;
338 const newFormat = formats[newFormatIndex];
339 const newContent = lineContent.replace(matches[0], matches[0].replace(format, newFormat));
340 this.editor.cm.replaceRange(newContent, contentRange.anchor, contentRange.head);
342 const chDiff = newContent.length - lineContent.length;
343 selectionRange.anchor.ch += chDiff;
344 if (selectionRange.anchor !== selectionRange.head) {
345 selectionRange.head.ch += chDiff;
347 this.editor.cm.setSelection(selectionRange.anchor, selectionRange.head);
351 syncDisplayPosition(event) {
352 // Thanks to http://liuhao.im/english/2015/11/10/the-sync-scroll-of-markdown-editor-in-javascript.html
353 const scrollEl = event.target;
354 const atEnd = Math.abs(scrollEl.scrollHeight - scrollEl.clientHeight - scrollEl.scrollTop) < 1;
356 this.editor.display.scrollToIndex(-1);
360 const blockInfo = this.editor.cm.lineBlockAtHeight(scrollEl.scrollTop);
361 const range = this.editor.cm.state.sliceDoc(0, blockInfo.from);
362 const parser = new DOMParser();
363 const doc = parser.parseFromString(this.editor.markdown.render(range), 'text/html');
364 const totalLines = doc.documentElement.querySelectorAll('body > *');
365 this.editor.display.scrollToIndex(totalLines.length);
369 * Fetch and insert the template of the given ID.
370 * The page-relative position provided can be used to determine insert location if possible.
371 * @param {String} templateId
372 * @param {Number} posX
373 * @param {Number} posY
375 insertTemplate(templateId, posX, posY) {
377 const cursorPos = this.editor.cm.coordsChar({left: posX, top: posY});
378 this.editor.cm.setCursor(cursorPos);
379 window.$http.get(`/templates/${templateId}`).then(resp => {
380 const content = resp.data.markdown || resp.data.html;
381 this.editor.cm.replaceSelection(content);
386 * Insert multiple images from the clipboard.
387 * @param {File[]} images
389 insertClipboardImages(images) {
391 const cursorPos = this.editor.cm.coordsChar({left: event.pageX, top: event.pageY});
392 this.editor.cm.setCursor(cursorPos);
393 for (const image of images) {
394 this.#uploadImage(image);
399 * Handle image upload and add image into markdown content
404 if (file === null || file.type.indexOf('image') !== 0) return;
408 let fileNameMatches = file.name.match(/\.(.+)$/);
409 if (fileNameMatches.length > 1) ext = fileNameMatches[1];
412 // Insert image into markdown
413 const id = "image-" + Math.random().toString(16).slice(2);
414 const placeholderImage = window.baseUrl(`/loading.gif#upload${id}`);
415 const selectedText = this.editor.cm.getSelection();
416 const placeHolderText = ``;
417 const cursor = this.editor.cm.getCursor();
418 this.editor.cm.replaceSelection(placeHolderText);
419 this.editor.cm.setCursor({line: cursor.line, ch: cursor.ch + selectedText.length + 3});
421 const remoteFilename = "image-" + Date.now() + "." + ext;
422 const formData = new FormData();
423 formData.append('file', file, remoteFilename);
424 formData.append('uploaded_to', this.editor.config.pageId);
426 window.$http.post('/images/gallery', formData).then(resp => {
427 const newContent = `[](${resp.data.url})`;
428 this.#findAndReplaceContent(placeHolderText, newContent);
430 window.$events.emit('error', this.editor.config.text.imageUploadError);
431 this.#findAndReplaceContent(placeHolderText, selectedText);
437 * Get the current text of the editor instance.
441 return this.editor.cm.state.doc.toString();
445 * Set the text of the current editor instance.
446 * @param {String} text
447 * @param {?SelectionRange} selectionRange
449 #setText(text, selectionRange = null) {
450 selectionRange = selectionRange || this.#getSelectionRange();
451 this.editor.cm.dispatch({
452 changes: {from: 0, to: this.editor.cm.state.doc.length, insert: text},
453 selection: {anchor: selectionRange.from},
460 * Replace the current selection and focus the editor.
461 * Takes an offset for the cursor, after the change, relative to the start of the provided string.
462 * Can be provided a selection range to use instead of the current selection range.
463 * @param {String} newContent
464 * @param {Number} cursorOffset
465 * @param {?SelectionRange} selectionRange
467 #replaceSelection(newContent, cursorOffset = 0, selectionRange = null) {
468 selectionRange = selectionRange || this.editor.cm.state.selection.main;
469 this.editor.cm.dispatch({
470 changes: {from: selectionRange.from, to: selectionRange.to, insert: newContent},
471 selection: {anchor: selectionRange.from + cursorOffset},
478 * Get the text content of the main current selection.
479 * @param {SelectionRange} selectionRange
482 #getSelectionText(selectionRange = null) {
483 selectionRange = selectionRange || this.#getSelectionRange();
484 return this.editor.cm.state.sliceDoc(selectionRange.from, selectionRange.to);
488 * Get the range of the current main selection.
489 * @return {SelectionRange}
491 #getSelectionRange() {
492 return this.editor.cm.state.selection.main;
496 * Cleans the given text to work with the editor.
497 * Standardises line endings to what's expected.
498 * @param {String} text
501 #cleanTextForEditor(text) {
502 return text.replace(/\r\n|\r/g, "\n");
506 * Find and replace the first occurrence of [search] with [replace]
507 * @param {String} search
508 * @param {String} replace
510 #findAndReplaceContent(search, replace) {
511 const newText = this.#getText().replace(search, replace);
512 this.#setText(newText);
516 * Wrap the line in the given start and end contents.
517 * @param {String} start
518 * @param {String} end
520 #wrapLine(start, end) {
521 const selectionRange = this.#getSelectionRange();
522 const line = this.editor.cm.state.doc.lineAt(selectionRange.from);
523 const lineContent = line.text;
527 if (lineContent.startsWith(start) && lineContent.endsWith(end)) {
528 newLineContent = lineContent.slice(start.length, lineContent.length - end.length);
529 lineOffset = -(start.length);
531 newLineContent = `${start}${lineContent}${end}`;
532 lineOffset = start.length;
535 this.editor.cm.dispatch({
536 changes: {from: line.from, to: line.to, insert: newLineContent},
537 selection: {anchor: selectionRange.from + lineOffset}