1 const MarkdownIt = require("markdown-it");
2 const mdTasksLists = require('markdown-it-task-lists');
3 const code = require('../libs/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[`${metaKey}-Enter`] = cm => {window.$events.emit('editor-save-page')};
90 extraKeys[`Shift-${metaKey}-K`] = cm => {this.actionShowLinkSelector()};
92 extraKeys[`${metaKey}-K`] = cm => {insertLink()};
94 extraKeys[`${metaKey}-1`] = cm => {replaceLineStart('##');};
95 extraKeys[`${metaKey}-2`] = cm => {replaceLineStart('###');};
96 extraKeys[`${metaKey}-3`] = cm => {replaceLineStart('####');};
97 extraKeys[`${metaKey}-4`] = cm => {replaceLineStart('#####');};
98 extraKeys[`${metaKey}-5`] = cm => {replaceLineStart('');};
99 extraKeys[`${metaKey}-d`] = cm => {replaceLineStart('');};
100 extraKeys[`${metaKey}-6`] = cm => {replaceLineStart('>');};
101 extraKeys[`${metaKey}-q`] = cm => {replaceLineStart('>');};
102 extraKeys[`${metaKey}-7`] = cm => {wrapSelection('\n```\n', '\n```');};
103 extraKeys[`${metaKey}-8`] = cm => {wrapSelection('`', '`');};
104 extraKeys[`Shift-${metaKey}-E`] = cm => {wrapSelection('`', '`');};
105 extraKeys[`${metaKey}-9`] = cm => {wrapSelection('<p class="callout info">', '</p>');};
106 cm.setOption('extraKeys', extraKeys);
108 // Update data on content change
109 cm.on('change', (instance, changeObj) => {
110 this.updateAndRender();
113 // Handle scroll to sync display view
114 cm.on('scroll', instance => {
115 // Thanks to http://liuhao.im/english/2015/11/10/the-sync-scroll-of-markdown-editor-in-javascript.html
116 let scroll = instance.getScrollInfo();
117 let atEnd = scroll.top + scroll.clientHeight === scroll.height;
119 this.onMarkdownScroll(-1);
123 let lineNum = instance.lineAtHeight(scroll.top, 'local');
124 let range = instance.getRange({line: 0, ch: null}, {line: lineNum, ch: null});
125 let parser = new DOMParser();
126 let doc = parser.parseFromString(this.markdown.render(range), 'text/html');
127 let totalLines = doc.documentElement.querySelectorAll('body > *');
128 this.onMarkdownScroll(totalLines.length);
131 // Handle image paste
132 cm.on('paste', (cm, event) => {
133 if (!event.clipboardData || !event.clipboardData.items) return;
134 for (let i = 0; i < event.clipboardData.items.length; i++) {
135 uploadImage(event.clipboardData.items[i].getAsFile());
139 // Handle images on drag-drop
140 cm.on('drop', (cm, event) => {
141 event.stopPropagation();
142 event.preventDefault();
143 let cursorPos = cm.coordsChar({left: event.pageX, top: event.pageY});
144 cm.setCursor(cursorPos);
145 if (!event.dataTransfer || !event.dataTransfer.files) return;
146 for (let i = 0; i < event.dataTransfer.files.length; i++) {
147 uploadImage(event.dataTransfer.files[i]);
151 // Helper to replace editor content
152 function replaceContent(search, replace) {
153 let text = cm.getValue();
154 let cursor = cm.listSelections();
155 cm.setValue(text.replace(search, replace));
156 cm.setSelections(cursor);
159 // Helper to replace the start of the line
160 function replaceLineStart(newStart) {
161 let cursor = cm.getCursor();
162 let lineContent = cm.getLine(cursor.line);
163 let lineLen = lineContent.length;
164 let lineStart = lineContent.split(' ')[0];
166 // Remove symbol if already set
167 if (lineStart === newStart) {
168 lineContent = lineContent.replace(`${newStart} `, '');
169 cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
170 cm.setCursor({line: cursor.line, ch: cursor.ch - (newStart.length + 1)});
174 let alreadySymbol = /^[#>`]/.test(lineStart);
177 posDif = newStart.length - lineStart.length;
178 lineContent = lineContent.replace(lineStart, newStart).trim();
179 } else if (newStart !== '') {
180 posDif = newStart.length + 1;
181 lineContent = newStart + ' ' + lineContent;
183 cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
184 cm.setCursor({line: cursor.line, ch: cursor.ch + posDif});
187 function wrapLine(start, end) {
188 let cursor = cm.getCursor();
189 let lineContent = cm.getLine(cursor.line);
190 let lineLen = lineContent.length;
191 let newLineContent = lineContent;
193 if (lineContent.indexOf(start) === 0 && lineContent.slice(-end.length) === end) {
194 newLineContent = lineContent.slice(start.length, lineContent.length - end.length);
196 newLineContent = `${start}${lineContent}${end}`;
199 cm.replaceRange(newLineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
200 cm.setCursor({line: cursor.line, ch: cursor.ch + start.length});
203 function wrapSelection(start, end) {
204 let selection = cm.getSelection();
205 if (selection === '') return wrapLine(start, end);
207 let newSelection = selection;
211 if (selection.indexOf(start) === 0 && selection.slice(-end.length) === end) {
212 newSelection = selection.slice(start.length, selection.length - end.length);
213 endDiff = -(end.length + start.length);
215 newSelection = `${start}${selection}${end}`;
216 endDiff = start.length + end.length;
219 let selections = cm.listSelections()[0];
220 cm.replaceSelection(newSelection);
221 let headFirst = selections.head.ch <= selections.anchor.ch;
222 selections.head.ch += headFirst ? frontDiff : endDiff;
223 selections.anchor.ch += headFirst ? endDiff : frontDiff;
224 cm.setSelections([selections]);
227 // Handle image upload and add image into markdown content
228 function uploadImage(file) {
229 if (file === null || file.type.indexOf('image') !== 0) return;
233 let fileNameMatches = file.name.match(/\.(.+)$/);
234 if (fileNameMatches.length > 1) ext = fileNameMatches[1];
237 // Insert image into markdown
238 let id = "image-" + Math.random().toString(16).slice(2);
239 let placeholderImage = window.baseUrl(`/loading.gif#upload${id}`);
240 let selectedText = cm.getSelection();
241 let placeHolderText = ``;
242 cm.replaceSelection(placeHolderText);
244 let remoteFilename = "image-" + Date.now() + "." + ext;
245 let formData = new FormData();
246 formData.append('file', file, remoteFilename);
248 window.$http.post('/images/gallery/upload', formData).then(resp => {
249 replaceContent(placeholderImage, resp.data.thumbs.display);
251 events.emit('error', trans('errors.image_upload_error'));
252 replaceContent(placeHolderText, selectedText);
257 function insertLink() {
258 let cursorPos = cm.getCursor('from');
259 let selectedText = cm.getSelection() || '';
260 let newText = `[${selectedText}]()`;
262 cm.replaceSelection(newText);
263 let cursorPosDiff = (selectedText === '') ? -3 : -1;
264 cm.setCursor(cursorPos.line, cursorPos.ch + newText.length+cursorPosDiff);
267 this.updateAndRender();
270 actionInsertImage() {
271 let cursorPos = this.cm.getCursor('from');
272 window.ImageManager.show(image => {
273 let selectedText = this.cm.getSelection();
274 let newText = "";
276 this.cm.replaceSelection(newText);
277 this.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
281 // Show the popup link selector and insert a link when finished
282 actionShowLinkSelector() {
283 let cursorPos = this.cm.getCursor('from');
284 window.EntitySelectorPopup.show(entity => {
285 let selectedText = this.cm.getSelection() || entity.name;
286 let newText = `[${selectedText}](${entity.link})`;
288 this.cm.replaceSelection(newText);
289 this.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
295 module.exports = MarkdownEditor ;