1 import * as DrawIO from '../services/drawio';
6 * @param {MarkdownEditor} editor
17 const content = this.#getText();
18 this.editor.config.inputEl.value = content;
20 const html = this.editor.markdown.render(content);
21 window.$events.emit('editor-html-change', '');
22 window.$events.emit('editor-markdown-change', '');
23 this.lastContent.html = html;
24 this.lastContent.markdown = content;
25 this.editor.display.patchWithHtml(html);
29 return this.lastContent;
33 /** @type {ImageManager} * */
34 const imageManager = window.$components.first('image-manager');
36 imageManager.show(image => {
37 const imageUrl = image.thumbs.display || image.url;
38 const selectedText = this.#getSelectionText();
39 const newText = `[](${image.url})`;
40 this.#replaceSelection(newText, newText.length);
45 const newText = ``;
46 this.#replaceSelection(newText, newText.length - 1);
50 const selectedText = this.#getSelectionText();
51 const newText = `[${selectedText}]()`;
52 const cursorPosDiff = (selectedText === '') ? -3 : -1;
53 this.#replaceSelection(newText, newText.length + cursorPosDiff);
57 const selectionRange = this.#getSelectionRange();
58 /** @type {ImageManager} * */
59 const imageManager = window.$components.first('image-manager');
60 imageManager.show(image => {
61 this.#insertDrawing(image, selectionRange);
65 // Show the popup link selector and insert a link when finished
67 const selectionRange = this.#getSelectionRange();
69 /** @type {EntitySelectorPopup} * */
70 const selector = window.$components.first('entity-selector-popup');
71 selector.show(entity => {
72 const selectedText = this.#getSelectionText(selectionRange) || entity.name;
73 const newText = `[${selectedText}](${entity.link})`;
74 this.#replaceSelection(newText, newText.length, selectionRange);
78 // Show draw.io if enabled and handle save.
80 const url = this.editor.config.drawioUrl;
83 const selectionRange = this.#getSelectionRange();
85 DrawIO.show(url, () => Promise.resolve(''), pngData => {
88 uploaded_to: Number(this.editor.config.pageId),
91 window.$http.post('/images/drawio', data).then(resp => {
92 this.#insertDrawing(resp.data, selectionRange);
95 this.handleDrawingUploadError(err);
100 #insertDrawing(image, originalSelectionRange) {
101 const newText = `<div drawio-diagram="${image.id}"><img src="${image.url}"></div>`;
102 this.#replaceSelection(newText, newText.length, originalSelectionRange);
105 // Show draw.io if enabled and handle save.
106 editDrawing(imgContainer) {
107 const {drawioUrl} = this.editor.config;
112 const selectionRange = this.#getSelectionRange();
113 const drawingId = imgContainer.getAttribute('drawio-diagram');
115 DrawIO.show(drawioUrl, () => DrawIO.load(drawingId), pngData => {
118 uploaded_to: Number(this.editor.config.pageId),
121 window.$http.post('/images/drawio', data).then(resp => {
122 const newText = `<div drawio-diagram="${resp.data.id}"><img src="${resp.data.url}"></div>`;
123 const newContent = this.#getText().split('\n').map(line => {
124 if (line.indexOf(`drawio-diagram="${drawingId}"`) !== -1) {
129 this.#setText(newContent, selectionRange);
132 this.handleDrawingUploadError(err);
137 handleDrawingUploadError(error) {
138 if (error.status === 413) {
139 window.$events.emit('error', this.editor.config.text.serverUploadLimit);
141 window.$events.emit('error', this.editor.config.text.imageUploadError);
143 console.error(error);
146 // Make the editor full screen
148 const {container} = this.editor.config;
149 const alreadyFullscreen = container.classList.contains('fullscreen');
150 container.classList.toggle('fullscreen', !alreadyFullscreen);
151 document.body.classList.toggle('markdown-fullscreen', !alreadyFullscreen);
154 // Scroll to a specified text
155 scrollToText(searchText) {
160 const text = this.editor.cm.state.doc;
162 let scrollToLine = -1;
163 for (const line of text.iterLines()) {
164 if (line.includes(searchText)) {
165 scrollToLine = lineCount;
171 if (scrollToLine === -1) {
175 const line = text.line(scrollToLine);
176 this.#setSelection(line.from, line.to, true);
181 if (!this.editor.cm.hasFocus) {
182 this.editor.cm.focus();
187 * Insert content into the editor.
188 * @param {String} content
190 insertContent(content) {
191 this.#replaceSelection(content, content.length);
195 * Prepend content to the editor.
196 * @param {String} content
198 prependContent(content) {
199 content = this.#cleanTextForEditor(content);
200 const selectionRange = this.#getSelectionRange();
201 const selectFrom = selectionRange.from + content.length + 1;
202 this.#dispatchChange(0, 0, `${content}\n`, selectFrom);
207 * Append content to the editor.
208 * @param {String} content
210 appendContent(content) {
211 content = this.#cleanTextForEditor(content);
212 this.#dispatchChange(this.editor.cm.state.doc.length, `\n${content}`);
217 * Replace the editor's contents
218 * @param {String} content
220 replaceContent(content) {
221 this.#setText(content);
225 * Replace the start of the line
226 * @param {String} newStart
228 replaceLineStart(newStart) {
229 const selectionRange = this.#getSelectionRange();
230 const line = this.editor.cm.state.doc.lineAt(selectionRange.from);
232 const lineContent = line.text;
233 const lineStart = lineContent.split(' ')[0];
235 // Remove symbol if already set
236 if (lineStart === newStart) {
237 const newLineContent = lineContent.replace(`${newStart} `, '');
238 const selectFrom = selectionRange.from + (newLineContent.length - lineContent.length);
239 this.#dispatchChange(line.from, line.to, newLineContent, selectFrom);
243 let newLineContent = lineContent;
244 const alreadySymbol = /^[#>`]/.test(lineStart);
246 newLineContent = lineContent.replace(lineStart, newStart).trim();
247 } else if (newStart !== '') {
248 newLineContent = `${newStart} ${lineContent}`;
251 const selectFrom = selectionRange.from + (newLineContent.length - lineContent.length);
252 this.#dispatchChange(line.from, line.to, newLineContent, selectFrom);
256 * Wrap the selection in the given contents start and end contents.
257 * @param {String} start
258 * @param {String} end
260 wrapSelection(start, end) {
261 const selectRange = this.#getSelectionRange();
262 const selectionText = this.#getSelectionText(selectRange);
263 if (!selectionText) {
264 this.#wrapLine(start, end);
268 let newSelectionText = selectionText;
271 if (selectionText.startsWith(start) && selectionText.endsWith(end)) {
272 newSelectionText = selectionText.slice(start.length, selectionText.length - end.length);
273 newRange = selectRange.extend(selectRange.from, selectRange.to - (start.length + end.length));
275 newSelectionText = `${start}${selectionText}${end}`;
276 newRange = selectRange.extend(selectRange.from, selectRange.to + (start.length + end.length));
279 this.#dispatchChange(
288 replaceLineStartForOrderedList() {
289 const selectionRange = this.#getSelectionRange();
290 const line = this.editor.cm.state.doc.lineAt(selectionRange.from);
291 const prevLine = this.editor.cm.state.doc.line(line.number - 1);
293 const listMatch = prevLine.text.match(/^(\s*)(\d)([).])\s/) || [];
295 const number = (Number(listMatch[2]) || 0) + 1;
296 const whiteSpace = listMatch[1] || '';
297 const listMark = listMatch[3] || '.';
299 const prefix = `${whiteSpace}${number}${listMark}`;
300 return this.replaceLineStart(prefix);
304 * Cycles through the type of callout block within the selection.
305 * Creates a callout block if none existing, and removes it if cycling past the danger type.
307 cycleCalloutTypeAtSelection() {
308 const selectionRange = this.#getSelectionRange();
309 const line = this.editor.cm.state.doc.lineAt(selectionRange.from);
311 const formats = ['info', 'success', 'warning', 'danger'];
312 const joint = formats.join('|');
313 const regex = new RegExp(`class="((${joint})\\s+callout|callout\\s+(${joint}))"`, 'i');
314 const matches = regex.exec(line.text);
315 const format = (matches ? (matches[2] || matches[3]) : '').toLowerCase();
317 if (format === formats[formats.length - 1]) {
318 this.#wrapLine(`<p class="callout ${formats[formats.length - 1]}">`, '</p>');
319 } else if (format === '') {
320 this.#wrapLine('<p class="callout info">', '</p>');
322 const newFormatIndex = formats.indexOf(format) + 1;
323 const newFormat = formats[newFormatIndex];
324 const newContent = line.text.replace(matches[0], matches[0].replace(format, newFormat));
325 const lineDiff = newContent.length - line.text.length;
326 this.#dispatchChange(
330 selectionRange.anchor + lineDiff,
331 selectionRange.head + lineDiff,
336 syncDisplayPosition(event) {
337 // Thanks to http://liuhao.im/english/2015/11/10/the-sync-scroll-of-markdown-editor-in-javascript.html
338 const scrollEl = event.target;
339 const atEnd = Math.abs(scrollEl.scrollHeight - scrollEl.clientHeight - scrollEl.scrollTop) < 1;
341 this.editor.display.scrollToIndex(-1);
345 const blockInfo = this.editor.cm.lineBlockAtHeight(scrollEl.scrollTop);
346 const range = this.editor.cm.state.sliceDoc(0, blockInfo.from);
347 const parser = new DOMParser();
348 const doc = parser.parseFromString(this.editor.markdown.render(range), 'text/html');
349 const totalLines = doc.documentElement.querySelectorAll('body > *');
350 this.editor.display.scrollToIndex(totalLines.length);
354 * Fetch and insert the template of the given ID.
355 * The page-relative position provided can be used to determine insert location if possible.
356 * @param {String} templateId
357 * @param {Number} posX
358 * @param {Number} posY
360 async insertTemplate(templateId, posX, posY) {
361 const cursorPos = this.editor.cm.posAtCoords({x: posX, y: posY}, false);
362 const {data} = await window.$http.get(`/templates/${templateId}`);
363 const content = data.markdown || data.html;
364 this.#dispatchChange(cursorPos, cursorPos, content, cursorPos);
368 * Insert multiple images from the clipboard from an event at the provided
369 * screen coordinates (Typically form a paste event).
370 * @param {File[]} images
371 * @param {Number} posX
372 * @param {Number} posY
374 insertClipboardImages(images, posX, posY) {
375 const cursorPos = this.editor.cm.posAtCoords({x: posX, y: posY}, false);
376 for (const image of images) {
377 this.uploadImage(image, cursorPos);
382 * Handle image upload and add image into markdown content
384 * @param {?Number} position
386 async uploadImage(file, position = null) {
387 if (file === null || file.type.indexOf('image') !== 0) return;
390 if (position === null) {
391 position = this.#getSelectionRange().from;
395 const fileNameMatches = file.name.match(/\.(.+)$/);
396 if (fileNameMatches.length > 1) ext = fileNameMatches[1];
399 // Insert image into markdown
400 const id = `image-${Math.random().toString(16).slice(2)}`;
401 const placeholderImage = window.baseUrl(`/loading.gif#upload${id}`);
402 const placeHolderText = ``;
403 this.#dispatchChange(position, position, placeHolderText, position);
405 const remoteFilename = `image-${Date.now()}.${ext}`;
406 const formData = new FormData();
407 formData.append('file', file, remoteFilename);
408 formData.append('uploaded_to', this.editor.config.pageId);
411 const {data} = await window.$http.post('/images/gallery', formData);
412 const newContent = `[](${data.url})`;
413 this.#findAndReplaceContent(placeHolderText, newContent);
415 window.$events.emit('error', this.editor.config.text.imageUploadError);
416 this.#findAndReplaceContent(placeHolderText, '');
422 * Get the current text of the editor instance.
426 return this.editor.cm.state.doc.toString();
430 * Set the text of the current editor instance.
431 * @param {String} text
432 * @param {?SelectionRange} selectionRange
434 #setText(text, selectionRange = null) {
435 selectionRange = selectionRange || this.#getSelectionRange();
436 this.#dispatchChange(0, this.editor.cm.state.doc.length, text, selectionRange.from);
441 * Replace the current selection and focus the editor.
442 * Takes an offset for the cursor, after the change, relative to the start of the provided string.
443 * Can be provided a selection range to use instead of the current selection range.
444 * @param {String} newContent
445 * @param {Number} cursorOffset
446 * @param {?SelectionRange} selectionRange
448 #replaceSelection(newContent, cursorOffset = 0, selectionRange = null) {
449 selectionRange = selectionRange || this.editor.cm.state.selection.main;
450 const selectFrom = selectionRange.from + cursorOffset;
451 this.#dispatchChange(selectionRange.from, selectionRange.to, newContent, selectFrom);
456 * Get the text content of the main current selection.
457 * @param {SelectionRange} selectionRange
460 #getSelectionText(selectionRange = null) {
461 selectionRange = selectionRange || this.#getSelectionRange();
462 return this.editor.cm.state.sliceDoc(selectionRange.from, selectionRange.to);
466 * Get the range of the current main selection.
467 * @return {SelectionRange}
469 #getSelectionRange() {
470 return this.editor.cm.state.selection.main;
474 * Cleans the given text to work with the editor.
475 * Standardises line endings to what's expected.
476 * @param {String} text
479 #cleanTextForEditor(text) {
480 return text.replace(/\r\n|\r/g, '\n');
484 * Find and replace the first occurrence of [search] with [replace]
485 * @param {String} search
486 * @param {String} replace
488 #findAndReplaceContent(search, replace) {
489 const newText = this.#getText().replace(search, replace);
490 this.#setText(newText);
494 * Wrap the line in the given start and end contents.
495 * @param {String} start
496 * @param {String} end
498 #wrapLine(start, end) {
499 const selectionRange = this.#getSelectionRange();
500 const line = this.editor.cm.state.doc.lineAt(selectionRange.from);
501 const lineContent = line.text;
505 if (lineContent.startsWith(start) && lineContent.endsWith(end)) {
506 newLineContent = lineContent.slice(start.length, lineContent.length - end.length);
507 lineOffset = -(start.length);
509 newLineContent = `${start}${lineContent}${end}`;
510 lineOffset = start.length;
513 this.#dispatchChange(line.from, line.to, newLineContent, selectionRange.from + lineOffset);
517 * Dispatch changes to the editor.
518 * @param {Number} from
519 * @param {?Number} to
520 * @param {?String} text
521 * @param {?Number} selectFrom
522 * @param {?Number} selectTo
524 #dispatchChange(from, to = null, text = null, selectFrom = null, selectTo = null) {
525 const tr = {changes: {from, to, insert: text}};
528 tr.selection = {anchor: selectFrom};
530 tr.selection.head = selectTo;
534 this.editor.cm.dispatch(tr);
538 * Set the current selection range.
539 * Optionally will scroll the new range into view.
540 * @param {Number} from
542 * @param {Boolean} scrollIntoView
544 #setSelection(from, to, scrollIntoView = false) {
545 this.editor.cm.dispatch({
546 selection: {anchor: from, head: to},