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 images on drag-drop
226 cm.on('drop', (cm, event) => {
227 event.stopPropagation();
228 event.preventDefault();
229 let cursorPos = cm.coordsChar({left: event.pageX, top: event.pageY});
230 cm.setCursor(cursorPos);
231 if (!event.dataTransfer || !event.dataTransfer.files) return;
232 for (let i = 0; i < event.dataTransfer.files.length; i++) {
233 uploadImage(event.dataTransfer.files[i]);
237 // Helper to replace editor content
238 function replaceContent(search, replace) {
239 let text = cm.getValue();
240 let cursor = cm.listSelections();
241 cm.setValue(text.replace(search, replace));
242 cm.setSelections(cursor);
245 // Helper to replace the start of the line
246 function replaceLineStart(newStart) {
247 let cursor = cm.getCursor();
248 let lineContent = cm.getLine(cursor.line);
249 let lineLen = lineContent.length;
250 let lineStart = lineContent.split(' ')[0];
252 // Remove symbol if already set
253 if (lineStart === newStart) {
254 lineContent = lineContent.replace(`${newStart} `, '');
255 cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
256 cm.setCursor({line: cursor.line, ch: cursor.ch - (newStart.length + 1)});
260 let alreadySymbol = /^[#>`]/.test(lineStart);
263 posDif = newStart.length - lineStart.length;
264 lineContent = lineContent.replace(lineStart, newStart).trim();
265 } else if (newStart !== '') {
266 posDif = newStart.length + 1;
267 lineContent = newStart + ' ' + lineContent;
269 cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
270 cm.setCursor({line: cursor.line, ch: cursor.ch + posDif});
273 function wrapLine(start, end) {
274 let cursor = cm.getCursor();
275 let lineContent = cm.getLine(cursor.line);
276 let lineLen = lineContent.length;
277 let newLineContent = lineContent;
279 if (lineContent.indexOf(start) === 0 && lineContent.slice(-end.length) === end) {
280 newLineContent = lineContent.slice(start.length, lineContent.length - end.length);
282 newLineContent = `${start}${lineContent}${end}`;
285 cm.replaceRange(newLineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
286 cm.setCursor({line: cursor.line, ch: cursor.ch + start.length});
289 function wrapSelection(start, end) {
290 let selection = cm.getSelection();
291 if (selection === '') return wrapLine(start, end);
293 let newSelection = selection;
297 if (selection.indexOf(start) === 0 && selection.slice(-end.length) === end) {
298 newSelection = selection.slice(start.length, selection.length - end.length);
299 endDiff = -(end.length + start.length);
301 newSelection = `${start}${selection}${end}`;
302 endDiff = start.length + end.length;
305 let selections = cm.listSelections()[0];
306 cm.replaceSelection(newSelection);
307 let headFirst = selections.head.ch <= selections.anchor.ch;
308 selections.head.ch += headFirst ? frontDiff : endDiff;
309 selections.anchor.ch += headFirst ? endDiff : frontDiff;
310 cm.setSelections([selections]);
313 // Handle image upload and add image into markdown content
314 function uploadImage(file) {
315 if (file === null || file.type.indexOf('image') !== 0) return;
319 let fileNameMatches = file.name.match(/\.(.+)$/);
320 if (fileNameMatches.length > 1) ext = fileNameMatches[1];
323 // Insert image into markdown
324 const id = "image-" + Math.random().toString(16).slice(2);
325 const placeholderImage = window.baseUrl(`/loading.gif#upload${id}`);
326 const selectedText = cm.getSelection();
327 const placeHolderText = ``;
328 const cursor = cm.getCursor();
329 cm.replaceSelection(placeHolderText);
330 cm.setCursor({line: cursor.line, ch: cursor.ch + selectedText.length + 3});
332 const remoteFilename = "image-" + Date.now() + "." + ext;
333 const formData = new FormData();
334 formData.append('file', file, remoteFilename);
335 formData.append('uploaded_to', context.pageId);
337 window.$http.post('/images/gallery', formData).then(resp => {
338 const newContent = `[](${resp.data.url})`;
339 replaceContent(placeHolderText, newContent);
341 window.$events.emit('error', trans('errors.image_upload_error'));
342 replaceContent(placeHolderText, selectedText);
347 function insertLink() {
348 let cursorPos = cm.getCursor('from');
349 let selectedText = cm.getSelection() || '';
350 let newText = `[${selectedText}]()`;
352 cm.replaceSelection(newText);
353 let cursorPosDiff = (selectedText === '') ? -3 : -1;
354 cm.setCursor(cursorPos.line, cursorPos.ch + newText.length+cursorPosDiff);
357 this.updateAndRender();
360 actionInsertImage() {
361 const cursorPos = this.cm.getCursor('from');
362 window.ImageManager.show(image => {
363 let selectedText = this.cm.getSelection();
364 let newText = "[](" + image.url + ")";
366 this.cm.replaceSelection(newText);
367 this.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
371 actionShowImageManager() {
372 const cursorPos = this.cm.getCursor('from');
373 window.ImageManager.show(image => {
374 this.insertDrawing(image, cursorPos);
378 // Show the popup link selector and insert a link when finished
379 actionShowLinkSelector() {
380 const cursorPos = this.cm.getCursor('from');
381 window.EntitySelectorPopup.show(entity => {
382 let selectedText = this.cm.getSelection() || entity.name;
383 let newText = `[${selectedText}](${entity.link})`;
385 this.cm.replaceSelection(newText);
386 this.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
390 // Show draw.io if enabled and handle save.
391 actionStartDrawing() {
392 if (document.querySelector('[drawio-enabled]').getAttribute('drawio-enabled') !== 'true') return;
393 let cursorPos = this.cm.getCursor('from');
396 return Promise.resolve('');
398 // let id = "image-" + Math.random().toString(16).slice(2);
399 // let loadingImage = window.baseUrl('/loading.gif');
402 uploaded_to: Number(document.getElementById('page-editor').getAttribute('page-id'))
405 window.$http.post(window.baseUrl('/images/drawio'), data).then(resp => {
406 this.insertDrawing(resp.data, cursorPos);
409 window.$events.emit('error', trans('errors.image_upload_error'));
415 insertDrawing(image, originalCursor) {
416 const newText = `<div drawio-diagram="${image.id}"><img src="${image.url}"></div>`;
418 this.cm.replaceSelection(newText);
419 this.cm.setCursor(originalCursor.line, originalCursor.ch + newText.length);
422 // Show draw.io if enabled and handle save.
423 actionEditDrawing(imgContainer) {
424 const drawingDisabled = document.querySelector('[drawio-enabled]').getAttribute('drawio-enabled') !== 'true';
425 if (drawingDisabled) {
429 const cursorPos = this.cm.getCursor('from');
430 const drawingId = imgContainer.getAttribute('drawio-diagram');
433 return DrawIO.load(drawingId);
438 uploaded_to: Number(document.getElementById('page-editor').getAttribute('page-id'))
441 window.$http.post(window.baseUrl(`/images/drawio`), data).then(resp => {
442 let newText = `<div drawio-diagram="${resp.data.id}"><img src="${resp.data.url}"></div>`;
443 let newContent = this.cm.getValue().split('\n').map(line => {
444 if (line.indexOf(`drawio-diagram="${drawingId}"`) !== -1) {
449 this.cm.setValue(newContent);
450 this.cm.setCursor(cursorPos);
454 window.$events.emit('error', trans('errors.image_upload_error'));
460 // Scroll to a specified text
461 scrollToText(searchText) {
466 const content = this.cm.getValue();
467 const lines = content.split(/\r?\n/);
468 let lineNumber = lines.findIndex(line => {
469 return line && line.indexOf(searchText) !== -1;
472 if (lineNumber === -1) {
476 this.cm.scrollIntoView({
480 // set the cursor location.
483 char: lines[lineNumber].length
487 listenForBookStackEditorEvents() {
489 function getContentToInsert({html, markdown}) {
490 return markdown || html;
493 // Replace editor content
494 window.$events.listen('editor::replace', (eventContent) => {
495 const markdown = getContentToInsert(eventContent);
496 this.cm.setValue(markdown);
499 // Append editor content
500 window.$events.listen('editor::append', (eventContent) => {
501 const cursorPos = this.cm.getCursor('from');
502 const markdown = getContentToInsert(eventContent);
503 const content = this.cm.getValue() + '\n' + markdown;
504 this.cm.setValue(content);
505 this.cm.setCursor(cursorPos.line, cursorPos.ch);
508 // Prepend editor content
509 window.$events.listen('editor::prepend', (eventContent) => {
510 const cursorPos = this.cm.getCursor('from');
511 const markdown = getContentToInsert(eventContent);
512 const content = markdown + '\n' + this.cm.getValue();
513 this.cm.setValue(content);
514 const prependLineCount = markdown.split('\n').length;
515 this.cm.setCursor(cursorPos.line + prependLineCount, cursorPos.ch);
520 export default MarkdownEditor ;