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 const selectionText = this.#getSelectionText(selectionRange);
72 selector.show(entity => {
73 const selectedText = selectionText || entity.name;
74 const newText = `[${selectedText}](${entity.link})`;
75 this.#replaceSelection(newText, newText.length, selectionRange);
77 searchEndpoint: '/search/entity-selector',
78 entityTypes: 'page,book,chapter,bookshelf',
79 entityPermission: 'view',
83 // Show draw.io if enabled and handle save.
85 const url = this.editor.config.drawioUrl;
88 const selectionRange = this.#getSelectionRange();
90 DrawIO.show(url, () => Promise.resolve(''), async pngData => {
93 uploaded_to: Number(this.editor.config.pageId),
97 const resp = await window.$http.post('/images/drawio', data);
98 this.#insertDrawing(resp.data, selectionRange);
101 this.handleDrawingUploadError(err);
102 throw new Error(`Failed to save image with error: ${err}`);
107 #insertDrawing(image, originalSelectionRange) {
108 const newText = `<div drawio-diagram="${image.id}"><img src="${image.url}"></div>`;
109 this.#replaceSelection(newText, newText.length, originalSelectionRange);
112 // Show draw.io if enabled and handle save.
113 editDrawing(imgContainer) {
114 const {drawioUrl} = this.editor.config;
119 const selectionRange = this.#getSelectionRange();
120 const drawingId = imgContainer.getAttribute('drawio-diagram');
122 DrawIO.show(drawioUrl, () => DrawIO.load(drawingId), async pngData => {
125 uploaded_to: Number(this.editor.config.pageId),
129 const resp = await window.$http.post('/images/drawio', data);
130 const newText = `<div drawio-diagram="${resp.data.id}"><img src="${resp.data.url}"></div>`;
131 const newContent = this.#getText().split('\n').map(line => {
132 if (line.indexOf(`drawio-diagram="${drawingId}"`) !== -1) {
137 this.#setText(newContent, selectionRange);
140 this.handleDrawingUploadError(err);
141 throw new Error(`Failed to save image with error: ${err}`);
146 handleDrawingUploadError(error) {
147 if (error.status === 413) {
148 window.$events.emit('error', this.editor.config.text.serverUploadLimit);
150 window.$events.emit('error', this.editor.config.text.imageUploadError);
152 console.error(error);
155 // Make the editor full screen
157 const {container} = this.editor.config;
158 const alreadyFullscreen = container.classList.contains('fullscreen');
159 container.classList.toggle('fullscreen', !alreadyFullscreen);
160 document.body.classList.toggle('markdown-fullscreen', !alreadyFullscreen);
163 // Scroll to a specified text
164 scrollToText(searchText) {
169 const text = this.editor.cm.state.doc;
171 let scrollToLine = -1;
172 for (const line of text.iterLines()) {
173 if (line.includes(searchText)) {
174 scrollToLine = lineCount;
180 if (scrollToLine === -1) {
184 const line = text.line(scrollToLine);
185 this.#setSelection(line.from, line.to, true);
190 if (!this.editor.cm.hasFocus) {
191 this.editor.cm.focus();
196 * Insert content into the editor.
197 * @param {String} content
199 insertContent(content) {
200 this.#replaceSelection(content, content.length);
204 * Prepend content to the editor.
205 * @param {String} content
207 prependContent(content) {
208 content = this.#cleanTextForEditor(content);
209 const selectionRange = this.#getSelectionRange();
210 const selectFrom = selectionRange.from + content.length + 1;
211 this.#dispatchChange(0, 0, `${content}\n`, selectFrom);
216 * Append content to the editor.
217 * @param {String} content
219 appendContent(content) {
220 content = this.#cleanTextForEditor(content);
221 this.#dispatchChange(this.editor.cm.state.doc.length, `\n${content}`);
226 * Replace the editor's contents
227 * @param {String} content
229 replaceContent(content) {
230 this.#setText(content);
234 * Replace the start of the line
235 * @param {String} newStart
237 replaceLineStart(newStart) {
238 const selectionRange = this.#getSelectionRange();
239 const line = this.editor.cm.state.doc.lineAt(selectionRange.from);
241 const lineContent = line.text;
242 const lineStart = lineContent.split(' ')[0];
244 // Remove symbol if already set
245 if (lineStart === newStart) {
246 const newLineContent = lineContent.replace(`${newStart} `, '');
247 const selectFrom = selectionRange.from + (newLineContent.length - lineContent.length);
248 this.#dispatchChange(line.from, line.to, newLineContent, selectFrom);
252 let newLineContent = lineContent;
253 const alreadySymbol = /^[#>`]/.test(lineStart);
255 newLineContent = lineContent.replace(lineStart, newStart).trim();
256 } else if (newStart !== '') {
257 newLineContent = `${newStart} ${lineContent}`;
260 const selectFrom = selectionRange.from + (newLineContent.length - lineContent.length);
261 this.#dispatchChange(line.from, line.to, newLineContent, selectFrom);
265 * Wrap the selection in the given contents start and end contents.
266 * @param {String} start
267 * @param {String} end
269 wrapSelection(start, end) {
270 const selectRange = this.#getSelectionRange();
271 const selectionText = this.#getSelectionText(selectRange);
272 if (!selectionText) {
273 this.#wrapLine(start, end);
277 let newSelectionText = selectionText;
280 if (selectionText.startsWith(start) && selectionText.endsWith(end)) {
281 newSelectionText = selectionText.slice(start.length, selectionText.length - end.length);
282 newRange = selectRange.extend(selectRange.from, selectRange.to - (start.length + end.length));
284 newSelectionText = `${start}${selectionText}${end}`;
285 newRange = selectRange.extend(selectRange.from, selectRange.to + (start.length + end.length));
288 this.#dispatchChange(
297 replaceLineStartForOrderedList() {
298 const selectionRange = this.#getSelectionRange();
299 const line = this.editor.cm.state.doc.lineAt(selectionRange.from);
300 const prevLine = this.editor.cm.state.doc.line(line.number - 1);
302 const listMatch = prevLine.text.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() {
317 const selectionRange = this.#getSelectionRange();
318 const line = this.editor.cm.state.doc.lineAt(selectionRange.from);
320 const formats = ['info', 'success', 'warning', 'danger'];
321 const joint = formats.join('|');
322 const regex = new RegExp(`class="((${joint})\\s+callout|callout\\s+(${joint}))"`, 'i');
323 const matches = regex.exec(line.text);
324 const format = (matches ? (matches[2] || matches[3]) : '').toLowerCase();
326 if (format === formats[formats.length - 1]) {
327 this.#wrapLine(`<p class="callout ${formats[formats.length - 1]}">`, '</p>');
328 } else if (format === '') {
329 this.#wrapLine('<p class="callout info">', '</p>');
331 const newFormatIndex = formats.indexOf(format) + 1;
332 const newFormat = formats[newFormatIndex];
333 const newContent = line.text.replace(matches[0], matches[0].replace(format, newFormat));
334 const lineDiff = newContent.length - line.text.length;
335 this.#dispatchChange(
339 selectionRange.anchor + lineDiff,
340 selectionRange.head + lineDiff,
345 syncDisplayPosition(event) {
346 // Thanks to http://liuhao.im/english/2015/11/10/the-sync-scroll-of-markdown-editor-in-javascript.html
347 const scrollEl = event.target;
348 const atEnd = Math.abs(scrollEl.scrollHeight - scrollEl.clientHeight - scrollEl.scrollTop) < 1;
350 this.editor.display.scrollToIndex(-1);
354 const blockInfo = this.editor.cm.lineBlockAtHeight(scrollEl.scrollTop);
355 const range = this.editor.cm.state.sliceDoc(0, blockInfo.from);
356 const parser = new DOMParser();
357 const doc = parser.parseFromString(this.editor.markdown.render(range), 'text/html');
358 const totalLines = doc.documentElement.querySelectorAll('body > *');
359 this.editor.display.scrollToIndex(totalLines.length);
363 * Fetch and insert the template of the given ID.
364 * The page-relative position provided can be used to determine insert location if possible.
365 * @param {String} templateId
366 * @param {Number} posX
367 * @param {Number} posY
369 async insertTemplate(templateId, posX, posY) {
370 const cursorPos = this.editor.cm.posAtCoords({x: posX, y: posY}, false);
371 const {data} = await window.$http.get(`/templates/${templateId}`);
372 const content = data.markdown || data.html;
373 this.#dispatchChange(cursorPos, cursorPos, content, cursorPos);
377 * Insert multiple images from the clipboard from an event at the provided
378 * screen coordinates (Typically form a paste event).
379 * @param {File[]} images
380 * @param {Number} posX
381 * @param {Number} posY
383 insertClipboardImages(images, posX, posY) {
384 const cursorPos = this.editor.cm.posAtCoords({x: posX, y: posY}, false);
385 for (const image of images) {
386 this.uploadImage(image, cursorPos);
391 * Handle image upload and add image into markdown content
393 * @param {?Number} position
395 async uploadImage(file, position = null) {
396 if (file === null || file.type.indexOf('image') !== 0) return;
399 if (position === null) {
400 position = this.#getSelectionRange().from;
404 const fileNameMatches = file.name.match(/\.(.+)$/);
405 if (fileNameMatches.length > 1) ext = fileNameMatches[1];
408 // Insert image into markdown
409 const id = `image-${Math.random().toString(16).slice(2)}`;
410 const placeholderImage = window.baseUrl(`/loading.gif#upload${id}`);
411 const placeHolderText = ``;
412 this.#dispatchChange(position, position, placeHolderText, position);
414 const remoteFilename = `image-${Date.now()}.${ext}`;
415 const formData = new FormData();
416 formData.append('file', file, remoteFilename);
417 formData.append('uploaded_to', this.editor.config.pageId);
420 const {data} = await window.$http.post('/images/gallery', formData);
421 const newContent = `[](${data.url})`;
422 this.#findAndReplaceContent(placeHolderText, newContent);
424 window.$events.error(err?.data?.message || this.editor.config.text.imageUploadError);
425 this.#findAndReplaceContent(placeHolderText, '');
431 * Get the current text of the editor instance.
435 return this.editor.cm.state.doc.toString();
439 * Set the text of the current editor instance.
440 * @param {String} text
441 * @param {?SelectionRange} selectionRange
443 #setText(text, selectionRange = null) {
444 selectionRange = selectionRange || this.#getSelectionRange();
445 const newDoc = this.editor.cm.state.toText(text);
446 const newSelectFrom = Math.min(selectionRange.from, newDoc.length);
447 this.#dispatchChange(0, this.editor.cm.state.doc.length, text, newSelectFrom);
452 * Replace the current selection and focus the editor.
453 * Takes an offset for the cursor, after the change, relative to the start of the provided string.
454 * Can be provided a selection range to use instead of the current selection range.
455 * @param {String} newContent
456 * @param {Number} cursorOffset
457 * @param {?SelectionRange} selectionRange
459 #replaceSelection(newContent, cursorOffset = 0, selectionRange = null) {
460 selectionRange = selectionRange || this.editor.cm.state.selection.main;
461 const selectFrom = selectionRange.from + cursorOffset;
462 this.#dispatchChange(selectionRange.from, selectionRange.to, newContent, selectFrom);
467 * Get the text content of the main current selection.
468 * @param {SelectionRange} selectionRange
471 #getSelectionText(selectionRange = null) {
472 selectionRange = selectionRange || this.#getSelectionRange();
473 return this.editor.cm.state.sliceDoc(selectionRange.from, selectionRange.to);
477 * Get the range of the current main selection.
478 * @return {SelectionRange}
480 #getSelectionRange() {
481 return this.editor.cm.state.selection.main;
485 * Cleans the given text to work with the editor.
486 * Standardises line endings to what's expected.
487 * @param {String} text
490 #cleanTextForEditor(text) {
491 return text.replace(/\r\n|\r/g, '\n');
495 * Find and replace the first occurrence of [search] with [replace]
496 * @param {String} search
497 * @param {String} replace
499 #findAndReplaceContent(search, replace) {
500 const newText = this.#getText().replace(search, replace);
501 this.#setText(newText);
505 * Wrap the line in the given start and end contents.
506 * @param {String} start
507 * @param {String} end
509 #wrapLine(start, end) {
510 const selectionRange = this.#getSelectionRange();
511 const line = this.editor.cm.state.doc.lineAt(selectionRange.from);
512 const lineContent = line.text;
516 if (lineContent.startsWith(start) && lineContent.endsWith(end)) {
517 newLineContent = lineContent.slice(start.length, lineContent.length - end.length);
518 lineOffset = -(start.length);
520 newLineContent = `${start}${lineContent}${end}`;
521 lineOffset = start.length;
524 this.#dispatchChange(line.from, line.to, newLineContent, selectionRange.from + lineOffset);
528 * Dispatch changes to the editor.
529 * @param {Number} from
530 * @param {?Number} to
531 * @param {?String} text
532 * @param {?Number} selectFrom
533 * @param {?Number} selectTo
535 #dispatchChange(from, to = null, text = null, selectFrom = null, selectTo = null) {
536 const tr = {changes: {from, to, insert: text}};
539 tr.selection = {anchor: selectFrom};
541 tr.selection.head = selectTo;
545 this.editor.cm.dispatch(tr);
549 * Set the current selection range.
550 * Optionally will scroll the new range into view.
551 * @param {Number} from
553 * @param {Boolean} scrollIntoView
555 #setSelection(from, to, scrollIntoView = false) {
556 this.editor.cm.dispatch({
557 selection: {anchor: from, head: to},