1 const MarkdownIt = require("markdown-it");
2 const mdTasksLists = require('markdown-it-task-lists');
3 const code = require('../code');
9 this.markdown = new MarkdownIt({html: true});
10 this.markdown.use(mdTasksLists, {label: true});
12 this.display = this.elem.querySelector('.markdown-display');
13 this.input = this.elem.querySelector('textarea');
14 this.htmlInput = this.elem.querySelector('input[name=html]');
15 this.cm = code.markdownEditor(this.input);
17 this.onMarkdownScroll = this.onMarkdownScroll.bind(this);
23 // Prevent markdown display link click redirect
24 this.display.addEventListener('click', event => {
25 let link = event.target.closest('a');
26 if (link === null) return;
28 event.preventDefault();
29 window.open(link.getAttribute('href'));
33 this.elem.addEventListener('click', event => {
34 let button = event.target.closest('button[data-action]');
35 if (button === null) return;
37 let action = button.getAttribute('data-action');
38 if (action === 'insertImage') this.actionInsertImage();
39 if (action === 'insertLink') this.actionShowLinkSelector();
42 window.$events.listen('editor-markdown-update', value => {
43 this.cm.setValue(value);
44 this.updateAndRender();
47 this.codeMirrorSetup();
50 // Update the input content and render the display.
52 let content = this.cm.getValue();
53 this.input.value = content;
54 let html = this.markdown.render(content);
55 window.$events.emit('editor-html-change', html);
56 window.$events.emit('editor-markdown-change', content);
57 this.display.innerHTML = html;
58 this.htmlInput.value = html;
61 onMarkdownScroll(lineCount) {
62 let elems = this.display.children;
63 if (elems.length <= lineCount) return;
65 let topElem = (lineCount === -1) ? elems[elems.length-1] : elems[lineCount];
66 // TODO - Replace jQuery
67 $(this.display).animate({
68 scrollTop: topElem.offsetTop
69 }, {queue: false, duration: 200, easing: 'linear'});
74 // Custom key commands
75 let metaKey = code.getMetaKey();
77 // Insert Image shortcut
78 extraKeys[`${metaKey}-Alt-I`] = function(cm) {
79 let selectedText = cm.getSelection();
80 let newText = ``;
81 let cursorPos = cm.getCursor('from');
82 cm.replaceSelection(newText);
83 cm.setCursor(cursorPos.line, cursorPos.ch + newText.length -1);
86 extraKeys[`${metaKey}-S`] = cm => {window.$events.emit('editor-save-draft')};
88 extraKeys[`Shift-${metaKey}-K`] = cm => {this.actionShowLinkSelector()};
90 extraKeys[`${metaKey}-K`] = cm => {insertLink()};
92 extraKeys[`${metaKey}-1`] = cm => {replaceLineStart('##');};
93 extraKeys[`${metaKey}-2`] = cm => {replaceLineStart('###');};
94 extraKeys[`${metaKey}-3`] = cm => {replaceLineStart('####');};
95 extraKeys[`${metaKey}-4`] = cm => {replaceLineStart('#####');};
96 extraKeys[`${metaKey}-5`] = cm => {replaceLineStart('');};
97 extraKeys[`${metaKey}-d`] = cm => {replaceLineStart('');};
98 extraKeys[`${metaKey}-6`] = cm => {replaceLineStart('>');};
99 extraKeys[`${metaKey}-q`] = cm => {replaceLineStart('>');};
100 extraKeys[`${metaKey}-7`] = cm => {wrapSelection('\n```\n', '\n```');};
101 extraKeys[`${metaKey}-8`] = cm => {wrapSelection('`', '`');};
102 extraKeys[`Shift-${metaKey}-E`] = cm => {wrapSelection('`', '`');};
103 extraKeys[`${metaKey}-9`] = cm => {wrapSelection('<p class="callout info">', '</p>');};
104 cm.setOption('extraKeys', extraKeys);
106 // Update data on content change
107 cm.on('change', (instance, changeObj) => {
108 this.updateAndRender();
111 // Handle scroll to sync display view
112 cm.on('scroll', instance => {
113 // Thanks to http://liuhao.im/english/2015/11/10/the-sync-scroll-of-markdown-editor-in-javascript.html
114 let scroll = instance.getScrollInfo();
115 let atEnd = scroll.top + scroll.clientHeight === scroll.height;
117 this.onMarkdownScroll(-1);
121 let lineNum = instance.lineAtHeight(scroll.top, 'local');
122 let range = instance.getRange({line: 0, ch: null}, {line: lineNum, ch: null});
123 let parser = new DOMParser();
124 let doc = parser.parseFromString(this.markdown.render(range), 'text/html');
125 let totalLines = doc.documentElement.querySelectorAll('body > *');
126 this.onMarkdownScroll(totalLines.length);
129 // Handle image paste
130 cm.on('paste', (cm, event) => {
131 if (!event.clipboardData || !event.clipboardData.items) return;
132 for (let i = 0; i < event.clipboardData.items.length; i++) {
133 uploadImage(event.clipboardData.items[i].getAsFile());
137 // Handle images on drag-drop
138 cm.on('drop', (cm, event) => {
139 event.stopPropagation();
140 event.preventDefault();
141 let cursorPos = cm.coordsChar({left: event.pageX, top: event.pageY});
142 cm.setCursor(cursorPos);
143 if (!event.dataTransfer || !event.dataTransfer.files) return;
144 for (let i = 0; i < event.dataTransfer.files.length; i++) {
145 uploadImage(event.dataTransfer.files[i]);
149 // Helper to replace editor content
150 function replaceContent(search, replace) {
151 let text = cm.getValue();
152 let cursor = cm.listSelections();
153 cm.setValue(text.replace(search, replace));
154 cm.setSelections(cursor);
157 // Helper to replace the start of the line
158 function replaceLineStart(newStart) {
159 let cursor = cm.getCursor();
160 let lineContent = cm.getLine(cursor.line);
161 let lineLen = lineContent.length;
162 let lineStart = lineContent.split(' ')[0];
164 // Remove symbol if already set
165 if (lineStart === newStart) {
166 lineContent = lineContent.replace(`${newStart} `, '');
167 cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
168 cm.setCursor({line: cursor.line, ch: cursor.ch - (newStart.length + 1)});
172 let alreadySymbol = /^[#>`]/.test(lineStart);
175 posDif = newStart.length - lineStart.length;
176 lineContent = lineContent.replace(lineStart, newStart).trim();
177 } else if (newStart !== '') {
178 posDif = newStart.length + 1;
179 lineContent = newStart + ' ' + lineContent;
181 cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
182 cm.setCursor({line: cursor.line, ch: cursor.ch + posDif});
185 function wrapLine(start, end) {
186 let cursor = cm.getCursor();
187 let lineContent = cm.getLine(cursor.line);
188 let lineLen = lineContent.length;
189 let newLineContent = lineContent;
191 if (lineContent.indexOf(start) === 0 && lineContent.slice(-end.length) === end) {
192 newLineContent = lineContent.slice(start.length, lineContent.length - end.length);
194 newLineContent = `${start}${lineContent}${end}`;
197 cm.replaceRange(newLineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
198 cm.setCursor({line: cursor.line, ch: cursor.ch + start.length});
201 function wrapSelection(start, end) {
202 let selection = cm.getSelection();
203 if (selection === '') return wrapLine(start, end);
205 let newSelection = selection;
209 if (selection.indexOf(start) === 0 && selection.slice(-end.length) === end) {
210 newSelection = selection.slice(start.length, selection.length - end.length);
211 endDiff = -(end.length + start.length);
213 newSelection = `${start}${selection}${end}`;
214 endDiff = start.length + end.length;
217 let selections = cm.listSelections()[0];
218 cm.replaceSelection(newSelection);
219 let headFirst = selections.head.ch <= selections.anchor.ch;
220 selections.head.ch += headFirst ? frontDiff : endDiff;
221 selections.anchor.ch += headFirst ? endDiff : frontDiff;
222 cm.setSelections([selections]);
225 // Handle image upload and add image into markdown content
226 function uploadImage(file) {
227 if (file === null || file.type.indexOf('image') !== 0) return;
231 let fileNameMatches = file.name.match(/\.(.+)$/);
232 if (fileNameMatches.length > 1) ext = fileNameMatches[1];
235 // Insert image into markdown
236 let id = "image-" + Math.random().toString(16).slice(2);
237 let placeholderImage = window.baseUrl(`/loading.gif#upload${id}`);
238 let selectedText = cm.getSelection();
239 let placeHolderText = ``;
240 cm.replaceSelection(placeHolderText);
242 let remoteFilename = "image-" + Date.now() + "." + ext;
243 let formData = new FormData();
244 formData.append('file', file, remoteFilename);
246 window.$http.post('/images/gallery/upload', formData).then(resp => {
247 replaceContent(placeholderImage, resp.data.thumbs.display);
249 events.emit('error', trans('errors.image_upload_error'));
250 replaceContent(placeHolderText, selectedText);
255 function insertLink() {
256 let cursorPos = cm.getCursor('from');
257 let selectedText = cm.getSelection() || '';
258 let newText = `[${selectedText}]()`;
260 cm.replaceSelection(newText);
261 let cursorPosDiff = (selectedText === '') ? -3 : -1;
262 cm.setCursor(cursorPos.line, cursorPos.ch + newText.length+cursorPosDiff);
265 this.updateAndRender();
268 actionInsertImage() {
269 let cursorPos = this.cm.getCursor('from');
270 window.ImageManager.show(image => {
271 let selectedText = this.cm.getSelection();
272 let newText = "";
274 this.cm.replaceSelection(newText);
275 this.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
279 // Show the popup link selector and insert a link when finished
280 actionShowLinkSelector() {
281 let cursorPos = this.cm.getCursor('from');
282 window.EntitySelectorPopup.show(entity => {
283 let selectedText = this.cm.getSelection() || entity.name;
284 let newText = `[${selectedText}](${entity.link})`;
286 this.cm.replaceSelection(newText);
287 this.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
293 module.exports = MarkdownEditor ;