1 import MarkdownIt from "markdown-it";
2 import mdTasksLists from 'markdown-it-task-lists';
3 import code from '../services/code';
4 import {debounce} from "../services/util";
6 import DrawIO from "../services/drawio";
13 const pageEditor = document.getElementById('page-editor');
14 this.pageId = pageEditor.getAttribute('page-id');
15 this.textDirection = pageEditor.getAttribute('text-direction');
17 this.markdown = new MarkdownIt({html: true});
18 this.markdown.use(mdTasksLists, {label: true});
20 this.display = this.elem.querySelector('.markdown-display');
22 this.displayStylesLoaded = false;
23 this.input = this.elem.querySelector('textarea');
24 this.htmlInput = this.elem.querySelector('input[name=html]');
25 this.cm = code.markdownEditor(this.input);
27 this.onMarkdownScroll = this.onMarkdownScroll.bind(this);
29 this.display.addEventListener('load', () => {
30 this.displayDoc = this.display.contentDocument;
34 window.$events.emitPublic(elem, 'editor-markdown::setup', {
35 markdownIt: this.markdown,
36 displayEl: this.display,
37 codeMirrorInstance: this.cm,
45 // Prevent markdown display link click redirect
46 this.displayDoc.addEventListener('click', event => {
47 let isDblClick = Date.now() - lastClick < 300;
49 let link = event.target.closest('a');
51 event.preventDefault();
52 window.open(link.getAttribute('href'));
56 let drawing = event.target.closest('[drawio-diagram]');
57 if (drawing !== null && isDblClick) {
58 this.actionEditDrawing(drawing);
62 lastClick = Date.now();
66 this.elem.addEventListener('click', event => {
67 let button = event.target.closest('button[data-action]');
68 if (button === null) return;
70 let action = button.getAttribute('data-action');
71 if (action === 'insertImage') this.actionInsertImage();
72 if (action === 'insertLink') this.actionShowLinkSelector();
73 if (action === 'insertDrawing' && (event.ctrlKey || event.metaKey)) {
74 this.actionShowImageManager();
77 if (action === 'insertDrawing') this.actionStartDrawing();
80 // Mobile section toggling
81 this.elem.addEventListener('click', event => {
82 const toolbarLabel = event.target.closest('.editor-toolbar-label');
83 if (!toolbarLabel) return;
85 const currentActiveSections = this.elem.querySelectorAll('.markdown-editor-wrap');
86 for (let activeElem of currentActiveSections) {
87 activeElem.classList.remove('active');
90 toolbarLabel.closest('.markdown-editor-wrap').classList.add('active');
93 window.$events.listen('editor-markdown-update', value => {
94 this.cm.setValue(value);
95 this.updateAndRender();
98 this.codeMirrorSetup();
99 this.listenForBookStackEditorEvents();
101 // Scroll to text if needed.
102 const queryParams = (new URL(window.location)).searchParams;
103 const scrollText = queryParams.get('content-text');
105 this.scrollToText(scrollText);
109 // Update the input content and render the display.
111 const content = this.cm.getValue();
112 this.input.value = content;
113 const html = this.markdown.render(content);
114 window.$events.emit('editor-html-change', html);
115 window.$events.emit('editor-markdown-change', content);
118 this.displayDoc.body.className = 'page-content';
119 this.displayDoc.body.innerHTML = html;
120 this.htmlInput.value = html;
122 // Copy styles from page head and set custom styles for editor
123 this.loadStylesIntoDisplay();
126 loadStylesIntoDisplay() {
127 if (this.displayStylesLoaded) return;
128 this.displayDoc.documentElement.className = 'markdown-editor-display';
130 this.displayDoc.head.innerHTML = '';
131 const styles = document.head.querySelectorAll('style,link[rel=stylesheet]');
132 for (let style of styles) {
133 const copy = style.cloneNode(true);
134 this.displayDoc.head.appendChild(copy);
137 this.displayStylesLoaded = true;
140 onMarkdownScroll(lineCount) {
141 const elems = this.displayDoc.body.children;
142 if (elems.length <= lineCount) return;
144 const topElem = (lineCount === -1) ? elems[elems.length-1] : elems[lineCount];
145 topElem.scrollIntoView({ block: 'start', inline: 'nearest', behavior: 'smooth'});
150 const context = this;
153 // cm.setOption('direction', this.textDirection);
154 cm.setOption('direction', 'ltr'); // Will force to remain as ltr for now due to issues when HTML is in editor.
155 // Custom key commands
156 let metaKey = code.getMetaKey();
157 const extraKeys = {};
158 // Insert Image shortcut
159 extraKeys[`${metaKey}-Alt-I`] = function(cm) {
160 let selectedText = cm.getSelection();
161 let newText = ``;
162 let cursorPos = cm.getCursor('from');
163 cm.replaceSelection(newText);
164 cm.setCursor(cursorPos.line, cursorPos.ch + newText.length -1);
167 extraKeys[`${metaKey}-S`] = cm => {window.$events.emit('editor-save-draft')};
169 extraKeys[`${metaKey}-Enter`] = cm => {window.$events.emit('editor-save-page')};
170 // Show link selector
171 extraKeys[`Shift-${metaKey}-K`] = cm => {this.actionShowLinkSelector()};
173 extraKeys[`${metaKey}-K`] = cm => {insertLink()};
175 extraKeys[`${metaKey}-1`] = cm => {replaceLineStart('##');};
176 extraKeys[`${metaKey}-2`] = cm => {replaceLineStart('###');};
177 extraKeys[`${metaKey}-3`] = cm => {replaceLineStart('####');};
178 extraKeys[`${metaKey}-4`] = cm => {replaceLineStart('#####');};
179 extraKeys[`${metaKey}-5`] = cm => {replaceLineStart('');};
180 extraKeys[`${metaKey}-d`] = cm => {replaceLineStart('');};
181 extraKeys[`${metaKey}-6`] = cm => {replaceLineStart('>');};
182 extraKeys[`${metaKey}-q`] = cm => {replaceLineStart('>');};
183 extraKeys[`${metaKey}-7`] = cm => {wrapSelection('\n```\n', '\n```');};
184 extraKeys[`${metaKey}-8`] = cm => {wrapSelection('`', '`');};
185 extraKeys[`Shift-${metaKey}-E`] = cm => {wrapSelection('`', '`');};
186 extraKeys[`${metaKey}-9`] = cm => {wrapSelection('<p class="callout info">', '</p>');};
187 cm.setOption('extraKeys', extraKeys);
189 // Update data on content change
190 cm.on('change', (instance, changeObj) => {
191 this.updateAndRender();
194 const onScrollDebounced = debounce((instance) => {
195 // Thanks to http://liuhao.im/english/2015/11/10/the-sync-scroll-of-markdown-editor-in-javascript.html
196 let scroll = instance.getScrollInfo();
197 let atEnd = scroll.top + scroll.clientHeight === scroll.height;
199 this.onMarkdownScroll(-1);
203 let lineNum = instance.lineAtHeight(scroll.top, 'local');
204 let range = instance.getRange({line: 0, ch: null}, {line: lineNum, ch: null});
205 let parser = new DOMParser();
206 let doc = parser.parseFromString(this.markdown.render(range), 'text/html');
207 let totalLines = doc.documentElement.querySelectorAll('body > *');
208 this.onMarkdownScroll(totalLines.length);
211 // Handle scroll to sync display view
212 cm.on('scroll', instance => {
213 onScrollDebounced(instance);
216 // Handle image paste
217 cm.on('paste', (cm, event) => {
218 const clipboardItems = event.clipboardData.items;
219 if (!event.clipboardData || !clipboardItems) return;
221 // Don't handle if clipboard includes text content
222 for (let clipboardItem of clipboardItems) {
223 if (clipboardItem.type.includes('text/')) {
228 for (let clipboardItem of clipboardItems) {
229 if (clipboardItem.type.includes("image")) {
230 uploadImage(clipboardItem.getAsFile());
235 // Handle image & content drag n drop
236 cm.on('drop', (cm, event) => {
238 const templateId = event.dataTransfer.getData('bookstack/template');
240 const cursorPos = cm.coordsChar({left: event.pageX, top: event.pageY});
241 cm.setCursor(cursorPos);
242 event.preventDefault();
243 window.$http.get(`/templates/${templateId}`).then(resp => {
244 const content = resp.data.markdown || resp.data.html;
245 cm.replaceSelection(content);
249 if (event.dataTransfer && event.dataTransfer.files && event.dataTransfer.files.length > 0) {
250 const cursorPos = cm.coordsChar({left: event.pageX, top: event.pageY});
251 cm.setCursor(cursorPos);
252 event.stopPropagation();
253 event.preventDefault();
254 for (let i = 0; i < event.dataTransfer.files.length; i++) {
255 uploadImage(event.dataTransfer.files[i]);
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);
414 // Show draw.io if enabled and handle save.
415 actionStartDrawing() {
416 if (document.querySelector('[drawio-enabled]').getAttribute('drawio-enabled') !== 'true') return;
417 let cursorPos = this.cm.getCursor('from');
420 return Promise.resolve('');
422 // let id = "image-" + Math.random().toString(16).slice(2);
423 // let loadingImage = window.baseUrl('/loading.gif');
426 uploaded_to: Number(document.getElementById('page-editor').getAttribute('page-id'))
429 window.$http.post(window.baseUrl('/images/drawio'), data).then(resp => {
430 this.insertDrawing(resp.data, cursorPos);
433 window.$events.emit('error', trans('errors.image_upload_error'));
439 insertDrawing(image, originalCursor) {
440 const newText = `<div drawio-diagram="${image.id}"><img src="${image.url}"></div>`;
442 this.cm.replaceSelection(newText);
443 this.cm.setCursor(originalCursor.line, originalCursor.ch + newText.length);
446 // Show draw.io if enabled and handle save.
447 actionEditDrawing(imgContainer) {
448 const drawingDisabled = document.querySelector('[drawio-enabled]').getAttribute('drawio-enabled') !== 'true';
449 if (drawingDisabled) {
453 const cursorPos = this.cm.getCursor('from');
454 const drawingId = imgContainer.getAttribute('drawio-diagram');
457 return DrawIO.load(drawingId);
462 uploaded_to: Number(document.getElementById('page-editor').getAttribute('page-id'))
465 window.$http.post(window.baseUrl(`/images/drawio`), data).then(resp => {
466 let newText = `<div drawio-diagram="${resp.data.id}"><img src="${resp.data.url}"></div>`;
467 let newContent = this.cm.getValue().split('\n').map(line => {
468 if (line.indexOf(`drawio-diagram="${drawingId}"`) !== -1) {
473 this.cm.setValue(newContent);
474 this.cm.setCursor(cursorPos);
478 window.$events.emit('error', trans('errors.image_upload_error'));
484 // Scroll to a specified text
485 scrollToText(searchText) {
490 const content = this.cm.getValue();
491 const lines = content.split(/\r?\n/);
492 let lineNumber = lines.findIndex(line => {
493 return line && line.indexOf(searchText) !== -1;
496 if (lineNumber === -1) {
500 this.cm.scrollIntoView({
504 // set the cursor location.
507 char: lines[lineNumber].length
511 listenForBookStackEditorEvents() {
513 function getContentToInsert({html, markdown}) {
514 return markdown || html;
517 // Replace editor content
518 window.$events.listen('editor::replace', (eventContent) => {
519 const markdown = getContentToInsert(eventContent);
520 this.cm.setValue(markdown);
523 // Append editor content
524 window.$events.listen('editor::append', (eventContent) => {
525 const cursorPos = this.cm.getCursor('from');
526 const markdown = getContentToInsert(eventContent);
527 const content = this.cm.getValue() + '\n' + markdown;
528 this.cm.setValue(content);
529 this.cm.setCursor(cursorPos.line, cursorPos.ch);
532 // Prepend editor content
533 window.$events.listen('editor::prepend', (eventContent) => {
534 const cursorPos = this.cm.getCursor('from');
535 const markdown = getContentToInsert(eventContent);
536 const content = markdown + '\n' + this.cm.getValue();
537 this.cm.setValue(content);
538 const prependLineCount = markdown.split('\n').length;
539 this.cm.setCursor(cursorPos.line + prependLineCount, cursorPos.ch);
544 export default MarkdownEditor ;