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.className = 'markdown-editor-display';
132 this.displayDoc.head.innerHTML = '';
133 const styles = document.head.querySelectorAll('style,link[rel=stylesheet]');
134 for (let style of styles) {
135 const copy = style.cloneNode(true);
136 this.displayDoc.head.appendChild(copy);
139 this.displayStylesLoaded = true;
142 onMarkdownScroll(lineCount) {
143 const elems = this.displayDoc.body.children;
144 if (elems.length <= lineCount) return;
146 const topElem = (lineCount === -1) ? elems[elems.length-1] : elems[lineCount];
147 topElem.scrollIntoView({ block: 'start', inline: 'nearest', behavior: 'smooth'});
152 const context = this;
155 // cm.setOption('direction', this.textDirection);
156 cm.setOption('direction', 'ltr'); // Will force to remain as ltr for now due to issues when HTML is in editor.
157 // Custom key commands
158 let metaKey = code.getMetaKey();
159 const extraKeys = {};
160 // Insert Image shortcut
161 extraKeys[`${metaKey}-Alt-I`] = function(cm) {
162 let selectedText = cm.getSelection();
163 let newText = ``;
164 let cursorPos = cm.getCursor('from');
165 cm.replaceSelection(newText);
166 cm.setCursor(cursorPos.line, cursorPos.ch + newText.length -1);
169 extraKeys[`${metaKey}-S`] = cm => {window.$events.emit('editor-save-draft')};
171 extraKeys[`${metaKey}-Enter`] = cm => {window.$events.emit('editor-save-page')};
172 // Show link selector
173 extraKeys[`Shift-${metaKey}-K`] = cm => {this.actionShowLinkSelector()};
175 extraKeys[`${metaKey}-K`] = cm => {insertLink()};
177 extraKeys[`${metaKey}-1`] = cm => {replaceLineStart('##');};
178 extraKeys[`${metaKey}-2`] = cm => {replaceLineStart('###');};
179 extraKeys[`${metaKey}-3`] = cm => {replaceLineStart('####');};
180 extraKeys[`${metaKey}-4`] = cm => {replaceLineStart('#####');};
181 extraKeys[`${metaKey}-5`] = cm => {replaceLineStart('');};
182 extraKeys[`${metaKey}-d`] = cm => {replaceLineStart('');};
183 extraKeys[`${metaKey}-6`] = cm => {replaceLineStart('>');};
184 extraKeys[`${metaKey}-q`] = cm => {replaceLineStart('>');};
185 extraKeys[`${metaKey}-7`] = cm => {wrapSelection('\n```\n', '\n```');};
186 extraKeys[`${metaKey}-8`] = cm => {wrapSelection('`', '`');};
187 extraKeys[`Shift-${metaKey}-E`] = cm => {wrapSelection('`', '`');};
188 extraKeys[`${metaKey}-9`] = cm => {wrapSelection('<p class="callout info">', '</p>');};
189 cm.setOption('extraKeys', extraKeys);
191 // Update data on content change
192 cm.on('change', (instance, changeObj) => {
193 this.updateAndRender();
196 const onScrollDebounced = debounce((instance) => {
197 // Thanks to http://liuhao.im/english/2015/11/10/the-sync-scroll-of-markdown-editor-in-javascript.html
198 let scroll = instance.getScrollInfo();
199 let atEnd = scroll.top + scroll.clientHeight === scroll.height;
201 this.onMarkdownScroll(-1);
205 let lineNum = instance.lineAtHeight(scroll.top, 'local');
206 let range = instance.getRange({line: 0, ch: null}, {line: lineNum, ch: null});
207 let parser = new DOMParser();
208 let doc = parser.parseFromString(this.markdown.render(range), 'text/html');
209 let totalLines = doc.documentElement.querySelectorAll('body > *');
210 this.onMarkdownScroll(totalLines.length);
213 // Handle scroll to sync display view
214 cm.on('scroll', instance => {
215 onScrollDebounced(instance);
218 // Handle image paste
219 cm.on('paste', (cm, event) => {
220 const clipboard = new Clipboard(event.clipboardData || event.dataTransfer);
222 // Don't handle the event ourselves if no items exist of contains table-looking data
223 if (!clipboard.hasItems() || clipboard.containsTabularData()) {
227 const images = clipboard.getImages();
228 for (const image of images) {
233 // Handle image & content drag n drop
234 cm.on('drop', (cm, event) => {
236 const templateId = event.dataTransfer.getData('bookstack/template');
238 const cursorPos = cm.coordsChar({left: event.pageX, top: event.pageY});
239 cm.setCursor(cursorPos);
240 event.preventDefault();
241 window.$http.get(`/templates/${templateId}`).then(resp => {
242 const content = resp.data.markdown || resp.data.html;
243 cm.replaceSelection(content);
247 const clipboard = new Clipboard(event.dataTransfer);
248 if (clipboard.hasItems()) {
249 const cursorPos = cm.coordsChar({left: event.pageX, top: event.pageY});
250 cm.setCursor(cursorPos);
251 event.stopPropagation();
252 event.preventDefault();
253 const images = clipboard.getImages();
254 for (const image of images) {
261 // Helper to replace editor content
262 function replaceContent(search, replace) {
263 let text = cm.getValue();
264 let cursor = cm.listSelections();
265 cm.setValue(text.replace(search, replace));
266 cm.setSelections(cursor);
269 // Helper to replace the start of the line
270 function replaceLineStart(newStart) {
271 let cursor = cm.getCursor();
272 let lineContent = cm.getLine(cursor.line);
273 let lineLen = lineContent.length;
274 let lineStart = lineContent.split(' ')[0];
276 // Remove symbol if already set
277 if (lineStart === newStart) {
278 lineContent = lineContent.replace(`${newStart} `, '');
279 cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
280 cm.setCursor({line: cursor.line, ch: cursor.ch - (newStart.length + 1)});
284 let alreadySymbol = /^[#>`]/.test(lineStart);
287 posDif = newStart.length - lineStart.length;
288 lineContent = lineContent.replace(lineStart, newStart).trim();
289 } else if (newStart !== '') {
290 posDif = newStart.length + 1;
291 lineContent = newStart + ' ' + lineContent;
293 cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
294 cm.setCursor({line: cursor.line, ch: cursor.ch + posDif});
297 function wrapLine(start, end) {
298 let cursor = cm.getCursor();
299 let lineContent = cm.getLine(cursor.line);
300 let lineLen = lineContent.length;
301 let newLineContent = lineContent;
303 if (lineContent.indexOf(start) === 0 && lineContent.slice(-end.length) === end) {
304 newLineContent = lineContent.slice(start.length, lineContent.length - end.length);
306 newLineContent = `${start}${lineContent}${end}`;
309 cm.replaceRange(newLineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
310 cm.setCursor({line: cursor.line, ch: cursor.ch + start.length});
313 function wrapSelection(start, end) {
314 let selection = cm.getSelection();
315 if (selection === '') return wrapLine(start, end);
317 let newSelection = selection;
321 if (selection.indexOf(start) === 0 && selection.slice(-end.length) === end) {
322 newSelection = selection.slice(start.length, selection.length - end.length);
323 endDiff = -(end.length + start.length);
325 newSelection = `${start}${selection}${end}`;
326 endDiff = start.length + end.length;
329 let selections = cm.listSelections()[0];
330 cm.replaceSelection(newSelection);
331 let headFirst = selections.head.ch <= selections.anchor.ch;
332 selections.head.ch += headFirst ? frontDiff : endDiff;
333 selections.anchor.ch += headFirst ? endDiff : frontDiff;
334 cm.setSelections([selections]);
337 // Handle image upload and add image into markdown content
338 function uploadImage(file) {
339 if (file === null || file.type.indexOf('image') !== 0) return;
343 let fileNameMatches = file.name.match(/\.(.+)$/);
344 if (fileNameMatches.length > 1) ext = fileNameMatches[1];
347 // Insert image into markdown
348 const id = "image-" + Math.random().toString(16).slice(2);
349 const placeholderImage = window.baseUrl(`/loading.gif#upload${id}`);
350 const selectedText = cm.getSelection();
351 const placeHolderText = ``;
352 const cursor = cm.getCursor();
353 cm.replaceSelection(placeHolderText);
354 cm.setCursor({line: cursor.line, ch: cursor.ch + selectedText.length + 3});
356 const remoteFilename = "image-" + Date.now() + "." + ext;
357 const formData = new FormData();
358 formData.append('file', file, remoteFilename);
359 formData.append('uploaded_to', context.pageId);
361 window.$http.post('/images/gallery', formData).then(resp => {
362 const newContent = `[](${resp.data.url})`;
363 replaceContent(placeHolderText, newContent);
365 window.$events.emit('error', trans('errors.image_upload_error'));
366 replaceContent(placeHolderText, selectedText);
371 function insertLink() {
372 let cursorPos = cm.getCursor('from');
373 let selectedText = cm.getSelection() || '';
374 let newText = `[${selectedText}]()`;
376 cm.replaceSelection(newText);
377 let cursorPosDiff = (selectedText === '') ? -3 : -1;
378 cm.setCursor(cursorPos.line, cursorPos.ch + newText.length+cursorPosDiff);
381 this.updateAndRender();
384 actionInsertImage() {
385 const cursorPos = this.cm.getCursor('from');
386 window.ImageManager.show(image => {
387 let selectedText = this.cm.getSelection();
388 let newText = "[](" + image.url + ")";
390 this.cm.replaceSelection(newText);
391 this.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
395 actionShowImageManager() {
396 const cursorPos = this.cm.getCursor('from');
397 window.ImageManager.show(image => {
398 this.insertDrawing(image, cursorPos);
402 // Show the popup link selector and insert a link when finished
403 actionShowLinkSelector() {
404 const cursorPos = this.cm.getCursor('from');
405 window.EntitySelectorPopup.show(entity => {
406 let selectedText = this.cm.getSelection() || entity.name;
407 let newText = `[${selectedText}](${entity.link})`;
409 this.cm.replaceSelection(newText);
410 this.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
415 const drawioUrlElem = document.querySelector('[drawio-url]');
416 return drawioUrlElem ? drawioUrlElem.getAttribute('drawio-url') : false;
419 // Show draw.io if enabled and handle save.
420 actionStartDrawing() {
421 const url = this.getDrawioUrl();
424 const cursorPos = this.cm.getCursor('from');
426 DrawIO.show(url,() => {
427 return Promise.resolve('');
432 uploaded_to: Number(document.getElementById('page-editor').getAttribute('page-id'))
435 window.$http.post(window.baseUrl('/images/drawio'), data).then(resp => {
436 this.insertDrawing(resp.data, cursorPos);
439 window.$events.emit('error', trans('errors.image_upload_error'));
445 insertDrawing(image, originalCursor) {
446 const newText = `<div drawio-diagram="${image.id}"><img src="${image.url}"></div>`;
448 this.cm.replaceSelection(newText);
449 this.cm.setCursor(originalCursor.line, originalCursor.ch + newText.length);
452 // Show draw.io if enabled and handle save.
453 actionEditDrawing(imgContainer) {
454 const drawioUrl = this.getDrawioUrl();
459 const cursorPos = this.cm.getCursor('from');
460 const drawingId = imgContainer.getAttribute('drawio-diagram');
462 DrawIO.show(drawioUrl, () => {
463 return DrawIO.load(drawingId);
468 uploaded_to: Number(document.getElementById('page-editor').getAttribute('page-id'))
471 window.$http.post(window.baseUrl(`/images/drawio`), data).then(resp => {
472 let newText = `<div drawio-diagram="${resp.data.id}"><img src="${resp.data.url}"></div>`;
473 let newContent = this.cm.getValue().split('\n').map(line => {
474 if (line.indexOf(`drawio-diagram="${drawingId}"`) !== -1) {
479 this.cm.setValue(newContent);
480 this.cm.setCursor(cursorPos);
484 window.$events.emit('error', trans('errors.image_upload_error'));
490 // Make the editor full screen
492 const alreadyFullscreen = this.elem.classList.contains('fullscreen');
493 this.elem.classList.toggle('fullscreen', !alreadyFullscreen);
494 document.body.classList.toggle('markdown-fullscreen', !alreadyFullscreen);
497 // Scroll to a specified text
498 scrollToText(searchText) {
503 const content = this.cm.getValue();
504 const lines = content.split(/\r?\n/);
505 let lineNumber = lines.findIndex(line => {
506 return line && line.indexOf(searchText) !== -1;
509 if (lineNumber === -1) {
513 this.cm.scrollIntoView({
517 // set the cursor location.
520 char: lines[lineNumber].length
524 listenForBookStackEditorEvents() {
526 function getContentToInsert({html, markdown}) {
527 return markdown || html;
530 // Replace editor content
531 window.$events.listen('editor::replace', (eventContent) => {
532 const markdown = getContentToInsert(eventContent);
533 this.cm.setValue(markdown);
536 // Append editor content
537 window.$events.listen('editor::append', (eventContent) => {
538 const cursorPos = this.cm.getCursor('from');
539 const markdown = getContentToInsert(eventContent);
540 const content = this.cm.getValue() + '\n' + markdown;
541 this.cm.setValue(content);
542 this.cm.setCursor(cursorPos.line, cursorPos.ch);
545 // Prepend editor content
546 window.$events.listen('editor::prepend', (eventContent) => {
547 const cursorPos = this.cm.getCursor('from');
548 const markdown = getContentToInsert(eventContent);
549 const content = markdown + '\n' + this.cm.getValue();
550 this.cm.setValue(content);
551 const prependLineCount = markdown.split('\n').length;
552 this.cm.setCursor(cursorPos.line + prependLineCount, cursorPos.ch);
557 export default MarkdownEditor ;