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.input = this.elem.querySelector('textarea');
22 this.htmlInput = this.elem.querySelector('input[name=html]');
23 this.cm = code.markdownEditor(this.input);
25 this.onMarkdownScroll = this.onMarkdownScroll.bind(this);
28 // Scroll to text if needed.
29 const queryParams = (new URL(window.location)).searchParams;
30 const scrollText = queryParams.get('content-text');
32 this.scrollToText(scrollText);
40 // Prevent markdown display link click redirect
41 this.display.addEventListener('click', event => {
42 let isDblClick = Date.now() - lastClick < 300;
44 let link = event.target.closest('a');
46 event.preventDefault();
47 window.open(link.getAttribute('href'));
51 let drawing = event.target.closest('[drawio-diagram]');
52 if (drawing !== null && isDblClick) {
53 this.actionEditDrawing(drawing);
57 lastClick = Date.now();
61 this.elem.addEventListener('click', event => {
62 let button = event.target.closest('button[data-action]');
63 if (button === null) return;
65 let action = button.getAttribute('data-action');
66 if (action === 'insertImage') this.actionInsertImage();
67 if (action === 'insertLink') this.actionShowLinkSelector();
68 if (action === 'insertDrawing' && (event.ctrlKey || event.metaKey)) {
69 this.actionShowImageManager();
72 if (action === 'insertDrawing') this.actionStartDrawing();
75 // Mobile section toggling
76 this.elem.addEventListener('click', event => {
77 const toolbarLabel = event.target.closest('.editor-toolbar-label');
78 if (!toolbarLabel) return;
80 const currentActiveSections = this.elem.querySelectorAll('.markdown-editor-wrap');
81 for (let activeElem of currentActiveSections) {
82 activeElem.classList.remove('active');
85 toolbarLabel.closest('.markdown-editor-wrap').classList.add('active');
88 window.$events.listen('editor-markdown-update', value => {
89 this.cm.setValue(value);
90 this.updateAndRender();
93 this.codeMirrorSetup();
94 this.listenForBookStackEditorEvents();
97 // Update the input content and render the display.
99 let content = this.cm.getValue();
100 this.input.value = content;
101 let html = this.markdown.render(content);
102 window.$events.emit('editor-html-change', html);
103 window.$events.emit('editor-markdown-change', content);
104 this.display.innerHTML = html;
105 this.htmlInput.value = html;
108 onMarkdownScroll(lineCount) {
109 const elems = this.display.children;
110 if (elems.length <= lineCount) return;
112 const topElem = (lineCount === -1) ? elems[elems.length-1] : elems[lineCount];
113 topElem.scrollIntoView({ block: 'start', inline: 'nearest', behavior: 'smooth'});
118 const context = this;
121 // cm.setOption('direction', this.textDirection);
122 cm.setOption('direction', 'ltr'); // Will force to remain as ltr for now due to issues when HTML is in editor.
123 // Custom key commands
124 let metaKey = code.getMetaKey();
125 const extraKeys = {};
126 // Insert Image shortcut
127 extraKeys[`${metaKey}-Alt-I`] = function(cm) {
128 let selectedText = cm.getSelection();
129 let newText = ``;
130 let cursorPos = cm.getCursor('from');
131 cm.replaceSelection(newText);
132 cm.setCursor(cursorPos.line, cursorPos.ch + newText.length -1);
135 extraKeys[`${metaKey}-S`] = cm => {window.$events.emit('editor-save-draft')};
137 extraKeys[`${metaKey}-Enter`] = cm => {window.$events.emit('editor-save-page')};
138 // Show link selector
139 extraKeys[`Shift-${metaKey}-K`] = cm => {this.actionShowLinkSelector()};
141 extraKeys[`${metaKey}-K`] = cm => {insertLink()};
143 extraKeys[`${metaKey}-1`] = cm => {replaceLineStart('##');};
144 extraKeys[`${metaKey}-2`] = cm => {replaceLineStart('###');};
145 extraKeys[`${metaKey}-3`] = cm => {replaceLineStart('####');};
146 extraKeys[`${metaKey}-4`] = cm => {replaceLineStart('#####');};
147 extraKeys[`${metaKey}-5`] = cm => {replaceLineStart('');};
148 extraKeys[`${metaKey}-d`] = cm => {replaceLineStart('');};
149 extraKeys[`${metaKey}-6`] = cm => {replaceLineStart('>');};
150 extraKeys[`${metaKey}-q`] = cm => {replaceLineStart('>');};
151 extraKeys[`${metaKey}-7`] = cm => {wrapSelection('\n```\n', '\n```');};
152 extraKeys[`${metaKey}-8`] = cm => {wrapSelection('`', '`');};
153 extraKeys[`Shift-${metaKey}-E`] = cm => {wrapSelection('`', '`');};
154 extraKeys[`${metaKey}-9`] = cm => {wrapSelection('<p class="callout info">', '</p>');};
155 cm.setOption('extraKeys', extraKeys);
157 // Update data on content change
158 cm.on('change', (instance, changeObj) => {
159 this.updateAndRender();
162 const onScrollDebounced = debounce((instance) => {
163 // Thanks to http://liuhao.im/english/2015/11/10/the-sync-scroll-of-markdown-editor-in-javascript.html
164 let scroll = instance.getScrollInfo();
165 let atEnd = scroll.top + scroll.clientHeight === scroll.height;
167 this.onMarkdownScroll(-1);
171 let lineNum = instance.lineAtHeight(scroll.top, 'local');
172 let range = instance.getRange({line: 0, ch: null}, {line: lineNum, ch: null});
173 let parser = new DOMParser();
174 let doc = parser.parseFromString(this.markdown.render(range), 'text/html');
175 let totalLines = doc.documentElement.querySelectorAll('body > *');
176 this.onMarkdownScroll(totalLines.length);
179 // Handle scroll to sync display view
180 cm.on('scroll', instance => {
181 onScrollDebounced(instance);
184 // Handle image paste
185 cm.on('paste', (cm, event) => {
186 const clipboardItems = event.clipboardData.items;
187 if (!event.clipboardData || !clipboardItems) return;
189 // Don't handle if clipboard includes text content
190 for (let clipboardItem of clipboardItems) {
191 if (clipboardItem.type.includes('text/')) {
196 for (let clipboardItem of clipboardItems) {
197 if (clipboardItem.type.includes("image")) {
198 uploadImage(clipboardItem.getAsFile());
203 // Handle images on drag-drop
204 cm.on('drop', (cm, event) => {
205 event.stopPropagation();
206 event.preventDefault();
207 let cursorPos = cm.coordsChar({left: event.pageX, top: event.pageY});
208 cm.setCursor(cursorPos);
209 if (!event.dataTransfer || !event.dataTransfer.files) return;
210 for (let i = 0; i < event.dataTransfer.files.length; i++) {
211 uploadImage(event.dataTransfer.files[i]);
215 // Helper to replace editor content
216 function replaceContent(search, replace) {
217 let text = cm.getValue();
218 let cursor = cm.listSelections();
219 cm.setValue(text.replace(search, replace));
220 cm.setSelections(cursor);
223 // Helper to replace the start of the line
224 function replaceLineStart(newStart) {
225 let cursor = cm.getCursor();
226 let lineContent = cm.getLine(cursor.line);
227 let lineLen = lineContent.length;
228 let lineStart = lineContent.split(' ')[0];
230 // Remove symbol if already set
231 if (lineStart === newStart) {
232 lineContent = lineContent.replace(`${newStart} `, '');
233 cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
234 cm.setCursor({line: cursor.line, ch: cursor.ch - (newStart.length + 1)});
238 let alreadySymbol = /^[#>`]/.test(lineStart);
241 posDif = newStart.length - lineStart.length;
242 lineContent = lineContent.replace(lineStart, newStart).trim();
243 } else if (newStart !== '') {
244 posDif = newStart.length + 1;
245 lineContent = newStart + ' ' + lineContent;
247 cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
248 cm.setCursor({line: cursor.line, ch: cursor.ch + posDif});
251 function wrapLine(start, end) {
252 let cursor = cm.getCursor();
253 let lineContent = cm.getLine(cursor.line);
254 let lineLen = lineContent.length;
255 let newLineContent = lineContent;
257 if (lineContent.indexOf(start) === 0 && lineContent.slice(-end.length) === end) {
258 newLineContent = lineContent.slice(start.length, lineContent.length - end.length);
260 newLineContent = `${start}${lineContent}${end}`;
263 cm.replaceRange(newLineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
264 cm.setCursor({line: cursor.line, ch: cursor.ch + start.length});
267 function wrapSelection(start, end) {
268 let selection = cm.getSelection();
269 if (selection === '') return wrapLine(start, end);
271 let newSelection = selection;
275 if (selection.indexOf(start) === 0 && selection.slice(-end.length) === end) {
276 newSelection = selection.slice(start.length, selection.length - end.length);
277 endDiff = -(end.length + start.length);
279 newSelection = `${start}${selection}${end}`;
280 endDiff = start.length + end.length;
283 let selections = cm.listSelections()[0];
284 cm.replaceSelection(newSelection);
285 let headFirst = selections.head.ch <= selections.anchor.ch;
286 selections.head.ch += headFirst ? frontDiff : endDiff;
287 selections.anchor.ch += headFirst ? endDiff : frontDiff;
288 cm.setSelections([selections]);
291 // Handle image upload and add image into markdown content
292 function uploadImage(file) {
293 if (file === null || file.type.indexOf('image') !== 0) return;
297 let fileNameMatches = file.name.match(/\.(.+)$/);
298 if (fileNameMatches.length > 1) ext = fileNameMatches[1];
301 // Insert image into markdown
302 const id = "image-" + Math.random().toString(16).slice(2);
303 const placeholderImage = window.baseUrl(`/loading.gif#upload${id}`);
304 const selectedText = cm.getSelection();
305 const placeHolderText = ``;
306 const cursor = cm.getCursor();
307 cm.replaceSelection(placeHolderText);
308 cm.setCursor({line: cursor.line, ch: cursor.ch + selectedText.length + 3});
310 const remoteFilename = "image-" + Date.now() + "." + ext;
311 const formData = new FormData();
312 formData.append('file', file, remoteFilename);
313 formData.append('uploaded_to', context.pageId);
315 window.$http.post('/images/gallery', formData).then(resp => {
316 const newContent = `[](${resp.data.url})`;
317 replaceContent(placeHolderText, newContent);
319 window.$events.emit('error', trans('errors.image_upload_error'));
320 replaceContent(placeHolderText, selectedText);
325 function insertLink() {
326 let cursorPos = cm.getCursor('from');
327 let selectedText = cm.getSelection() || '';
328 let newText = `[${selectedText}]()`;
330 cm.replaceSelection(newText);
331 let cursorPosDiff = (selectedText === '') ? -3 : -1;
332 cm.setCursor(cursorPos.line, cursorPos.ch + newText.length+cursorPosDiff);
335 this.updateAndRender();
338 actionInsertImage() {
339 const cursorPos = this.cm.getCursor('from');
340 window.ImageManager.show(image => {
341 let selectedText = this.cm.getSelection();
342 let newText = "[](" + image.url + ")";
344 this.cm.replaceSelection(newText);
345 this.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
349 actionShowImageManager() {
350 const cursorPos = this.cm.getCursor('from');
351 window.ImageManager.show(image => {
352 this.insertDrawing(image, cursorPos);
356 // Show the popup link selector and insert a link when finished
357 actionShowLinkSelector() {
358 const cursorPos = this.cm.getCursor('from');
359 window.EntitySelectorPopup.show(entity => {
360 let selectedText = this.cm.getSelection() || entity.name;
361 let newText = `[${selectedText}](${entity.link})`;
363 this.cm.replaceSelection(newText);
364 this.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
368 // Show draw.io if enabled and handle save.
369 actionStartDrawing() {
370 if (document.querySelector('[drawio-enabled]').getAttribute('drawio-enabled') !== 'true') return;
371 let cursorPos = this.cm.getCursor('from');
374 return Promise.resolve('');
376 // let id = "image-" + Math.random().toString(16).slice(2);
377 // let loadingImage = window.baseUrl('/loading.gif');
380 uploaded_to: Number(document.getElementById('page-editor').getAttribute('page-id'))
383 window.$http.post(window.baseUrl('/images/drawio'), data).then(resp => {
384 this.insertDrawing(resp.data, cursorPos);
387 window.$events.emit('error', trans('errors.image_upload_error'));
393 insertDrawing(image, originalCursor) {
394 const newText = `<div drawio-diagram="${image.id}"><img src="${image.url}"></div>`;
396 this.cm.replaceSelection(newText);
397 this.cm.setCursor(originalCursor.line, originalCursor.ch + newText.length);
400 // Show draw.io if enabled and handle save.
401 actionEditDrawing(imgContainer) {
402 const drawingDisabled = document.querySelector('[drawio-enabled]').getAttribute('drawio-enabled') !== 'true';
403 if (drawingDisabled) {
407 const cursorPos = this.cm.getCursor('from');
408 const drawingId = imgContainer.getAttribute('drawio-diagram');
411 return DrawIO.load(drawingId);
416 uploaded_to: Number(document.getElementById('page-editor').getAttribute('page-id'))
419 window.$http.post(window.baseUrl(`/images/drawio`), data).then(resp => {
420 let newText = `<div drawio-diagram="${resp.data.id}"><img src="${resp.data.url}"></div>`;
421 let newContent = this.cm.getValue().split('\n').map(line => {
422 if (line.indexOf(`drawio-diagram="${drawingId}"`) !== -1) {
427 this.cm.setValue(newContent);
428 this.cm.setCursor(cursorPos);
432 window.$events.emit('error', trans('errors.image_upload_error'));
438 // Scroll to a specified text
439 scrollToText(searchText) {
444 const content = this.cm.getValue();
445 const lines = content.split(/\r?\n/);
446 let lineNumber = lines.findIndex(line => {
447 return line && line.indexOf(searchText) !== -1;
450 if (lineNumber === -1) {
454 this.cm.scrollIntoView({
458 // set the cursor location.
461 char: lines[lineNumber].length
465 listenForBookStackEditorEvents() {
467 function getContentToInsert({html, markdown}) {
468 return markdown || html;
471 // Replace editor content
472 window.$events.listen('editor::replace', (eventContent) => {
473 const markdown = getContentToInsert(eventContent);
474 this.cm.setValue(markdown);
477 // Append editor content
478 window.$events.listen('editor::append', (eventContent) => {
479 const cursorPos = this.cm.getCursor('from');
480 const markdown = getContentToInsert(eventContent);
481 const content = this.cm.getValue() + '\n' + markdown;
482 this.cm.setValue(content);
483 this.cm.setCursor(cursorPos.line, cursorPos.ch);
486 // Prepend editor content
487 window.$events.listen('editor::prepend', (eventContent) => {
488 const cursorPos = this.cm.getCursor('from');
489 const markdown = getContentToInsert(eventContent);
490 const content = markdown + '\n' + this.cm.getValue();
491 this.cm.setValue(content);
492 const prependLineCount = markdown.split('\n').length;
493 this.cm.setCursor(cursorPos.line + prependLineCount, cursorPos.ch);
498 export default MarkdownEditor ;