1 import MarkdownIt from "markdown-it";
2 import mdTasksLists from 'markdown-it-task-lists';
3 import code from '../services/code';
4 import Clipboard from "../services/clipboard";
5 import {debounce} from "../services/util";
7 import DrawIO from "../services/drawio";
14 this.pageId = this.$opts.pageId;
15 this.textDirection = this.$opts.textDirection;
16 this.imageUploadErrorText = this.$opts.imageUploadErrorText;
18 this.markdown = new MarkdownIt({html: true});
19 this.markdown.use(mdTasksLists, {label: true});
21 this.display = this.elem.querySelector('.markdown-display');
23 this.displayStylesLoaded = false;
24 this.input = this.elem.querySelector('textarea');
25 this.htmlInput = this.elem.querySelector('input[name=html]');
26 this.cm = code.markdownEditor(this.input);
28 this.onMarkdownScroll = this.onMarkdownScroll.bind(this);
30 const displayLoad = () => {
31 this.displayDoc = this.display.contentDocument;
35 if (this.display.contentDocument.readyState === 'complete') {
38 this.display.addEventListener('load', displayLoad.bind(this));
41 window.$events.emitPublic(this.elem, 'editor-markdown::setup', {
42 markdownIt: this.markdown,
43 displayEl: this.display,
44 codeMirrorInstance: this.cm,
52 // Prevent markdown display link click redirect
53 this.displayDoc.addEventListener('click', event => {
54 let isDblClick = Date.now() - lastClick < 300;
56 let link = event.target.closest('a');
58 event.preventDefault();
59 window.open(link.getAttribute('href'));
63 let drawing = event.target.closest('[drawio-diagram]');
64 if (drawing !== null && isDblClick) {
65 this.actionEditDrawing(drawing);
69 lastClick = Date.now();
73 this.elem.addEventListener('click', event => {
74 let button = event.target.closest('button[data-action]');
75 if (button === null) return;
77 let action = button.getAttribute('data-action');
78 if (action === 'insertImage') this.actionInsertImage();
79 if (action === 'insertLink') this.actionShowLinkSelector();
80 if (action === 'insertDrawing' && (event.ctrlKey || event.metaKey)) {
81 this.actionShowImageManager();
84 if (action === 'insertDrawing') this.actionStartDrawing();
85 if (action === 'fullscreen') this.actionFullScreen();
88 // Mobile section toggling
89 this.elem.addEventListener('click', event => {
90 const toolbarLabel = event.target.closest('.editor-toolbar-label');
91 if (!toolbarLabel) return;
93 const currentActiveSections = this.elem.querySelectorAll('.markdown-editor-wrap');
94 for (let activeElem of currentActiveSections) {
95 activeElem.classList.remove('active');
98 toolbarLabel.closest('.markdown-editor-wrap').classList.add('active');
101 window.$events.listen('editor-markdown-update', value => {
102 this.cm.setValue(value);
103 this.updateAndRender();
106 this.codeMirrorSetup();
107 this.listenForBookStackEditorEvents();
109 // Scroll to text if needed.
110 const queryParams = (new URL(window.location)).searchParams;
111 const scrollText = queryParams.get('content-text');
113 this.scrollToText(scrollText);
117 // Update the input content and render the display.
119 const content = this.cm.getValue();
120 this.input.value = content;
121 const html = this.markdown.render(content);
122 window.$events.emit('editor-html-change', html);
123 window.$events.emit('editor-markdown-change', content);
126 this.displayDoc.body.className = 'page-content';
127 this.displayDoc.body.innerHTML = html;
128 this.htmlInput.value = html;
130 // Copy styles from page head and set custom styles for editor
131 this.loadStylesIntoDisplay();
134 loadStylesIntoDisplay() {
135 if (this.displayStylesLoaded) return;
136 this.displayDoc.documentElement.classList.add('markdown-editor-display');
137 // Set display to be dark mode if parent is
139 if (document.documentElement.classList.contains('dark-mode')) {
140 this.displayDoc.documentElement.style.backgroundColor = '#222';
141 this.displayDoc.documentElement.classList.add('dark-mode');
144 this.displayDoc.head.innerHTML = '';
145 const styles = document.head.querySelectorAll('style,link[rel=stylesheet]');
146 for (let style of styles) {
147 const copy = style.cloneNode(true);
148 this.displayDoc.head.appendChild(copy);
151 this.displayStylesLoaded = true;
154 onMarkdownScroll(lineCount) {
155 const elems = this.displayDoc.body.children;
156 if (elems.length <= lineCount) return;
158 const topElem = (lineCount === -1) ? elems[elems.length-1] : elems[lineCount];
159 topElem.scrollIntoView({ block: 'start', inline: 'nearest', behavior: 'smooth'});
164 const context = this;
167 // cm.setOption('direction', this.textDirection);
168 cm.setOption('direction', 'ltr'); // Will force to remain as ltr for now due to issues when HTML is in editor.
169 // Custom key commands
170 let metaKey = code.getMetaKey();
171 const extraKeys = {};
172 // Insert Image shortcut
173 extraKeys[`${metaKey}-Alt-I`] = function(cm) {
174 let selectedText = cm.getSelection();
175 let newText = ``;
176 let cursorPos = cm.getCursor('from');
177 cm.replaceSelection(newText);
178 cm.setCursor(cursorPos.line, cursorPos.ch + newText.length -1);
181 extraKeys[`${metaKey}-S`] = cm => {window.$events.emit('editor-save-draft')};
183 extraKeys[`${metaKey}-Enter`] = cm => {window.$events.emit('editor-save-page')};
184 // Show link selector
185 extraKeys[`Shift-${metaKey}-K`] = cm => {this.actionShowLinkSelector()};
187 extraKeys[`${metaKey}-K`] = cm => {insertLink()};
189 extraKeys[`${metaKey}-1`] = cm => {replaceLineStart('##');};
190 extraKeys[`${metaKey}-2`] = cm => {replaceLineStart('###');};
191 extraKeys[`${metaKey}-3`] = cm => {replaceLineStart('####');};
192 extraKeys[`${metaKey}-4`] = cm => {replaceLineStart('#####');};
193 extraKeys[`${metaKey}-5`] = cm => {replaceLineStart('');};
194 extraKeys[`${metaKey}-d`] = cm => {replaceLineStart('');};
195 extraKeys[`${metaKey}-6`] = cm => {replaceLineStart('>');};
196 extraKeys[`${metaKey}-q`] = cm => {replaceLineStart('>');};
197 extraKeys[`${metaKey}-7`] = cm => {wrapSelection('\n```\n', '\n```');};
198 extraKeys[`${metaKey}-8`] = cm => {wrapSelection('`', '`');};
199 extraKeys[`Shift-${metaKey}-E`] = cm => {wrapSelection('`', '`');};
200 extraKeys[`${metaKey}-9`] = cm => {wrapSelection('<p class="callout info">', '</p>');};
201 cm.setOption('extraKeys', extraKeys);
203 // Update data on content change
204 cm.on('change', (instance, changeObj) => {
205 this.updateAndRender();
208 const onScrollDebounced = debounce((instance) => {
209 // Thanks to http://liuhao.im/english/2015/11/10/the-sync-scroll-of-markdown-editor-in-javascript.html
210 let scroll = instance.getScrollInfo();
211 let atEnd = scroll.top + scroll.clientHeight === scroll.height;
213 this.onMarkdownScroll(-1);
217 let lineNum = instance.lineAtHeight(scroll.top, 'local');
218 let range = instance.getRange({line: 0, ch: null}, {line: lineNum, ch: null});
219 let parser = new DOMParser();
220 let doc = parser.parseFromString(this.markdown.render(range), 'text/html');
221 let totalLines = doc.documentElement.querySelectorAll('body > *');
222 this.onMarkdownScroll(totalLines.length);
225 // Handle scroll to sync display view
226 cm.on('scroll', instance => {
227 onScrollDebounced(instance);
230 // Handle image paste
231 cm.on('paste', (cm, event) => {
232 const clipboard = new Clipboard(event.clipboardData || event.dataTransfer);
234 // Don't handle the event ourselves if no items exist of contains table-looking data
235 if (!clipboard.hasItems() || clipboard.containsTabularData()) {
239 const images = clipboard.getImages();
240 for (const image of images) {
245 // Handle image & content drag n drop
246 cm.on('drop', (cm, event) => {
248 const templateId = event.dataTransfer.getData('bookstack/template');
250 const cursorPos = cm.coordsChar({left: event.pageX, top: event.pageY});
251 cm.setCursor(cursorPos);
252 event.preventDefault();
253 window.$http.get(`/templates/${templateId}`).then(resp => {
254 const content = resp.data.markdown || resp.data.html;
255 cm.replaceSelection(content);
259 const clipboard = new Clipboard(event.dataTransfer);
260 if (clipboard.hasItems() && clipboard.getImages().length > 0) {
261 const cursorPos = cm.coordsChar({left: event.pageX, top: event.pageY});
262 cm.setCursor(cursorPos);
263 event.stopPropagation();
264 event.preventDefault();
265 const images = clipboard.getImages();
266 for (const image of images) {
273 // Helper to replace editor content
274 function replaceContent(search, replace) {
275 let text = cm.getValue();
276 let cursor = cm.listSelections();
277 cm.setValue(text.replace(search, replace));
278 cm.setSelections(cursor);
281 // Helper to replace the start of the line
282 function replaceLineStart(newStart) {
283 let cursor = cm.getCursor();
284 let lineContent = cm.getLine(cursor.line);
285 let lineLen = lineContent.length;
286 let lineStart = lineContent.split(' ')[0];
288 // Remove symbol if already set
289 if (lineStart === newStart) {
290 lineContent = lineContent.replace(`${newStart} `, '');
291 cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
292 cm.setCursor({line: cursor.line, ch: cursor.ch - (newStart.length + 1)});
296 let alreadySymbol = /^[#>`]/.test(lineStart);
299 posDif = newStart.length - lineStart.length;
300 lineContent = lineContent.replace(lineStart, newStart).trim();
301 } else if (newStart !== '') {
302 posDif = newStart.length + 1;
303 lineContent = newStart + ' ' + lineContent;
305 cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
306 cm.setCursor({line: cursor.line, ch: cursor.ch + posDif});
309 function wrapLine(start, end) {
310 let cursor = cm.getCursor();
311 let lineContent = cm.getLine(cursor.line);
312 let lineLen = lineContent.length;
313 let newLineContent = lineContent;
315 if (lineContent.indexOf(start) === 0 && lineContent.slice(-end.length) === end) {
316 newLineContent = lineContent.slice(start.length, lineContent.length - end.length);
318 newLineContent = `${start}${lineContent}${end}`;
321 cm.replaceRange(newLineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
322 cm.setCursor({line: cursor.line, ch: cursor.ch + start.length});
325 function wrapSelection(start, end) {
326 let selection = cm.getSelection();
327 if (selection === '') return wrapLine(start, end);
329 let newSelection = selection;
333 if (selection.indexOf(start) === 0 && selection.slice(-end.length) === end) {
334 newSelection = selection.slice(start.length, selection.length - end.length);
335 endDiff = -(end.length + start.length);
337 newSelection = `${start}${selection}${end}`;
338 endDiff = start.length + end.length;
341 let selections = cm.listSelections()[0];
342 cm.replaceSelection(newSelection);
343 let headFirst = selections.head.ch <= selections.anchor.ch;
344 selections.head.ch += headFirst ? frontDiff : endDiff;
345 selections.anchor.ch += headFirst ? endDiff : frontDiff;
346 cm.setSelections([selections]);
349 // Handle image upload and add image into markdown content
350 function uploadImage(file) {
351 if (file === null || file.type.indexOf('image') !== 0) return;
355 let fileNameMatches = file.name.match(/\.(.+)$/);
356 if (fileNameMatches.length > 1) ext = fileNameMatches[1];
359 // Insert image into markdown
360 const id = "image-" + Math.random().toString(16).slice(2);
361 const placeholderImage = window.baseUrl(`/loading.gif#upload${id}`);
362 const selectedText = cm.getSelection();
363 const placeHolderText = ``;
364 const cursor = cm.getCursor();
365 cm.replaceSelection(placeHolderText);
366 cm.setCursor({line: cursor.line, ch: cursor.ch + selectedText.length + 3});
368 const remoteFilename = "image-" + Date.now() + "." + ext;
369 const formData = new FormData();
370 formData.append('file', file, remoteFilename);
371 formData.append('uploaded_to', context.pageId);
373 window.$http.post('/images/gallery', formData).then(resp => {
374 const newContent = `[](${resp.data.url})`;
375 replaceContent(placeHolderText, newContent);
377 window.$events.emit('error', context.imageUploadErrorText);
378 replaceContent(placeHolderText, selectedText);
383 function insertLink() {
384 let cursorPos = cm.getCursor('from');
385 let selectedText = cm.getSelection() || '';
386 let newText = `[${selectedText}]()`;
388 cm.replaceSelection(newText);
389 let cursorPosDiff = (selectedText === '') ? -3 : -1;
390 cm.setCursor(cursorPos.line, cursorPos.ch + newText.length+cursorPosDiff);
393 this.updateAndRender();
396 actionInsertImage() {
397 const cursorPos = this.cm.getCursor('from');
398 window.ImageManager.show(image => {
399 let selectedText = this.cm.getSelection();
400 let newText = "[](" + image.url + ")";
402 this.cm.replaceSelection(newText);
403 this.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
407 actionShowImageManager() {
408 const cursorPos = this.cm.getCursor('from');
409 window.ImageManager.show(image => {
410 this.insertDrawing(image, cursorPos);
414 // Show the popup link selector and insert a link when finished
415 actionShowLinkSelector() {
416 const cursorPos = this.cm.getCursor('from');
417 window.EntitySelectorPopup.show(entity => {
418 let selectedText = this.cm.getSelection() || entity.name;
419 let newText = `[${selectedText}](${entity.link})`;
421 this.cm.replaceSelection(newText);
422 this.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
427 const drawioUrlElem = document.querySelector('[drawio-url]');
428 return drawioUrlElem ? drawioUrlElem.getAttribute('drawio-url') : false;
431 // Show draw.io if enabled and handle save.
432 actionStartDrawing() {
433 const url = this.getDrawioUrl();
436 const cursorPos = this.cm.getCursor('from');
438 DrawIO.show(url,() => {
439 return Promise.resolve('');
444 uploaded_to: Number(this.pageId),
447 window.$http.post("/images/drawio", data).then(resp => {
448 this.insertDrawing(resp.data, cursorPos);
451 window.$events.emit('error', trans('errors.image_upload_error'));
457 insertDrawing(image, originalCursor) {
458 const newText = `<div drawio-diagram="${image.id}"><img src="${image.url}"></div>`;
460 this.cm.replaceSelection(newText);
461 this.cm.setCursor(originalCursor.line, originalCursor.ch + newText.length);
464 // Show draw.io if enabled and handle save.
465 actionEditDrawing(imgContainer) {
466 const drawioUrl = this.getDrawioUrl();
471 const cursorPos = this.cm.getCursor('from');
472 const drawingId = imgContainer.getAttribute('drawio-diagram');
474 DrawIO.show(drawioUrl, () => {
475 return DrawIO.load(drawingId);
480 uploaded_to: Number(this.pageId),
483 window.$http.post("/images/drawio", data).then(resp => {
484 let newText = `<div drawio-diagram="${resp.data.id}"><img src="${resp.data.url}"></div>`;
485 let newContent = this.cm.getValue().split('\n').map(line => {
486 if (line.indexOf(`drawio-diagram="${drawingId}"`) !== -1) {
491 this.cm.setValue(newContent);
492 this.cm.setCursor(cursorPos);
496 window.$events.emit('error', this.imageUploadErrorText);
502 // Make the editor full screen
504 const alreadyFullscreen = this.elem.classList.contains('fullscreen');
505 this.elem.classList.toggle('fullscreen', !alreadyFullscreen);
506 document.body.classList.toggle('markdown-fullscreen', !alreadyFullscreen);
509 // Scroll to a specified text
510 scrollToText(searchText) {
515 const content = this.cm.getValue();
516 const lines = content.split(/\r?\n/);
517 let lineNumber = lines.findIndex(line => {
518 return line && line.indexOf(searchText) !== -1;
521 if (lineNumber === -1) {
525 this.cm.scrollIntoView({
529 // set the cursor location.
532 char: lines[lineNumber].length
536 listenForBookStackEditorEvents() {
538 function getContentToInsert({html, markdown}) {
539 return markdown || html;
542 // Replace editor content
543 window.$events.listen('editor::replace', (eventContent) => {
544 const markdown = getContentToInsert(eventContent);
545 this.cm.setValue(markdown);
548 // Append editor content
549 window.$events.listen('editor::append', (eventContent) => {
550 const cursorPos = this.cm.getCursor('from');
551 const markdown = getContentToInsert(eventContent);
552 const content = this.cm.getValue() + '\n' + markdown;
553 this.cm.setValue(content);
554 this.cm.setCursor(cursorPos.line, cursorPos.ch);
557 // Prepend editor content
558 window.$events.listen('editor::prepend', (eventContent) => {
559 const cursorPos = this.cm.getCursor('from');
560 const markdown = getContentToInsert(eventContent);
561 const content = markdown + '\n' + this.cm.getValue();
562 this.cm.setValue(content);
563 const prependLineCount = markdown.split('\n').length;
564 this.cm.setCursor(cursorPos.line + prependLineCount, cursorPos.ch);
567 // Insert editor content at the current location
568 window.$events.listen('editor::insert', (eventContent) => {
569 const markdown = getContentToInsert(eventContent);
570 this.cm.replaceSelection(markdown);
574 window.$events.listen('editor::focus', () => {
580 export default MarkdownEditor ;