2 const MarkdownIt = require("markdown-it");
3 const mdTasksLists = require('markdown-it-task-lists');
4 const code = require('./code');
6 module.exports = function (ngApp, events) {
10 * An angular wrapper around the tinyMCE editor.
12 ngApp.directive('tinymce', ['$timeout', function ($timeout) {
20 link: function (scope, element, attrs) {
22 function tinyMceSetup(editor) {
23 editor.on('ExecCommand change input NodeChange ObjectResized', (e) => {
24 let content = editor.getContent();
26 scope.mceModel = content;
28 scope.mceChange(content);
31 editor.on('keydown', (event) => {
32 if (event.keyCode === 83 && (navigator.platform.match("Mac") ? event.metaKey : event.ctrlKey)) {
33 event.preventDefault();
34 scope.$emit('save-draft', event);
38 editor.on('init', (e) => {
39 scope.mceModel = editor.getContent();
42 scope.$on('html-update', (event, value) => {
43 editor.setContent(value);
44 editor.selection.select(editor.getBody(), true);
45 editor.selection.collapse(false);
46 scope.mceModel = editor.getContent();
50 scope.tinymce.extraSetups.push(tinyMceSetup);
51 tinymce.init(scope.tinymce);
56 const md = new MarkdownIt({html: true});
57 md.use(mdTasksLists, {label: true});
61 * Handles the logic for just the editor input field.
63 ngApp.directive('markdownInput', ['$timeout', function ($timeout) {
70 link: function (scope, element, attrs) {
73 element = element.find('textarea').first();
74 let cm = code.markdownEditor(element[0]);
76 // Custom key commands
77 let metaKey = code.getMetaKey();
79 // Insert Image shortcut
80 extraKeys[`${metaKey}-Alt-I`] = function(cm) {
81 let selectedText = cm.getSelection();
82 let newText = ``;
83 let cursorPos = cm.getCursor('from');
84 cm.replaceSelection(newText);
85 cm.setCursor(cursorPos.line, cursorPos.ch + newText.length -1);
88 extraKeys[`${metaKey}-S`] = function(cm) {scope.$emit('save-draft');};
90 extraKeys[`Shift-${metaKey}-K`] = function(cm) {showLinkSelector()};
92 extraKeys[`${metaKey}-K`] = function(cm) {insertLink()};
94 extraKeys[`${metaKey}-1`] = function(cm) {replaceLineStart('##');};
95 extraKeys[`${metaKey}-2`] = function(cm) {replaceLineStart('###');};
96 extraKeys[`${metaKey}-3`] = function(cm) {replaceLineStart('####');};
97 extraKeys[`${metaKey}-4`] = function(cm) {replaceLineStart('#####');};
98 extraKeys[`${metaKey}-5`] = function(cm) {replaceLineStart('');};
99 extraKeys[`${metaKey}-d`] = function(cm) {replaceLineStart('');};
100 extraKeys[`${metaKey}-6`] = function(cm) {replaceLineStart('>');};
101 extraKeys[`${metaKey}-q`] = function(cm) {replaceLineStart('>');};
102 extraKeys[`${metaKey}-7`] = function(cm) {wrapSelection('\n```\n', '\n```');};
103 extraKeys[`${metaKey}-8`] = function(cm) {wrapSelection('`', '`');};
104 extraKeys[`Shift-${metaKey}-E`] = function(cm) {wrapSelection('`', '`');};
105 extraKeys[`${metaKey}-9`] = function(cm) {wrapSelection('<p class="callout info">', '</p>');};
106 cm.setOption('extraKeys', extraKeys);
108 // Update data on content change
109 cm.on('change', (instance, changeObj) => {
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 scope.$emit('markdown-scroll', -1);
122 let lineNum = instance.lineAtHeight(scroll.top, 'local');
123 let range = instance.getRange({line: 0, ch: null}, {line: lineNum, ch: null});
124 let parser = new DOMParser();
125 let doc = parser.parseFromString(md.render(range), 'text/html');
126 let totalLines = doc.documentElement.querySelectorAll('body > *');
127 scope.$emit('markdown-scroll', totalLines.length);
130 // Handle image paste
131 cm.on('paste', (cm, event) => {
132 if (!event.clipboardData || !event.clipboardData.items) return;
133 for (let i = 0; i < event.clipboardData.items.length; i++) {
134 uploadImage(event.clipboardData.items[i].getAsFile());
138 // Handle images on drag-drop
139 cm.on('drop', (cm, event) => {
140 event.stopPropagation();
141 event.preventDefault();
142 let cursorPos = cm.coordsChar({left: event.pageX, top: event.pageY});
143 cm.setCursor(cursorPos);
144 if (!event.dataTransfer || !event.dataTransfer.files) return;
145 for (let i = 0; i < event.dataTransfer.files.length; i++) {
146 uploadImage(event.dataTransfer.files[i]);
150 // Helper to replace editor content
151 function replaceContent(search, replace) {
152 let text = cm.getValue();
153 let cursor = cm.listSelections();
154 cm.setValue(text.replace(search, replace));
155 cm.setSelections(cursor);
158 // Helper to replace the start of the line
159 function replaceLineStart(newStart) {
160 let cursor = cm.getCursor();
161 let lineContent = cm.getLine(cursor.line);
162 let lineLen = lineContent.length;
163 let lineStart = lineContent.split(' ')[0];
165 // Remove symbol if already set
166 if (lineStart === newStart) {
167 lineContent = lineContent.replace(`${newStart} `, '');
168 cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
169 cm.setCursor({line: cursor.line, ch: cursor.ch - (newStart.length + 1)});
173 let alreadySymbol = /^[#>`]/.test(lineStart);
176 posDif = newStart.length - lineStart.length;
177 lineContent = lineContent.replace(lineStart, newStart).trim();
178 } else if (newStart !== '') {
179 posDif = newStart.length + 1;
180 lineContent = newStart + ' ' + lineContent;
182 cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
183 cm.setCursor({line: cursor.line, ch: cursor.ch + posDif});
186 function wrapLine(start, end) {
187 let cursor = cm.getCursor();
188 let lineContent = cm.getLine(cursor.line);
189 let lineLen = lineContent.length;
190 let newLineContent = lineContent;
192 if (lineContent.indexOf(start) === 0 && lineContent.slice(-end.length) === end) {
193 newLineContent = lineContent.slice(start.length, lineContent.length - end.length);
195 newLineContent = `${start}${lineContent}${end}`;
198 cm.replaceRange(newLineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
199 cm.setCursor({line: cursor.line, ch: cursor.ch + start.length});
202 function wrapSelection(start, end) {
203 let selection = cm.getSelection();
204 if (selection === '') return wrapLine(start, end);
206 let newSelection = selection;
210 if (selection.indexOf(start) === 0 && selection.slice(-end.length) === end) {
211 newSelection = selection.slice(start.length, selection.length - end.length);
212 endDiff = -(end.length + start.length);
214 newSelection = `${start}${selection}${end}`;
215 endDiff = start.length + end.length;
218 let selections = cm.listSelections()[0];
219 cm.replaceSelection(newSelection);
220 let headFirst = selections.head.ch <= selections.anchor.ch;
221 selections.head.ch += headFirst ? frontDiff : endDiff;
222 selections.anchor.ch += headFirst ? endDiff : frontDiff;
223 cm.setSelections([selections]);
226 // Handle image upload and add image into markdown content
227 function uploadImage(file) {
228 if (file === null || file.type.indexOf('image') !== 0) return;
232 let fileNameMatches = file.name.match(/\.(.+)$/);
233 if (fileNameMatches.length > 1) ext = fileNameMatches[1];
236 // Insert image into markdown
237 let id = "image-" + Math.random().toString(16).slice(2);
238 let placeholderImage = window.baseUrl(`/loading.gif#upload${id}`);
239 let selectedText = cm.getSelection();
240 let placeHolderText = ``;
241 cm.replaceSelection(placeHolderText);
243 let remoteFilename = "image-" + Date.now() + "." + ext;
244 let formData = new FormData();
245 formData.append('file', file, remoteFilename);
247 window.$http.post('/images/gallery/upload', formData).then(resp => {
248 replaceContent(placeholderImage, resp.data.thumbs.display);
250 events.emit('error', trans('errors.image_upload_error'));
251 replaceContent(placeHolderText, selectedText);
256 // Show the popup link selector and insert a link when finished
257 function showLinkSelector() {
258 let cursorPos = cm.getCursor('from');
259 window.EntitySelectorPopup.show(entity => {
260 let selectedText = cm.getSelection() || entity.name;
261 let newText = `[${selectedText}](${entity.link})`;
263 cm.replaceSelection(newText);
264 cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
268 function insertLink() {
269 let cursorPos = cm.getCursor('from');
270 let selectedText = cm.getSelection() || '';
271 let newText = `[${selectedText}]()`;
273 cm.replaceSelection(newText);
274 let cursorPosDiff = (selectedText === '') ? -3 : -1;
275 cm.setCursor(cursorPos.line, cursorPos.ch + newText.length+cursorPosDiff);
278 // Show the image manager and handle image insertion
279 function showImageManager() {
280 let cursorPos = cm.getCursor('from');
281 window.ImageManager.show(image => {
282 let selectedText = cm.getSelection();
283 let newText = "";
285 cm.replaceSelection(newText);
286 cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
290 // Update the data models and rendered output
291 function update(instance) {
292 let content = instance.getValue();
293 element.val(content);
295 scope.mdModel = content;
296 scope.mdChange(md.render(content));
301 // Listen to commands from parent scope
302 scope.$on('md-insert-link', showLinkSelector);
303 scope.$on('md-insert-image', showImageManager);
304 scope.$on('markdown-update', (event, value) => {
307 scope.mdModel = value;
308 scope.mdChange(md.render(value));
317 * Handles all functionality of the markdown editor.
319 ngApp.directive('markdownEditor', ['$timeout', '$rootScope', function ($timeout, $rootScope) {
322 link: function (scope, element, attrs) {
325 const $display = element.find('.markdown-display').first();
326 const $insertImage = element.find('button[data-action="insertImage"]');
327 const $insertEntityLink = element.find('button[data-action="insertEntityLink"]');
329 // Prevent markdown display link click redirect
330 $display.on('click', 'a', function(event) {
331 event.preventDefault();
332 window.open(this.getAttribute('href'));
336 $insertEntityLink.click(e => {scope.$broadcast('md-insert-link');});
337 $insertImage.click(e => {scope.$broadcast('md-insert-image');});
339 // Handle scroll sync event from editor scroll
340 $rootScope.$on('markdown-scroll', (event, lineCount) => {
341 let elems = $display[0].children[0].children;
342 if (elems.length > lineCount) {
343 let topElem = (lineCount === -1) ? elems[elems.length-1] : elems[lineCount];
345 scrollTop: topElem.offsetTop
346 }, {queue: false, duration: 200, easing: 'linear'});
354 * Page Editor Toolbox
355 * Controls all functionality for the sliding toolbox
356 * on the page edit view.
358 ngApp.directive('toolbox', [function () {
361 link: function (scope, elem, attrs) {
363 // Get common elements
364 const $buttons = elem.find('[toolbox-tab-button]');
365 const $content = elem.find('[toolbox-tab-content]');
366 const $toggle = elem.find('[toolbox-toggle]');
368 // Handle toolbox toggle click
369 $toggle.click((e) => {
370 elem.toggleClass('open');
373 // Set an active tab/content by name
374 function setActive(tabName, openToolbox) {
375 $buttons.removeClass('active');
377 $buttons.filter(`[toolbox-tab-button="${tabName}"]`).addClass('active');
378 $content.filter(`[toolbox-tab-content="${tabName}"]`).show();
379 if (openToolbox) elem.addClass('open');
382 // Set the first tab content active on load
383 setActive($content.first().attr('toolbox-tab-content'), false);
385 // Handle tab button click
386 $buttons.click(function (e) {
387 let name = $(this).attr('toolbox-tab-button');
388 setActive(name, true);