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 const pageEditor = document.getElementById('page-editor');
15 this.pageId = pageEditor.getAttribute('page-id');
16 this.textDirection = pageEditor.getAttribute('text-direction');
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 this.display.addEventListener('load', () => {
31 this.displayDoc = this.display.contentDocument;
35 window.$events.emitPublic(elem, 'editor-markdown::setup', {
36 markdownIt: this.markdown,
37 displayEl: this.display,
38 codeMirrorInstance: this.cm,
46 // Prevent markdown display link click redirect
47 this.displayDoc.addEventListener('click', event => {
48 let isDblClick = Date.now() - lastClick < 300;
50 let link = event.target.closest('a');
52 event.preventDefault();
53 window.open(link.getAttribute('href'));
57 let drawing = event.target.closest('[drawio-diagram]');
58 if (drawing !== null && isDblClick) {
59 this.actionEditDrawing(drawing);
63 lastClick = Date.now();
67 this.elem.addEventListener('click', event => {
68 let button = event.target.closest('button[data-action]');
69 if (button === null) return;
71 let action = button.getAttribute('data-action');
72 if (action === 'insertImage') this.actionInsertImage();
73 if (action === 'insertLink') this.actionShowLinkSelector();
74 if (action === 'insertDrawing' && (event.ctrlKey || event.metaKey)) {
75 this.actionShowImageManager();
78 if (action === 'insertDrawing') this.actionStartDrawing();
79 if (action === 'fullscreen') this.actionFullScreen();
82 // Mobile section toggling
83 this.elem.addEventListener('click', event => {
84 const toolbarLabel = event.target.closest('.editor-toolbar-label');
85 if (!toolbarLabel) return;
87 const currentActiveSections = this.elem.querySelectorAll('.markdown-editor-wrap');
88 for (let activeElem of currentActiveSections) {
89 activeElem.classList.remove('active');
92 toolbarLabel.closest('.markdown-editor-wrap').classList.add('active');
95 window.$events.listen('editor-markdown-update', value => {
96 this.cm.setValue(value);
97 this.updateAndRender();
100 this.codeMirrorSetup();
101 this.listenForBookStackEditorEvents();
103 // Scroll to text if needed.
104 const queryParams = (new URL(window.location)).searchParams;
105 const scrollText = queryParams.get('content-text');
107 this.scrollToText(scrollText);
111 // Update the input content and render the display.
113 const content = this.cm.getValue();
114 this.input.value = content;
115 const html = this.markdown.render(content);
116 window.$events.emit('editor-html-change', html);
117 window.$events.emit('editor-markdown-change', content);
120 this.displayDoc.body.className = 'page-content';
121 this.displayDoc.body.innerHTML = html;
122 this.htmlInput.value = html;
124 // Copy styles from page head and set custom styles for editor
125 this.loadStylesIntoDisplay();
128 loadStylesIntoDisplay() {
129 if (this.displayStylesLoaded) return;
130 this.displayDoc.documentElement.classList.add('markdown-editor-display');
131 // Set display to be dark mode if parent is
133 if (document.documentElement.classList.contains('dark-mode')) {
134 this.displayDoc.documentElement.style.backgroundColor = '#222';
135 this.displayDoc.documentElement.classList.add('dark-mode');
138 this.displayDoc.head.innerHTML = '';
139 const styles = document.head.querySelectorAll('style,link[rel=stylesheet]');
140 for (let style of styles) {
141 const copy = style.cloneNode(true);
142 this.displayDoc.head.appendChild(copy);
145 this.displayStylesLoaded = true;
148 onMarkdownScroll(lineCount) {
149 const elems = this.displayDoc.body.children;
150 if (elems.length <= lineCount) return;
152 const topElem = (lineCount === -1) ? elems[elems.length-1] : elems[lineCount];
153 topElem.scrollIntoView({ block: 'start', inline: 'nearest', behavior: 'smooth'});
158 const context = this;
161 // cm.setOption('direction', this.textDirection);
162 cm.setOption('direction', 'ltr'); // Will force to remain as ltr for now due to issues when HTML is in editor.
163 // Custom key commands
164 let metaKey = code.getMetaKey();
165 const extraKeys = {};
166 // Insert Image shortcut
167 extraKeys[`${metaKey}-Alt-I`] = function(cm) {
168 let selectedText = cm.getSelection();
169 let newText = ``;
170 let cursorPos = cm.getCursor('from');
171 cm.replaceSelection(newText);
172 cm.setCursor(cursorPos.line, cursorPos.ch + newText.length -1);
175 extraKeys[`${metaKey}-S`] = cm => {window.$events.emit('editor-save-draft')};
177 extraKeys[`${metaKey}-Enter`] = cm => {window.$events.emit('editor-save-page')};
178 // Show link selector
179 extraKeys[`Shift-${metaKey}-K`] = cm => {this.actionShowLinkSelector()};
181 extraKeys[`${metaKey}-K`] = cm => {insertLink()};
183 extraKeys[`${metaKey}-1`] = cm => {replaceLineStart('##');};
184 extraKeys[`${metaKey}-2`] = cm => {replaceLineStart('###');};
185 extraKeys[`${metaKey}-3`] = cm => {replaceLineStart('####');};
186 extraKeys[`${metaKey}-4`] = cm => {replaceLineStart('#####');};
187 extraKeys[`${metaKey}-5`] = cm => {replaceLineStart('');};
188 extraKeys[`${metaKey}-d`] = cm => {replaceLineStart('');};
189 extraKeys[`${metaKey}-6`] = cm => {replaceLineStart('>');};
190 extraKeys[`${metaKey}-q`] = cm => {replaceLineStart('>');};
191 extraKeys[`${metaKey}-7`] = cm => {wrapSelection('\n```\n', '\n```');};
192 extraKeys[`${metaKey}-8`] = cm => {wrapSelection('`', '`');};
193 extraKeys[`Shift-${metaKey}-E`] = cm => {wrapSelection('`', '`');};
194 extraKeys[`${metaKey}-9`] = cm => {wrapSelection('<p class="callout info">', '</p>');};
195 cm.setOption('extraKeys', extraKeys);
197 // Update data on content change
198 cm.on('change', (instance, changeObj) => {
199 this.updateAndRender();
202 const onScrollDebounced = debounce((instance) => {
203 // Thanks to http://liuhao.im/english/2015/11/10/the-sync-scroll-of-markdown-editor-in-javascript.html
204 let scroll = instance.getScrollInfo();
205 let atEnd = scroll.top + scroll.clientHeight === scroll.height;
207 this.onMarkdownScroll(-1);
211 let lineNum = instance.lineAtHeight(scroll.top, 'local');
212 let range = instance.getRange({line: 0, ch: null}, {line: lineNum, ch: null});
213 let parser = new DOMParser();
214 let doc = parser.parseFromString(this.markdown.render(range), 'text/html');
215 let totalLines = doc.documentElement.querySelectorAll('body > *');
216 this.onMarkdownScroll(totalLines.length);
219 // Handle scroll to sync display view
220 cm.on('scroll', instance => {
221 onScrollDebounced(instance);
224 // Handle image paste
225 cm.on('paste', (cm, event) => {
226 const clipboard = new Clipboard(event.clipboardData || event.dataTransfer);
228 // Don't handle the event ourselves if no items exist of contains table-looking data
229 if (!clipboard.hasItems() || clipboard.containsTabularData()) {
233 const images = clipboard.getImages();
234 for (const image of images) {
239 // Handle image & content drag n drop
240 cm.on('drop', (cm, event) => {
242 const templateId = event.dataTransfer.getData('bookstack/template');
244 const cursorPos = cm.coordsChar({left: event.pageX, top: event.pageY});
245 cm.setCursor(cursorPos);
246 event.preventDefault();
247 window.$http.get(`/templates/${templateId}`).then(resp => {
248 const content = resp.data.markdown || resp.data.html;
249 cm.replaceSelection(content);
253 const clipboard = new Clipboard(event.dataTransfer);
254 if (clipboard.hasItems()) {
255 const cursorPos = cm.coordsChar({left: event.pageX, top: event.pageY});
256 cm.setCursor(cursorPos);
257 event.stopPropagation();
258 event.preventDefault();
259 const images = clipboard.getImages();
260 for (const image of images) {
267 // Helper to replace editor content
268 function replaceContent(search, replace) {
269 let text = cm.getValue();
270 let cursor = cm.listSelections();
271 cm.setValue(text.replace(search, replace));
272 cm.setSelections(cursor);
275 // Helper to replace the start of the line
276 function replaceLineStart(newStart) {
277 let cursor = cm.getCursor();
278 let lineContent = cm.getLine(cursor.line);
279 let lineLen = lineContent.length;
280 let lineStart = lineContent.split(' ')[0];
282 // Remove symbol if already set
283 if (lineStart === newStart) {
284 lineContent = lineContent.replace(`${newStart} `, '');
285 cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
286 cm.setCursor({line: cursor.line, ch: cursor.ch - (newStart.length + 1)});
290 let alreadySymbol = /^[#>`]/.test(lineStart);
293 posDif = newStart.length - lineStart.length;
294 lineContent = lineContent.replace(lineStart, newStart).trim();
295 } else if (newStart !== '') {
296 posDif = newStart.length + 1;
297 lineContent = newStart + ' ' + lineContent;
299 cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
300 cm.setCursor({line: cursor.line, ch: cursor.ch + posDif});
303 function wrapLine(start, end) {
304 let cursor = cm.getCursor();
305 let lineContent = cm.getLine(cursor.line);
306 let lineLen = lineContent.length;
307 let newLineContent = lineContent;
309 if (lineContent.indexOf(start) === 0 && lineContent.slice(-end.length) === end) {
310 newLineContent = lineContent.slice(start.length, lineContent.length - end.length);
312 newLineContent = `${start}${lineContent}${end}`;
315 cm.replaceRange(newLineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
316 cm.setCursor({line: cursor.line, ch: cursor.ch + start.length});
319 function wrapSelection(start, end) {
320 let selection = cm.getSelection();
321 if (selection === '') return wrapLine(start, end);
323 let newSelection = selection;
327 if (selection.indexOf(start) === 0 && selection.slice(-end.length) === end) {
328 newSelection = selection.slice(start.length, selection.length - end.length);
329 endDiff = -(end.length + start.length);
331 newSelection = `${start}${selection}${end}`;
332 endDiff = start.length + end.length;
335 let selections = cm.listSelections()[0];
336 cm.replaceSelection(newSelection);
337 let headFirst = selections.head.ch <= selections.anchor.ch;
338 selections.head.ch += headFirst ? frontDiff : endDiff;
339 selections.anchor.ch += headFirst ? endDiff : frontDiff;
340 cm.setSelections([selections]);
343 // Handle image upload and add image into markdown content
344 function uploadImage(file) {
345 if (file === null || file.type.indexOf('image') !== 0) return;
349 let fileNameMatches = file.name.match(/\.(.+)$/);
350 if (fileNameMatches.length > 1) ext = fileNameMatches[1];
353 // Insert image into markdown
354 const id = "image-" + Math.random().toString(16).slice(2);
355 const placeholderImage = window.baseUrl(`/loading.gif#upload${id}`);
356 const selectedText = cm.getSelection();
357 const placeHolderText = ``;
358 const cursor = cm.getCursor();
359 cm.replaceSelection(placeHolderText);
360 cm.setCursor({line: cursor.line, ch: cursor.ch + selectedText.length + 3});
362 const remoteFilename = "image-" + Date.now() + "." + ext;
363 const formData = new FormData();
364 formData.append('file', file, remoteFilename);
365 formData.append('uploaded_to', context.pageId);
367 window.$http.post('/images/gallery', formData).then(resp => {
368 const newContent = `[](${resp.data.url})`;
369 replaceContent(placeHolderText, newContent);
371 window.$events.emit('error', trans('errors.image_upload_error'));
372 replaceContent(placeHolderText, selectedText);
377 function insertLink() {
378 let cursorPos = cm.getCursor('from');
379 let selectedText = cm.getSelection() || '';
380 let newText = `[${selectedText}]()`;
382 cm.replaceSelection(newText);
383 let cursorPosDiff = (selectedText === '') ? -3 : -1;
384 cm.setCursor(cursorPos.line, cursorPos.ch + newText.length+cursorPosDiff);
387 this.updateAndRender();
390 actionInsertImage() {
391 const cursorPos = this.cm.getCursor('from');
392 window.ImageManager.show(image => {
393 let selectedText = this.cm.getSelection();
394 let newText = "[](" + image.url + ")";
396 this.cm.replaceSelection(newText);
397 this.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
401 actionShowImageManager() {
402 const cursorPos = this.cm.getCursor('from');
403 window.ImageManager.show(image => {
404 this.insertDrawing(image, cursorPos);
408 // Show the popup link selector and insert a link when finished
409 actionShowLinkSelector() {
410 const cursorPos = this.cm.getCursor('from');
411 window.EntitySelectorPopup.show(entity => {
412 let selectedText = this.cm.getSelection() || entity.name;
413 let newText = `[${selectedText}](${entity.link})`;
415 this.cm.replaceSelection(newText);
416 this.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
421 const drawioUrlElem = document.querySelector('[drawio-url]');
422 return drawioUrlElem ? drawioUrlElem.getAttribute('drawio-url') : false;
425 // Show draw.io if enabled and handle save.
426 actionStartDrawing() {
427 const url = this.getDrawioUrl();
430 const cursorPos = this.cm.getCursor('from');
432 DrawIO.show(url,() => {
433 return Promise.resolve('');
438 uploaded_to: Number(document.getElementById('page-editor').getAttribute('page-id'))
441 window.$http.post(window.baseUrl('/images/drawio'), data).then(resp => {
442 this.insertDrawing(resp.data, cursorPos);
445 window.$events.emit('error', trans('errors.image_upload_error'));
451 insertDrawing(image, originalCursor) {
452 const newText = `<div drawio-diagram="${image.id}"><img src="${image.url}"></div>`;
454 this.cm.replaceSelection(newText);
455 this.cm.setCursor(originalCursor.line, originalCursor.ch + newText.length);
458 // Show draw.io if enabled and handle save.
459 actionEditDrawing(imgContainer) {
460 const drawioUrl = this.getDrawioUrl();
465 const cursorPos = this.cm.getCursor('from');
466 const drawingId = imgContainer.getAttribute('drawio-diagram');
468 DrawIO.show(drawioUrl, () => {
469 return DrawIO.load(drawingId);
474 uploaded_to: Number(document.getElementById('page-editor').getAttribute('page-id'))
477 window.$http.post(window.baseUrl(`/images/drawio`), data).then(resp => {
478 let newText = `<div drawio-diagram="${resp.data.id}"><img src="${resp.data.url}"></div>`;
479 let newContent = this.cm.getValue().split('\n').map(line => {
480 if (line.indexOf(`drawio-diagram="${drawingId}"`) !== -1) {
485 this.cm.setValue(newContent);
486 this.cm.setCursor(cursorPos);
490 window.$events.emit('error', trans('errors.image_upload_error'));
496 // Make the editor full screen
498 const alreadyFullscreen = this.elem.classList.contains('fullscreen');
499 this.elem.classList.toggle('fullscreen', !alreadyFullscreen);
500 document.body.classList.toggle('markdown-fullscreen', !alreadyFullscreen);
503 // Scroll to a specified text
504 scrollToText(searchText) {
509 const content = this.cm.getValue();
510 const lines = content.split(/\r?\n/);
511 let lineNumber = lines.findIndex(line => {
512 return line && line.indexOf(searchText) !== -1;
515 if (lineNumber === -1) {
519 this.cm.scrollIntoView({
523 // set the cursor location.
526 char: lines[lineNumber].length
530 listenForBookStackEditorEvents() {
532 function getContentToInsert({html, markdown}) {
533 return markdown || html;
536 // Replace editor content
537 window.$events.listen('editor::replace', (eventContent) => {
538 const markdown = getContentToInsert(eventContent);
539 this.cm.setValue(markdown);
542 // Append editor content
543 window.$events.listen('editor::append', (eventContent) => {
544 const cursorPos = this.cm.getCursor('from');
545 const markdown = getContentToInsert(eventContent);
546 const content = this.cm.getValue() + '\n' + markdown;
547 this.cm.setValue(content);
548 this.cm.setCursor(cursorPos.line, cursorPos.ch);
551 // Prepend editor content
552 window.$events.listen('editor::prepend', (eventContent) => {
553 const cursorPos = this.cm.getCursor('from');
554 const markdown = getContentToInsert(eventContent);
555 const content = markdown + '\n' + this.cm.getValue();
556 this.cm.setValue(content);
557 const prependLineCount = markdown.split('\n').length;
558 this.cm.setCursor(cursorPos.line + prependLineCount, cursorPos.ch);
563 export default MarkdownEditor ;