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">', '</div>');};
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 + (newLineContent.length - lineLen)});
199 function wrapSelection(start, end) {
200 let selection = cm.getSelection();
201 if (selection === '') return wrapLine(start, end);
202 let newSelection = selection;
206 if (selection.indexOf(start) === 0 && selection.slice(-end.length) === end) {
207 newSelection = selection.slice(start.length, selection.length - end.length);
208 endDiff = -(end.length + start.length);
210 newSelection = `${start}${selection}${end}`;
211 endDiff = start.length + end.length;
214 let selections = cm.listSelections()[0];
215 cm.replaceSelection(newSelection);
216 let headFirst = selections.head.ch <= selections.anchor.ch;
217 selections.head.ch += headFirst ? frontDiff : endDiff;
218 selections.anchor.ch += headFirst ? endDiff : frontDiff;
219 cm.setSelections([selections]);
222 // Handle image upload and add image into markdown content
223 function uploadImage(file) {
224 if (file === null || file.type.indexOf('image') !== 0) return;
228 let fileNameMatches = file.name.match(/\.(.+)$/);
229 if (fileNameMatches.length > 1) ext = fileNameMatches[1];
232 // Insert image into markdown
233 let id = "image-" + Math.random().toString(16).slice(2);
234 let placeholderImage = window.baseUrl(`/loading.gif#upload${id}`);
235 let selectedText = cm.getSelection();
236 let placeHolderText = ``;
237 cm.replaceSelection(placeHolderText);
239 let remoteFilename = "image-" + Date.now() + "." + ext;
240 let formData = new FormData();
241 formData.append('file', file, remoteFilename);
243 window.$http.post('/images/gallery/upload', formData).then(resp => {
244 replaceContent(placeholderImage, resp.data.thumbs.display);
246 events.emit('error', trans('errors.image_upload_error'));
247 replaceContent(placeHolderText, selectedText);
252 // Show the popup link selector and insert a link when finished
253 function showLinkSelector() {
254 let cursorPos = cm.getCursor('from');
255 window.EntitySelectorPopup.show(entity => {
256 let selectedText = cm.getSelection() || entity.name;
257 let newText = `[${selectedText}](${entity.link})`;
259 cm.replaceSelection(newText);
260 cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
264 function insertLink() {
265 let cursorPos = cm.getCursor('from');
266 let selectedText = cm.getSelection() || '';
267 let newText = `[${selectedText}]()`;
269 cm.replaceSelection(newText);
270 let cursorPosDiff = (selectedText === '') ? -3 : -1;
271 cm.setCursor(cursorPos.line, cursorPos.ch + newText.length+cursorPosDiff);
274 // Show the image manager and handle image insertion
275 function showImageManager() {
276 let cursorPos = cm.getCursor('from');
277 window.ImageManager.show(image => {
278 let selectedText = cm.getSelection();
279 let newText = "";
281 cm.replaceSelection(newText);
282 cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
286 // Update the data models and rendered output
287 function update(instance) {
288 let content = instance.getValue();
289 element.val(content);
291 scope.mdModel = content;
292 scope.mdChange(md.render(content));
297 // Listen to commands from parent scope
298 scope.$on('md-insert-link', showLinkSelector);
299 scope.$on('md-insert-image', showImageManager);
300 scope.$on('markdown-update', (event, value) => {
303 scope.mdModel = value;
304 scope.mdChange(md.render(value));
313 * Handles all functionality of the markdown editor.
315 ngApp.directive('markdownEditor', ['$timeout', '$rootScope', function ($timeout, $rootScope) {
318 link: function (scope, element, attrs) {
321 const $display = element.find('.markdown-display').first();
322 const $insertImage = element.find('button[data-action="insertImage"]');
323 const $insertEntityLink = element.find('button[data-action="insertEntityLink"]');
325 // Prevent markdown display link click redirect
326 $display.on('click', 'a', function(event) {
327 event.preventDefault();
328 window.open(this.getAttribute('href'));
332 $insertEntityLink.click(e => {scope.$broadcast('md-insert-link');});
333 $insertImage.click(e => {scope.$broadcast('md-insert-image');});
335 // Handle scroll sync event from editor scroll
336 $rootScope.$on('markdown-scroll', (event, lineCount) => {
337 let elems = $display[0].children[0].children;
338 if (elems.length > lineCount) {
339 let topElem = (lineCount === -1) ? elems[elems.length-1] : elems[lineCount];
341 scrollTop: topElem.offsetTop
342 }, {queue: false, duration: 200, easing: 'linear'});
350 * Page Editor Toolbox
351 * Controls all functionality for the sliding toolbox
352 * on the page edit view.
354 ngApp.directive('toolbox', [function () {
357 link: function (scope, elem, attrs) {
359 // Get common elements
360 const $buttons = elem.find('[toolbox-tab-button]');
361 const $content = elem.find('[toolbox-tab-content]');
362 const $toggle = elem.find('[toolbox-toggle]');
364 // Handle toolbox toggle click
365 $toggle.click((e) => {
366 elem.toggleClass('open');
369 // Set an active tab/content by name
370 function setActive(tabName, openToolbox) {
371 $buttons.removeClass('active');
373 $buttons.filter(`[toolbox-tab-button="${tabName}"]`).addClass('active');
374 $content.filter(`[toolbox-tab-content="${tabName}"]`).show();
375 if (openToolbox) elem.addClass('open');
378 // Set the first tab content active on load
379 setActive($content.first().attr('toolbox-tab-content'), false);
381 // Handle tab button click
382 $buttons.click(function (e) {
383 let name = $(this).attr('toolbox-tab-button');
384 setActive(name, true);