1 import 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);
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 selectionRange = this.#getSelectionRange();
262 const selectionText = this.#getSelectionText(selectionRange);
263 if (!selectionText) return this.#wrapLine(start, end);
265 let newSelectionText = selectionText;
268 if (selectionText.startsWith(start) && selectionText.endsWith(end)) {
269 newSelectionText = selectionText.slice(start.length, selectionText.length - end.length);
270 newRange = selectionRange.extend(selectionRange.from, selectionRange.to - (start.length + end.length));
272 newSelectionText = `${start}${selectionText}${end}`;
273 newRange = selectionRange.extend(selectionRange.from, selectionRange.to + (start.length + end.length));
276 this.#dispatchChange(selectionRange.from, selectionRange.to, newSelectionText, newRange.anchor, newRange.head);
279 replaceLineStartForOrderedList() {
280 const selectionRange = this.#getSelectionRange();
281 const line = this.editor.cm.state.doc.lineAt(selectionRange.from);
282 const prevLine = this.editor.cm.state.doc.line(line.number - 1);
284 const listMatch = prevLine.text.match(/^(\s*)(\d)([).])\s/) || [];
286 const number = (Number(listMatch[2]) || 0) + 1;
287 const whiteSpace = listMatch[1] || '';
288 const listMark = listMatch[3] || '.';
290 const prefix = `${whiteSpace}${number}${listMark}`;
291 return this.replaceLineStart(prefix);
295 * Cycles through the type of callout block within the selection.
296 * Creates a callout block if none existing, and removes it if cycling past the danger type.
298 cycleCalloutTypeAtSelection() {
299 const selectionRange = this.#getSelectionRange();
300 const line = this.editor.cm.state.doc.lineAt(selectionRange.from);
302 const formats = ['info', 'success', 'warning', 'danger'];
303 const joint = formats.join('|');
304 const regex = new RegExp(`class="((${joint})\\s+callout|callout\\s+(${joint}))"`, 'i');
305 const matches = regex.exec(line.text);
306 const format = (matches ? (matches[2] || matches[3]) : '').toLowerCase();
308 if (format === formats[formats.length - 1]) {
309 this.#wrapLine(`<p class="callout ${formats[formats.length - 1]}">`, '</p>');
310 } else if (format === '') {
311 this.#wrapLine('<p class="callout info">', '</p>');
313 const newFormatIndex = formats.indexOf(format) + 1;
314 const newFormat = formats[newFormatIndex];
315 const newContent = line.text.replace(matches[0], matches[0].replace(format, newFormat));
316 const lineDiff = newContent.length - line.text.length;
317 this.#dispatchChange(line.from, line.to, newContent, selectionRange.anchor + lineDiff, selectionRange.head + lineDiff);
321 syncDisplayPosition(event) {
322 // Thanks to http://liuhao.im/english/2015/11/10/the-sync-scroll-of-markdown-editor-in-javascript.html
323 const scrollEl = event.target;
324 const atEnd = Math.abs(scrollEl.scrollHeight - scrollEl.clientHeight - scrollEl.scrollTop) < 1;
326 this.editor.display.scrollToIndex(-1);
330 const blockInfo = this.editor.cm.lineBlockAtHeight(scrollEl.scrollTop);
331 const range = this.editor.cm.state.sliceDoc(0, blockInfo.from);
332 const parser = new DOMParser();
333 const doc = parser.parseFromString(this.editor.markdown.render(range), 'text/html');
334 const totalLines = doc.documentElement.querySelectorAll('body > *');
335 this.editor.display.scrollToIndex(totalLines.length);
339 * Fetch and insert the template of the given ID.
340 * The page-relative position provided can be used to determine insert location if possible.
341 * @param {String} templateId
342 * @param {Number} posX
343 * @param {Number} posY
345 async insertTemplate(templateId, posX, posY) {
346 const cursorPos = this.editor.cm.posAtCoords({x: posX, y: posY}, false);
347 const {data} = await window.$http.get(`/templates/${templateId}`);
348 const content = data.markdown || data.html;
349 this.#dispatchChange(cursorPos, cursorPos, content, cursorPos);
353 * Insert multiple images from the clipboard from an event at the provided
354 * screen coordinates (Typically form a paste event).
355 * @param {File[]} images
356 * @param {Number} posX
357 * @param {Number} posY
359 insertClipboardImages(images, posX, posY) {
360 const cursorPos = this.editor.cm.posAtCoords({x: posX, y: posY}, false);
361 for (const image of images) {
362 this.uploadImage(image, cursorPos);
367 * Handle image upload and add image into markdown content
369 * @param {?Number} position
371 async uploadImage(file, position = null) {
372 if (file === null || file.type.indexOf('image') !== 0) return;
375 if (position === null) {
376 position = this.#getSelectionRange().from;
380 const fileNameMatches = file.name.match(/\.(.+)$/);
381 if (fileNameMatches.length > 1) ext = fileNameMatches[1];
384 // Insert image into markdown
385 const id = `image-${Math.random().toString(16).slice(2)}`;
386 const placeholderImage = window.baseUrl(`/loading.gif#upload${id}`);
387 const placeHolderText = ``;
388 this.#dispatchChange(position, position, placeHolderText, position);
390 const remoteFilename = `image-${Date.now()}.${ext}`;
391 const formData = new FormData();
392 formData.append('file', file, remoteFilename);
393 formData.append('uploaded_to', this.editor.config.pageId);
396 const {data} = await window.$http.post('/images/gallery', formData);
397 const newContent = `[](${data.url})`;
398 this.#findAndReplaceContent(placeHolderText, newContent);
400 window.$events.emit('error', this.editor.config.text.imageUploadError);
401 this.#findAndReplaceContent(placeHolderText, '');
407 * Get the current text of the editor instance.
411 return this.editor.cm.state.doc.toString();
415 * Set the text of the current editor instance.
416 * @param {String} text
417 * @param {?SelectionRange} selectionRange
419 #setText(text, selectionRange = null) {
420 selectionRange = selectionRange || this.#getSelectionRange();
421 this.#dispatchChange(0, this.editor.cm.state.doc.length, text, selectionRange.from);
426 * Replace the current selection and focus the editor.
427 * Takes an offset for the cursor, after the change, relative to the start of the provided string.
428 * Can be provided a selection range to use instead of the current selection range.
429 * @param {String} newContent
430 * @param {Number} cursorOffset
431 * @param {?SelectionRange} selectionRange
433 #replaceSelection(newContent, cursorOffset = 0, selectionRange = null) {
434 selectionRange = selectionRange || this.editor.cm.state.selection.main;
435 this.#dispatchChange(selectionRange.from, selectionRange.to, newContent, selectionRange.from + cursorOffset);
440 * Get the text content of the main current selection.
441 * @param {SelectionRange} selectionRange
444 #getSelectionText(selectionRange = null) {
445 selectionRange = selectionRange || this.#getSelectionRange();
446 return this.editor.cm.state.sliceDoc(selectionRange.from, selectionRange.to);
450 * Get the range of the current main selection.
451 * @return {SelectionRange}
453 #getSelectionRange() {
454 return this.editor.cm.state.selection.main;
458 * Cleans the given text to work with the editor.
459 * Standardises line endings to what's expected.
460 * @param {String} text
463 #cleanTextForEditor(text) {
464 return text.replace(/\r\n|\r/g, '\n');
468 * Find and replace the first occurrence of [search] with [replace]
469 * @param {String} search
470 * @param {String} replace
472 #findAndReplaceContent(search, replace) {
473 const newText = this.#getText().replace(search, replace);
474 this.#setText(newText);
478 * Wrap the line in the given start and end contents.
479 * @param {String} start
480 * @param {String} end
482 #wrapLine(start, end) {
483 const selectionRange = this.#getSelectionRange();
484 const line = this.editor.cm.state.doc.lineAt(selectionRange.from);
485 const lineContent = line.text;
489 if (lineContent.startsWith(start) && lineContent.endsWith(end)) {
490 newLineContent = lineContent.slice(start.length, lineContent.length - end.length);
491 lineOffset = -(start.length);
493 newLineContent = `${start}${lineContent}${end}`;
494 lineOffset = start.length;
497 this.#dispatchChange(line.from, line.to, newLineContent, selectionRange.from + lineOffset);
501 * Dispatch changes to the editor.
502 * @param {Number} from
503 * @param {?Number} to
504 * @param {?String} text
505 * @param {?Number} selectFrom
506 * @param {?Number} selectTo
508 #dispatchChange(from, to = null, text = null, selectFrom = null, selectTo = null) {
509 const tr = {changes: {from, to, insert: text}};
512 tr.selection = {anchor: selectFrom};
515 this.editor.cm.dispatch(tr);
519 * Set the current selection range.
520 * Optionally will scroll the new range into view.
521 * @param {Number} from
523 * @param {Boolean} scrollIntoView
525 #setSelection(from, to, scrollIntoView = false) {
526 this.editor.cm.dispatch({
527 selection: {anchor: from, head: to},