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 NodeChange ObjectResized', (e) => {
24 let content = editor.getContent();
26 scope.mceModel = content;
28 scope.mceChange(content);
31 editor.on('keydown', (event) => {
32 scope.$emit('editor-keydown', event);
35 editor.on('init', (e) => {
36 scope.mceModel = editor.getContent();
39 scope.$on('html-update', (event, value) => {
40 editor.setContent(value);
41 editor.selection.select(editor.getBody(), true);
42 editor.selection.collapse(false);
43 scope.mceModel = editor.getContent();
47 scope.tinymce.extraSetups.push(tinyMceSetup);
48 tinymce.init(scope.tinymce);
53 const md = new MarkdownIt({html: true});
54 md.use(mdTasksLists, {label: true});
58 * Handles the logic for just the editor input field.
60 ngApp.directive('markdownInput', ['$timeout', function ($timeout) {
67 link: function (scope, element, attrs) {
70 element = element.find('textarea').first();
71 let cm = code.markdownEditor(element[0]);
73 // Custom key commands
74 let metaKey = code.getMetaKey();
76 // Insert Image shortcut
77 extraKeys[`${metaKey}-Alt-I`] = function(cm) {
78 let selectedText = cm.getSelection();
79 let newText = ``;
80 let cursorPos = cm.getCursor('from');
81 cm.replaceSelection(newText);
82 cm.setCursor(cursorPos.line, cursorPos.ch + newText.length -1);
85 extraKeys[`${metaKey}-S`] = function(cm) {scope.$emit('save-draft');};
87 extraKeys[`Shift-${metaKey}-K`] = function(cm) {showLinkSelector()};
89 extraKeys[`${metaKey}-K`] = function(cm) {insertLink()};
91 extraKeys[`${metaKey}-1`] = function(cm) {replaceLineStart('##');};
92 extraKeys[`${metaKey}-2`] = function(cm) {replaceLineStart('###');};
93 extraKeys[`${metaKey}-3`] = function(cm) {replaceLineStart('####');};
94 extraKeys[`${metaKey}-4`] = function(cm) {replaceLineStart('#####');};
95 extraKeys[`${metaKey}-5`] = function(cm) {replaceLineStart('');};
96 extraKeys[`${metaKey}-d`] = function(cm) {replaceLineStart('');};
97 extraKeys[`${metaKey}-6`] = function(cm) {replaceLineStart('>');};
98 extraKeys[`${metaKey}-q`] = function(cm) {replaceLineStart('>');};
99 extraKeys[`${metaKey}-7`] = function(cm) {wrapSelection('\n```\n', '\n```');};
100 extraKeys[`${metaKey}-8`] = function(cm) {wrapSelection('`', '`');};
101 extraKeys[`Shift-${metaKey}-E`] = function(cm) {wrapSelection('`', '`');};
102 extraKeys[`${metaKey}-9`] = function(cm) {wrapSelection('<p class="callout info">', '</p>');};
103 cm.setOption('extraKeys', extraKeys);
105 // Update data on content change
106 cm.on('change', (instance, changeObj) => {
110 // Handle scroll to sync display view
111 cm.on('scroll', instance => {
112 // Thanks to http://liuhao.im/english/2015/11/10/the-sync-scroll-of-markdown-editor-in-javascript.html
113 let scroll = instance.getScrollInfo();
114 let atEnd = scroll.top + scroll.clientHeight === scroll.height;
116 scope.$emit('markdown-scroll', -1);
119 let lineNum = instance.lineAtHeight(scroll.top, 'local');
120 let range = instance.getRange({line: 0, ch: null}, {line: lineNum, ch: null});
121 let parser = new DOMParser();
122 let doc = parser.parseFromString(md.render(range), 'text/html');
123 let totalLines = doc.documentElement.querySelectorAll('body > *');
124 scope.$emit('markdown-scroll', totalLines.length);
127 // Handle image paste
128 cm.on('paste', (cm, event) => {
129 if (!event.clipboardData || !event.clipboardData.items) return;
130 for (let i = 0; i < event.clipboardData.items.length; i++) {
131 uploadImage(event.clipboardData.items[i].getAsFile());
135 // Handle images on drag-drop
136 cm.on('drop', (cm, event) => {
137 event.stopPropagation();
138 event.preventDefault();
139 let cursorPos = cm.coordsChar({left: event.pageX, top: event.pageY});
140 cm.setCursor(cursorPos);
141 if (!event.dataTransfer || !event.dataTransfer.files) return;
142 for (let i = 0; i < event.dataTransfer.files.length; i++) {
143 uploadImage(event.dataTransfer.files[i]);
147 // Helper to replace editor content
148 function replaceContent(search, replace) {
149 let text = cm.getValue();
150 let cursor = cm.listSelections();
151 cm.setValue(text.replace(search, replace));
152 cm.setSelections(cursor);
155 // Helper to replace the start of the line
156 function replaceLineStart(newStart) {
157 let cursor = cm.getCursor();
158 let lineContent = cm.getLine(cursor.line);
159 let lineLen = lineContent.length;
160 let lineStart = lineContent.split(' ')[0];
162 // Remove symbol if already set
163 if (lineStart === newStart) {
164 lineContent = lineContent.replace(`${newStart} `, '');
165 cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
166 cm.setCursor({line: cursor.line, ch: cursor.ch - (newStart.length + 1)});
170 let alreadySymbol = /^[#>`]/.test(lineStart);
173 posDif = newStart.length - lineStart.length;
174 lineContent = lineContent.replace(lineStart, newStart).trim();
175 } else if (newStart !== '') {
176 posDif = newStart.length + 1;
177 lineContent = newStart + ' ' + lineContent;
179 cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
180 cm.setCursor({line: cursor.line, ch: cursor.ch + posDif});
183 function wrapLine(start, end) {
184 let cursor = cm.getCursor();
185 let lineContent = cm.getLine(cursor.line);
186 let lineLen = lineContent.length;
187 let newLineContent = lineContent;
189 if (lineContent.indexOf(start) === 0 && lineContent.slice(-end.length) === end) {
190 newLineContent = lineContent.slice(start.length, lineContent.length - end.length);
192 newLineContent = `${start}${lineContent}${end}`;
195 cm.replaceRange(newLineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
196 cm.setCursor({line: cursor.line, ch: cursor.ch + start.length});
199 function wrapSelection(start, end) {
200 let selection = cm.getSelection();
201 if (selection === '') return wrapLine(start, end);
203 let newSelection = selection;
207 if (selection.indexOf(start) === 0 && selection.slice(-end.length) === end) {
208 newSelection = selection.slice(start.length, selection.length - end.length);
209 endDiff = -(end.length + start.length);
211 newSelection = `${start}${selection}${end}`;
212 endDiff = start.length + end.length;
215 let selections = cm.listSelections()[0];
216 cm.replaceSelection(newSelection);
217 let headFirst = selections.head.ch <= selections.anchor.ch;
218 selections.head.ch += headFirst ? frontDiff : endDiff;
219 selections.anchor.ch += headFirst ? endDiff : frontDiff;
220 cm.setSelections([selections]);
223 // Handle image upload and add image into markdown content
224 function uploadImage(file) {
225 if (file === null || file.type.indexOf('image') !== 0) return;
229 let fileNameMatches = file.name.match(/\.(.+)$/);
230 if (fileNameMatches.length > 1) ext = fileNameMatches[1];
233 // Insert image into markdown
234 let id = "image-" + Math.random().toString(16).slice(2);
235 let placeholderImage = window.baseUrl(`/loading.gif#upload${id}`);
236 let selectedText = cm.getSelection();
237 let placeHolderText = ``;
238 cm.replaceSelection(placeHolderText);
240 let remoteFilename = "image-" + Date.now() + "." + ext;
241 let formData = new FormData();
242 formData.append('file', file, remoteFilename);
244 window.$http.post('/images/gallery/upload', formData).then(resp => {
245 replaceContent(placeholderImage, resp.data.thumbs.display);
247 events.emit('error', trans('errors.image_upload_error'));
248 replaceContent(placeHolderText, selectedText);
253 // Show the popup link selector and insert a link when finished
254 function showLinkSelector() {
255 let cursorPos = cm.getCursor('from');
256 window.EntitySelectorPopup.show(entity => {
257 let selectedText = cm.getSelection() || entity.name;
258 let newText = `[${selectedText}](${entity.link})`;
260 cm.replaceSelection(newText);
261 cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
265 function insertLink() {
266 let cursorPos = cm.getCursor('from');
267 let selectedText = cm.getSelection() || '';
268 let newText = `[${selectedText}]()`;
270 cm.replaceSelection(newText);
271 let cursorPosDiff = (selectedText === '') ? -3 : -1;
272 cm.setCursor(cursorPos.line, cursorPos.ch + newText.length+cursorPosDiff);
275 // Show the image manager and handle image insertion
276 function showImageManager() {
277 let cursorPos = cm.getCursor('from');
278 window.ImageManager.show(image => {
279 let selectedText = cm.getSelection();
280 let newText = "";
282 cm.replaceSelection(newText);
283 cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
287 // Update the data models and rendered output
288 function update(instance) {
289 let content = instance.getValue();
290 element.val(content);
292 scope.mdModel = content;
293 scope.mdChange(md.render(content));
298 // Listen to commands from parent scope
299 scope.$on('md-insert-link', showLinkSelector);
300 scope.$on('md-insert-image', showImageManager);
301 scope.$on('markdown-update', (event, value) => {
304 scope.mdModel = value;
305 scope.mdChange(md.render(value));
314 * Handles all functionality of the markdown editor.
316 ngApp.directive('markdownEditor', ['$timeout', '$rootScope', function ($timeout, $rootScope) {
319 link: function (scope, element, attrs) {
322 const $display = element.find('.markdown-display').first();
323 const $insertImage = element.find('button[data-action="insertImage"]');
324 const $insertEntityLink = element.find('button[data-action="insertEntityLink"]');
326 // Prevent markdown display link click redirect
327 $display.on('click', 'a', function(event) {
328 event.preventDefault();
329 window.open(this.getAttribute('href'));
333 $insertEntityLink.click(e => {scope.$broadcast('md-insert-link');});
334 $insertImage.click(e => {scope.$broadcast('md-insert-image');});
336 // Handle scroll sync event from editor scroll
337 $rootScope.$on('markdown-scroll', (event, lineCount) => {
338 let elems = $display[0].children[0].children;
339 if (elems.length > lineCount) {
340 let topElem = (lineCount === -1) ? elems[elems.length-1] : elems[lineCount];
342 scrollTop: topElem.offsetTop
343 }, {queue: false, duration: 200, easing: 'linear'});
351 * Page Editor Toolbox
352 * Controls all functionality for the sliding toolbox
353 * on the page edit view.
355 ngApp.directive('toolbox', [function () {
358 link: function (scope, elem, attrs) {
360 // Get common elements
361 const $buttons = elem.find('[toolbox-tab-button]');
362 const $content = elem.find('[toolbox-tab-content]');
363 const $toggle = elem.find('[toolbox-toggle]');
365 // Handle toolbox toggle click
366 $toggle.click((e) => {
367 elem.toggleClass('open');
370 // Set an active tab/content by name
371 function setActive(tabName, openToolbox) {
372 $buttons.removeClass('active');
374 $buttons.filter(`[toolbox-tab-button="${tabName}"]`).addClass('active');
375 $content.filter(`[toolbox-tab-content="${tabName}"]`).show();
376 if (openToolbox) elem.addClass('open');
379 // Set the first tab content active on load
380 setActive($content.first().attr('toolbox-tab-content'), false);
382 // Handle tab button click
383 $buttons.click(function (e) {
384 let name = $(this).attr('toolbox-tab-button');
385 setActive(name, true);