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;
39 // Prevent markdown display link click redirect
40 this.displayDoc.addEventListener('click', event => {
41 let isDblClick = Date.now() - lastClick < 300;
43 let link = event.target.closest('a');
45 event.preventDefault();
46 window.open(link.getAttribute('href'));
50 let drawing = event.target.closest('[drawio-diagram]');
51 if (drawing !== null && isDblClick) {
52 this.actionEditDrawing(drawing);
56 lastClick = Date.now();
60 this.elem.addEventListener('click', event => {
61 let button = event.target.closest('button[data-action]');
62 if (button === null) return;
64 let action = button.getAttribute('data-action');
65 if (action === 'insertImage') this.actionInsertImage();
66 if (action === 'insertLink') this.actionShowLinkSelector();
67 if (action === 'insertDrawing' && (event.ctrlKey || event.metaKey)) {
68 this.actionShowImageManager();
71 if (action === 'insertDrawing') this.actionStartDrawing();
74 // Mobile section toggling
75 this.elem.addEventListener('click', event => {
76 const toolbarLabel = event.target.closest('.editor-toolbar-label');
77 if (!toolbarLabel) return;
79 const currentActiveSections = this.elem.querySelectorAll('.markdown-editor-wrap');
80 for (let activeElem of currentActiveSections) {
81 activeElem.classList.remove('active');
84 toolbarLabel.closest('.markdown-editor-wrap').classList.add('active');
87 window.$events.listen('editor-markdown-update', value => {
88 this.cm.setValue(value);
89 this.updateAndRender();
92 this.codeMirrorSetup();
93 this.listenForBookStackEditorEvents();
95 // Scroll to text if needed.
96 const queryParams = (new URL(window.location)).searchParams;
97 const scrollText = queryParams.get('content-text');
99 this.scrollToText(scrollText);
103 // Update the input content and render the display.
105 const content = this.cm.getValue();
106 this.input.value = content;
107 const html = this.markdown.render(content);
108 window.$events.emit('editor-html-change', html);
109 window.$events.emit('editor-markdown-change', content);
112 this.displayDoc.body.className = 'page-content';
113 this.displayDoc.body.innerHTML = html;
114 this.htmlInput.value = html;
116 // Copy styles from page head and set custom styles for editor
117 this.loadStylesIntoDisplay();
120 loadStylesIntoDisplay() {
121 if (this.displayStylesLoaded) return;
122 this.displayDoc.documentElement.className = 'markdown-editor-display';
124 this.displayDoc.head.innerHTML = '';
125 const styles = document.head.querySelectorAll('style,link[rel=stylesheet]');
126 for (let style of styles) {
127 const copy = style.cloneNode(true);
128 this.displayDoc.head.appendChild(copy);
131 this.displayStylesLoaded = true;
134 onMarkdownScroll(lineCount) {
135 const elems = this.displayDoc.body.children;
136 if (elems.length <= lineCount) return;
138 const topElem = (lineCount === -1) ? elems[elems.length-1] : elems[lineCount];
139 topElem.scrollIntoView({ block: 'start', inline: 'nearest', behavior: 'smooth'});
144 const context = this;
147 // cm.setOption('direction', this.textDirection);
148 cm.setOption('direction', 'ltr'); // Will force to remain as ltr for now due to issues when HTML is in editor.
149 // Custom key commands
150 let metaKey = code.getMetaKey();
151 const extraKeys = {};
152 // Insert Image shortcut
153 extraKeys[`${metaKey}-Alt-I`] = function(cm) {
154 let selectedText = cm.getSelection();
155 let newText = ``;
156 let cursorPos = cm.getCursor('from');
157 cm.replaceSelection(newText);
158 cm.setCursor(cursorPos.line, cursorPos.ch + newText.length -1);
161 extraKeys[`${metaKey}-S`] = cm => {window.$events.emit('editor-save-draft')};
163 extraKeys[`${metaKey}-Enter`] = cm => {window.$events.emit('editor-save-page')};
164 // Show link selector
165 extraKeys[`Shift-${metaKey}-K`] = cm => {this.actionShowLinkSelector()};
167 extraKeys[`${metaKey}-K`] = cm => {insertLink()};
169 extraKeys[`${metaKey}-1`] = cm => {replaceLineStart('##');};
170 extraKeys[`${metaKey}-2`] = cm => {replaceLineStart('###');};
171 extraKeys[`${metaKey}-3`] = cm => {replaceLineStart('####');};
172 extraKeys[`${metaKey}-4`] = cm => {replaceLineStart('#####');};
173 extraKeys[`${metaKey}-5`] = cm => {replaceLineStart('');};
174 extraKeys[`${metaKey}-d`] = cm => {replaceLineStart('');};
175 extraKeys[`${metaKey}-6`] = cm => {replaceLineStart('>');};
176 extraKeys[`${metaKey}-q`] = cm => {replaceLineStart('>');};
177 extraKeys[`${metaKey}-7`] = cm => {wrapSelection('\n```\n', '\n```');};
178 extraKeys[`${metaKey}-8`] = cm => {wrapSelection('`', '`');};
179 extraKeys[`Shift-${metaKey}-E`] = cm => {wrapSelection('`', '`');};
180 extraKeys[`${metaKey}-9`] = cm => {wrapSelection('<p class="callout info">', '</p>');};
181 cm.setOption('extraKeys', extraKeys);
183 // Update data on content change
184 cm.on('change', (instance, changeObj) => {
185 this.updateAndRender();
188 const onScrollDebounced = debounce((instance) => {
189 // Thanks to http://liuhao.im/english/2015/11/10/the-sync-scroll-of-markdown-editor-in-javascript.html
190 let scroll = instance.getScrollInfo();
191 let atEnd = scroll.top + scroll.clientHeight === scroll.height;
193 this.onMarkdownScroll(-1);
197 let lineNum = instance.lineAtHeight(scroll.top, 'local');
198 let range = instance.getRange({line: 0, ch: null}, {line: lineNum, ch: null});
199 let parser = new DOMParser();
200 let doc = parser.parseFromString(this.markdown.render(range), 'text/html');
201 let totalLines = doc.documentElement.querySelectorAll('body > *');
202 this.onMarkdownScroll(totalLines.length);
205 // Handle scroll to sync display view
206 cm.on('scroll', instance => {
207 onScrollDebounced(instance);
210 // Handle image paste
211 cm.on('paste', (cm, event) => {
212 const clipboardItems = event.clipboardData.items;
213 if (!event.clipboardData || !clipboardItems) return;
215 // Don't handle if clipboard includes text content
216 for (let clipboardItem of clipboardItems) {
217 if (clipboardItem.type.includes('text/')) {
222 for (let clipboardItem of clipboardItems) {
223 if (clipboardItem.type.includes("image")) {
224 uploadImage(clipboardItem.getAsFile());
229 // Handle image & content drag n drop
230 cm.on('drop', (cm, event) => {
232 const templateId = event.dataTransfer.getData('bookstack/template');
234 const cursorPos = cm.coordsChar({left: event.pageX, top: event.pageY});
235 cm.setCursor(cursorPos);
236 event.preventDefault();
237 window.$http.get(`/templates/${templateId}`).then(resp => {
238 const content = resp.data.markdown || resp.data.html;
239 cm.replaceSelection(content);
243 if (event.dataTransfer && event.dataTransfer.files && event.dataTransfer.files.length > 0) {
244 const cursorPos = cm.coordsChar({left: event.pageX, top: event.pageY});
245 cm.setCursor(cursorPos);
246 event.stopPropagation();
247 event.preventDefault();
248 for (let i = 0; i < event.dataTransfer.files.length; i++) {
249 uploadImage(event.dataTransfer.files[i]);
255 // Helper to replace editor content
256 function replaceContent(search, replace) {
257 let text = cm.getValue();
258 let cursor = cm.listSelections();
259 cm.setValue(text.replace(search, replace));
260 cm.setSelections(cursor);
263 // Helper to replace the start of the line
264 function replaceLineStart(newStart) {
265 let cursor = cm.getCursor();
266 let lineContent = cm.getLine(cursor.line);
267 let lineLen = lineContent.length;
268 let lineStart = lineContent.split(' ')[0];
270 // Remove symbol if already set
271 if (lineStart === newStart) {
272 lineContent = lineContent.replace(`${newStart} `, '');
273 cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
274 cm.setCursor({line: cursor.line, ch: cursor.ch - (newStart.length + 1)});
278 let alreadySymbol = /^[#>`]/.test(lineStart);
281 posDif = newStart.length - lineStart.length;
282 lineContent = lineContent.replace(lineStart, newStart).trim();
283 } else if (newStart !== '') {
284 posDif = newStart.length + 1;
285 lineContent = newStart + ' ' + lineContent;
287 cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
288 cm.setCursor({line: cursor.line, ch: cursor.ch + posDif});
291 function wrapLine(start, end) {
292 let cursor = cm.getCursor();
293 let lineContent = cm.getLine(cursor.line);
294 let lineLen = lineContent.length;
295 let newLineContent = lineContent;
297 if (lineContent.indexOf(start) === 0 && lineContent.slice(-end.length) === end) {
298 newLineContent = lineContent.slice(start.length, lineContent.length - end.length);
300 newLineContent = `${start}${lineContent}${end}`;
303 cm.replaceRange(newLineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
304 cm.setCursor({line: cursor.line, ch: cursor.ch + start.length});
307 function wrapSelection(start, end) {
308 let selection = cm.getSelection();
309 if (selection === '') return wrapLine(start, end);
311 let newSelection = selection;
315 if (selection.indexOf(start) === 0 && selection.slice(-end.length) === end) {
316 newSelection = selection.slice(start.length, selection.length - end.length);
317 endDiff = -(end.length + start.length);
319 newSelection = `${start}${selection}${end}`;
320 endDiff = start.length + end.length;
323 let selections = cm.listSelections()[0];
324 cm.replaceSelection(newSelection);
325 let headFirst = selections.head.ch <= selections.anchor.ch;
326 selections.head.ch += headFirst ? frontDiff : endDiff;
327 selections.anchor.ch += headFirst ? endDiff : frontDiff;
328 cm.setSelections([selections]);
331 // Handle image upload and add image into markdown content
332 function uploadImage(file) {
333 if (file === null || file.type.indexOf('image') !== 0) return;
337 let fileNameMatches = file.name.match(/\.(.+)$/);
338 if (fileNameMatches.length > 1) ext = fileNameMatches[1];
341 // Insert image into markdown
342 const id = "image-" + Math.random().toString(16).slice(2);
343 const placeholderImage = window.baseUrl(`/loading.gif#upload${id}`);
344 const selectedText = cm.getSelection();
345 const placeHolderText = ``;
346 const cursor = cm.getCursor();
347 cm.replaceSelection(placeHolderText);
348 cm.setCursor({line: cursor.line, ch: cursor.ch + selectedText.length + 3});
350 const remoteFilename = "image-" + Date.now() + "." + ext;
351 const formData = new FormData();
352 formData.append('file', file, remoteFilename);
353 formData.append('uploaded_to', context.pageId);
355 window.$http.post('/images/gallery', formData).then(resp => {
356 const newContent = `[](${resp.data.url})`;
357 replaceContent(placeHolderText, newContent);
359 window.$events.emit('error', trans('errors.image_upload_error'));
360 replaceContent(placeHolderText, selectedText);
365 function insertLink() {
366 let cursorPos = cm.getCursor('from');
367 let selectedText = cm.getSelection() || '';
368 let newText = `[${selectedText}]()`;
370 cm.replaceSelection(newText);
371 let cursorPosDiff = (selectedText === '') ? -3 : -1;
372 cm.setCursor(cursorPos.line, cursorPos.ch + newText.length+cursorPosDiff);
375 this.updateAndRender();
378 actionInsertImage() {
379 const cursorPos = this.cm.getCursor('from');
380 window.ImageManager.show(image => {
381 let selectedText = this.cm.getSelection();
382 let newText = "[](" + image.url + ")";
384 this.cm.replaceSelection(newText);
385 this.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
389 actionShowImageManager() {
390 const cursorPos = this.cm.getCursor('from');
391 window.ImageManager.show(image => {
392 this.insertDrawing(image, cursorPos);
396 // Show the popup link selector and insert a link when finished
397 actionShowLinkSelector() {
398 const cursorPos = this.cm.getCursor('from');
399 window.EntitySelectorPopup.show(entity => {
400 let selectedText = this.cm.getSelection() || entity.name;
401 let newText = `[${selectedText}](${entity.link})`;
403 this.cm.replaceSelection(newText);
404 this.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
408 // Show draw.io if enabled and handle save.
409 actionStartDrawing() {
410 if (document.querySelector('[drawio-enabled]').getAttribute('drawio-enabled') !== 'true') return;
411 let cursorPos = this.cm.getCursor('from');
414 return Promise.resolve('');
416 // let id = "image-" + Math.random().toString(16).slice(2);
417 // let loadingImage = window.baseUrl('/loading.gif');
420 uploaded_to: Number(document.getElementById('page-editor').getAttribute('page-id'))
423 window.$http.post(window.baseUrl('/images/drawio'), data).then(resp => {
424 this.insertDrawing(resp.data, cursorPos);
427 window.$events.emit('error', trans('errors.image_upload_error'));
433 insertDrawing(image, originalCursor) {
434 const newText = `<div drawio-diagram="${image.id}"><img src="${image.url}"></div>`;
436 this.cm.replaceSelection(newText);
437 this.cm.setCursor(originalCursor.line, originalCursor.ch + newText.length);
440 // Show draw.io if enabled and handle save.
441 actionEditDrawing(imgContainer) {
442 const drawingDisabled = document.querySelector('[drawio-enabled]').getAttribute('drawio-enabled') !== 'true';
443 if (drawingDisabled) {
447 const cursorPos = this.cm.getCursor('from');
448 const drawingId = imgContainer.getAttribute('drawio-diagram');
451 return DrawIO.load(drawingId);
456 uploaded_to: Number(document.getElementById('page-editor').getAttribute('page-id'))
459 window.$http.post(window.baseUrl(`/images/drawio`), data).then(resp => {
460 let newText = `<div drawio-diagram="${resp.data.id}"><img src="${resp.data.url}"></div>`;
461 let newContent = this.cm.getValue().split('\n').map(line => {
462 if (line.indexOf(`drawio-diagram="${drawingId}"`) !== -1) {
467 this.cm.setValue(newContent);
468 this.cm.setCursor(cursorPos);
472 window.$events.emit('error', trans('errors.image_upload_error'));
478 // Scroll to a specified text
479 scrollToText(searchText) {
484 const content = this.cm.getValue();
485 const lines = content.split(/\r?\n/);
486 let lineNumber = lines.findIndex(line => {
487 return line && line.indexOf(searchText) !== -1;
490 if (lineNumber === -1) {
494 this.cm.scrollIntoView({
498 // set the cursor location.
501 char: lines[lineNumber].length
505 listenForBookStackEditorEvents() {
507 function getContentToInsert({html, markdown}) {
508 return markdown || html;
511 // Replace editor content
512 window.$events.listen('editor::replace', (eventContent) => {
513 const markdown = getContentToInsert(eventContent);
514 this.cm.setValue(markdown);
517 // Append editor content
518 window.$events.listen('editor::append', (eventContent) => {
519 const cursorPos = this.cm.getCursor('from');
520 const markdown = getContentToInsert(eventContent);
521 const content = this.cm.getValue() + '\n' + markdown;
522 this.cm.setValue(content);
523 this.cm.setCursor(cursorPos.line, cursorPos.ch);
526 // Prepend editor content
527 window.$events.listen('editor::prepend', (eventContent) => {
528 const cursorPos = this.cm.getCursor('from');
529 const markdown = getContentToInsert(eventContent);
530 const content = markdown + '\n' + this.cm.getValue();
531 this.cm.setValue(content);
532 const prependLineCount = markdown.split('\n').length;
533 this.cm.setCursor(cursorPos.line + prependLineCount, cursorPos.ch);
538 export default MarkdownEditor ;