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');
21 this.displayDoc = this.display.contentDocument;
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);
30 // Scroll to text if needed.
31 const queryParams = (new URL(window.location)).searchParams;
32 const scrollText = queryParams.get('content-text');
34 this.scrollToText(scrollText);
42 // Prevent markdown display link click redirect
43 this.displayDoc.addEventListener('click', event => {
44 let isDblClick = Date.now() - lastClick < 300;
46 let link = event.target.closest('a');
48 event.preventDefault();
49 window.open(link.getAttribute('href'));
53 let drawing = event.target.closest('[drawio-diagram]');
54 if (drawing !== null && isDblClick) {
55 this.actionEditDrawing(drawing);
59 lastClick = Date.now();
63 this.elem.addEventListener('click', event => {
64 let button = event.target.closest('button[data-action]');
65 if (button === null) return;
67 let action = button.getAttribute('data-action');
68 if (action === 'insertImage') this.actionInsertImage();
69 if (action === 'insertLink') this.actionShowLinkSelector();
70 if (action === 'insertDrawing' && (event.ctrlKey || event.metaKey)) {
71 this.actionShowImageManager();
74 if (action === 'insertDrawing') this.actionStartDrawing();
77 // Mobile section toggling
78 this.elem.addEventListener('click', event => {
79 const toolbarLabel = event.target.closest('.editor-toolbar-label');
80 if (!toolbarLabel) return;
82 const currentActiveSections = this.elem.querySelectorAll('.markdown-editor-wrap');
83 for (let activeElem of currentActiveSections) {
84 activeElem.classList.remove('active');
87 toolbarLabel.closest('.markdown-editor-wrap').classList.add('active');
90 window.$events.listen('editor-markdown-update', value => {
91 this.cm.setValue(value);
92 this.updateAndRender();
95 this.codeMirrorSetup();
96 this.listenForBookStackEditorEvents();
99 // Update the input content and render the display.
101 const content = this.cm.getValue();
102 this.input.value = content;
103 const html = this.markdown.render(content);
104 window.$events.emit('editor-html-change', html);
105 window.$events.emit('editor-markdown-change', content);
108 this.displayDoc.body.className = 'page-content';
109 this.displayDoc.body.innerHTML = html;
110 this.htmlInput.value = html;
112 // Copy styles from page head and set custom styles for editor
113 this.loadStylesIntoDisplay();
116 loadStylesIntoDisplay() {
117 if (this.displayStylesLoaded) return;
118 this.displayDoc.documentElement.className = 'markdown-editor-display';
120 this.displayDoc.head.innerHTML = '';
121 const styles = document.head.querySelectorAll('style,link[rel=stylesheet]');
122 for (let style of styles) {
123 const copy = style.cloneNode(true);
124 this.displayDoc.head.appendChild(copy);
127 this.displayStylesLoaded = true;
130 onMarkdownScroll(lineCount) {
131 const elems = this.displayDoc.body.children;
132 if (elems.length <= lineCount) return;
134 const topElem = (lineCount === -1) ? elems[elems.length-1] : elems[lineCount];
135 topElem.scrollIntoView({ block: 'start', inline: 'nearest', behavior: 'smooth'});
140 const context = this;
143 // cm.setOption('direction', this.textDirection);
144 cm.setOption('direction', 'ltr'); // Will force to remain as ltr for now due to issues when HTML is in editor.
145 // Custom key commands
146 let metaKey = code.getMetaKey();
147 const extraKeys = {};
148 // Insert Image shortcut
149 extraKeys[`${metaKey}-Alt-I`] = function(cm) {
150 let selectedText = cm.getSelection();
151 let newText = ``;
152 let cursorPos = cm.getCursor('from');
153 cm.replaceSelection(newText);
154 cm.setCursor(cursorPos.line, cursorPos.ch + newText.length -1);
157 extraKeys[`${metaKey}-S`] = cm => {window.$events.emit('editor-save-draft')};
159 extraKeys[`${metaKey}-Enter`] = cm => {window.$events.emit('editor-save-page')};
160 // Show link selector
161 extraKeys[`Shift-${metaKey}-K`] = cm => {this.actionShowLinkSelector()};
163 extraKeys[`${metaKey}-K`] = cm => {insertLink()};
165 extraKeys[`${metaKey}-1`] = cm => {replaceLineStart('##');};
166 extraKeys[`${metaKey}-2`] = cm => {replaceLineStart('###');};
167 extraKeys[`${metaKey}-3`] = cm => {replaceLineStart('####');};
168 extraKeys[`${metaKey}-4`] = cm => {replaceLineStart('#####');};
169 extraKeys[`${metaKey}-5`] = cm => {replaceLineStart('');};
170 extraKeys[`${metaKey}-d`] = cm => {replaceLineStart('');};
171 extraKeys[`${metaKey}-6`] = cm => {replaceLineStart('>');};
172 extraKeys[`${metaKey}-q`] = cm => {replaceLineStart('>');};
173 extraKeys[`${metaKey}-7`] = cm => {wrapSelection('\n```\n', '\n```');};
174 extraKeys[`${metaKey}-8`] = cm => {wrapSelection('`', '`');};
175 extraKeys[`Shift-${metaKey}-E`] = cm => {wrapSelection('`', '`');};
176 extraKeys[`${metaKey}-9`] = cm => {wrapSelection('<p class="callout info">', '</p>');};
177 cm.setOption('extraKeys', extraKeys);
179 // Update data on content change
180 cm.on('change', (instance, changeObj) => {
181 this.updateAndRender();
184 const onScrollDebounced = debounce((instance) => {
185 // Thanks to http://liuhao.im/english/2015/11/10/the-sync-scroll-of-markdown-editor-in-javascript.html
186 let scroll = instance.getScrollInfo();
187 let atEnd = scroll.top + scroll.clientHeight === scroll.height;
189 this.onMarkdownScroll(-1);
193 let lineNum = instance.lineAtHeight(scroll.top, 'local');
194 let range = instance.getRange({line: 0, ch: null}, {line: lineNum, ch: null});
195 let parser = new DOMParser();
196 let doc = parser.parseFromString(this.markdown.render(range), 'text/html');
197 let totalLines = doc.documentElement.querySelectorAll('body > *');
198 this.onMarkdownScroll(totalLines.length);
201 // Handle scroll to sync display view
202 cm.on('scroll', instance => {
203 onScrollDebounced(instance);
206 // Handle image paste
207 cm.on('paste', (cm, event) => {
208 const clipboardItems = event.clipboardData.items;
209 if (!event.clipboardData || !clipboardItems) return;
211 // Don't handle if clipboard includes text content
212 for (let clipboardItem of clipboardItems) {
213 if (clipboardItem.type.includes('text/')) {
218 for (let clipboardItem of clipboardItems) {
219 if (clipboardItem.type.includes("image")) {
220 uploadImage(clipboardItem.getAsFile());
225 // Handle image & content drag n drop
226 cm.on('drop', (cm, event) => {
228 const templateId = event.dataTransfer.getData('bookstack/template');
230 const cursorPos = cm.coordsChar({left: event.pageX, top: event.pageY});
231 cm.setCursor(cursorPos);
232 event.preventDefault();
233 window.$http.get(`/templates/${templateId}`).then(resp => {
234 const content = resp.data.markdown || resp.data.html;
235 cm.replaceSelection(content);
239 if (event.dataTransfer && event.dataTransfer.files && event.dataTransfer.files.length > 0) {
240 const cursorPos = cm.coordsChar({left: event.pageX, top: event.pageY});
241 cm.setCursor(cursorPos);
242 event.stopPropagation();
243 event.preventDefault();
244 for (let i = 0; i < event.dataTransfer.files.length; i++) {
245 uploadImage(event.dataTransfer.files[i]);
251 // Helper to replace editor content
252 function replaceContent(search, replace) {
253 let text = cm.getValue();
254 let cursor = cm.listSelections();
255 cm.setValue(text.replace(search, replace));
256 cm.setSelections(cursor);
259 // Helper to replace the start of the line
260 function replaceLineStart(newStart) {
261 let cursor = cm.getCursor();
262 let lineContent = cm.getLine(cursor.line);
263 let lineLen = lineContent.length;
264 let lineStart = lineContent.split(' ')[0];
266 // Remove symbol if already set
267 if (lineStart === newStart) {
268 lineContent = lineContent.replace(`${newStart} `, '');
269 cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
270 cm.setCursor({line: cursor.line, ch: cursor.ch - (newStart.length + 1)});
274 let alreadySymbol = /^[#>`]/.test(lineStart);
277 posDif = newStart.length - lineStart.length;
278 lineContent = lineContent.replace(lineStart, newStart).trim();
279 } else if (newStart !== '') {
280 posDif = newStart.length + 1;
281 lineContent = newStart + ' ' + lineContent;
283 cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
284 cm.setCursor({line: cursor.line, ch: cursor.ch + posDif});
287 function wrapLine(start, end) {
288 let cursor = cm.getCursor();
289 let lineContent = cm.getLine(cursor.line);
290 let lineLen = lineContent.length;
291 let newLineContent = lineContent;
293 if (lineContent.indexOf(start) === 0 && lineContent.slice(-end.length) === end) {
294 newLineContent = lineContent.slice(start.length, lineContent.length - end.length);
296 newLineContent = `${start}${lineContent}${end}`;
299 cm.replaceRange(newLineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
300 cm.setCursor({line: cursor.line, ch: cursor.ch + start.length});
303 function wrapSelection(start, end) {
304 let selection = cm.getSelection();
305 if (selection === '') return wrapLine(start, end);
307 let newSelection = selection;
311 if (selection.indexOf(start) === 0 && selection.slice(-end.length) === end) {
312 newSelection = selection.slice(start.length, selection.length - end.length);
313 endDiff = -(end.length + start.length);
315 newSelection = `${start}${selection}${end}`;
316 endDiff = start.length + end.length;
319 let selections = cm.listSelections()[0];
320 cm.replaceSelection(newSelection);
321 let headFirst = selections.head.ch <= selections.anchor.ch;
322 selections.head.ch += headFirst ? frontDiff : endDiff;
323 selections.anchor.ch += headFirst ? endDiff : frontDiff;
324 cm.setSelections([selections]);
327 // Handle image upload and add image into markdown content
328 function uploadImage(file) {
329 if (file === null || file.type.indexOf('image') !== 0) return;
333 let fileNameMatches = file.name.match(/\.(.+)$/);
334 if (fileNameMatches.length > 1) ext = fileNameMatches[1];
337 // Insert image into markdown
338 const id = "image-" + Math.random().toString(16).slice(2);
339 const placeholderImage = window.baseUrl(`/loading.gif#upload${id}`);
340 const selectedText = cm.getSelection();
341 const placeHolderText = ``;
342 const cursor = cm.getCursor();
343 cm.replaceSelection(placeHolderText);
344 cm.setCursor({line: cursor.line, ch: cursor.ch + selectedText.length + 3});
346 const remoteFilename = "image-" + Date.now() + "." + ext;
347 const formData = new FormData();
348 formData.append('file', file, remoteFilename);
349 formData.append('uploaded_to', context.pageId);
351 window.$http.post('/images/gallery', formData).then(resp => {
352 const newContent = `[](${resp.data.url})`;
353 replaceContent(placeHolderText, newContent);
355 window.$events.emit('error', trans('errors.image_upload_error'));
356 replaceContent(placeHolderText, selectedText);
361 function insertLink() {
362 let cursorPos = cm.getCursor('from');
363 let selectedText = cm.getSelection() || '';
364 let newText = `[${selectedText}]()`;
366 cm.replaceSelection(newText);
367 let cursorPosDiff = (selectedText === '') ? -3 : -1;
368 cm.setCursor(cursorPos.line, cursorPos.ch + newText.length+cursorPosDiff);
371 this.updateAndRender();
374 actionInsertImage() {
375 const cursorPos = this.cm.getCursor('from');
376 window.ImageManager.show(image => {
377 let selectedText = this.cm.getSelection();
378 let newText = "[](" + image.url + ")";
380 this.cm.replaceSelection(newText);
381 this.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
385 actionShowImageManager() {
386 const cursorPos = this.cm.getCursor('from');
387 window.ImageManager.show(image => {
388 this.insertDrawing(image, cursorPos);
392 // Show the popup link selector and insert a link when finished
393 actionShowLinkSelector() {
394 const cursorPos = this.cm.getCursor('from');
395 window.EntitySelectorPopup.show(entity => {
396 let selectedText = this.cm.getSelection() || entity.name;
397 let newText = `[${selectedText}](${entity.link})`;
399 this.cm.replaceSelection(newText);
400 this.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
404 // Show draw.io if enabled and handle save.
405 actionStartDrawing() {
406 if (document.querySelector('[drawio-enabled]').getAttribute('drawio-enabled') !== 'true') return;
407 let cursorPos = this.cm.getCursor('from');
410 return Promise.resolve('');
412 // let id = "image-" + Math.random().toString(16).slice(2);
413 // let loadingImage = window.baseUrl('/loading.gif');
416 uploaded_to: Number(document.getElementById('page-editor').getAttribute('page-id'))
419 window.$http.post(window.baseUrl('/images/drawio'), data).then(resp => {
420 this.insertDrawing(resp.data, cursorPos);
423 window.$events.emit('error', trans('errors.image_upload_error'));
429 insertDrawing(image, originalCursor) {
430 const newText = `<div drawio-diagram="${image.id}"><img src="${image.url}"></div>`;
432 this.cm.replaceSelection(newText);
433 this.cm.setCursor(originalCursor.line, originalCursor.ch + newText.length);
436 // Show draw.io if enabled and handle save.
437 actionEditDrawing(imgContainer) {
438 const drawingDisabled = document.querySelector('[drawio-enabled]').getAttribute('drawio-enabled') !== 'true';
439 if (drawingDisabled) {
443 const cursorPos = this.cm.getCursor('from');
444 const drawingId = imgContainer.getAttribute('drawio-diagram');
447 return DrawIO.load(drawingId);
452 uploaded_to: Number(document.getElementById('page-editor').getAttribute('page-id'))
455 window.$http.post(window.baseUrl(`/images/drawio`), data).then(resp => {
456 let newText = `<div drawio-diagram="${resp.data.id}"><img src="${resp.data.url}"></div>`;
457 let newContent = this.cm.getValue().split('\n').map(line => {
458 if (line.indexOf(`drawio-diagram="${drawingId}"`) !== -1) {
463 this.cm.setValue(newContent);
464 this.cm.setCursor(cursorPos);
468 window.$events.emit('error', trans('errors.image_upload_error'));
474 // Scroll to a specified text
475 scrollToText(searchText) {
480 const content = this.cm.getValue();
481 const lines = content.split(/\r?\n/);
482 let lineNumber = lines.findIndex(line => {
483 return line && line.indexOf(searchText) !== -1;
486 if (lineNumber === -1) {
490 this.cm.scrollIntoView({
494 // set the cursor location.
497 char: lines[lineNumber].length
501 listenForBookStackEditorEvents() {
503 function getContentToInsert({html, markdown}) {
504 return markdown || html;
507 // Replace editor content
508 window.$events.listen('editor::replace', (eventContent) => {
509 const markdown = getContentToInsert(eventContent);
510 this.cm.setValue(markdown);
513 // Append editor content
514 window.$events.listen('editor::append', (eventContent) => {
515 const cursorPos = this.cm.getCursor('from');
516 const markdown = getContentToInsert(eventContent);
517 const content = this.cm.getValue() + '\n' + markdown;
518 this.cm.setValue(content);
519 this.cm.setCursor(cursorPos.line, cursorPos.ch);
522 // Prepend editor content
523 window.$events.listen('editor::prepend', (eventContent) => {
524 const cursorPos = this.cm.getCursor('from');
525 const markdown = getContentToInsert(eventContent);
526 const content = markdown + '\n' + this.cm.getValue();
527 this.cm.setValue(content);
528 const prependLineCount = markdown.split('\n').length;
529 this.cm.setCursor(cursorPos.line + prependLineCount, cursorPos.ch);
534 export default MarkdownEditor ;