mirror of
https://github.com/BookStackApp/BookStack.git
synced 2024-08-25 19:56:05 +00:00
Migrated editor inputs to non-angular JS
This commit is contained in:
parent
0c4ddf16a5
commit
9e2934fe17
@ -11,6 +11,8 @@ let componentMapping = {
|
||||
'sidebar': require('./sidebar'),
|
||||
'page-picker': require('./page-picker'),
|
||||
'page-comments': require('./page-comments'),
|
||||
'wysiwyg-editor': require('./wysiwyg-editor'),
|
||||
'markdown-editor': require('./markdown-editor'),
|
||||
};
|
||||
|
||||
window.components = {};
|
||||
|
293
resources/assets/js/components/markdown-editor.js
Normal file
293
resources/assets/js/components/markdown-editor.js
Normal file
@ -0,0 +1,293 @@
|
||||
const MarkdownIt = require("markdown-it");
|
||||
const mdTasksLists = require('markdown-it-task-lists');
|
||||
const code = require('../code');
|
||||
|
||||
class MarkdownEditor {
|
||||
|
||||
constructor(elem) {
|
||||
this.elem = elem;
|
||||
this.markdown = new MarkdownIt({html: true});
|
||||
this.markdown.use(mdTasksLists, {label: true});
|
||||
|
||||
this.display = this.elem.querySelector('.markdown-display');
|
||||
this.input = this.elem.querySelector('textarea');
|
||||
this.htmlInput = this.elem.querySelector('input[name=html]');
|
||||
this.cm = code.markdownEditor(this.input);
|
||||
|
||||
this.onMarkdownScroll = this.onMarkdownScroll.bind(this);
|
||||
this.init();
|
||||
}
|
||||
|
||||
init() {
|
||||
|
||||
// Prevent markdown display link click redirect
|
||||
this.display.addEventListener('click', event => {
|
||||
let link = event.target.closest('a');
|
||||
if (link === null) return;
|
||||
|
||||
event.preventDefault();
|
||||
window.open(link.getAttribute('href'));
|
||||
});
|
||||
|
||||
// Button actions
|
||||
this.elem.addEventListener('click', event => {
|
||||
let button = event.target.closest('button[data-action]');
|
||||
if (button === null) return;
|
||||
|
||||
let action = button.getAttribute('data-action');
|
||||
if (action === 'insertImage') this.actionInsertImage();
|
||||
if (action === 'insertLink') this.actionShowLinkSelector();
|
||||
});
|
||||
|
||||
window.$events.listen('editor-markdown-update', value => {
|
||||
this.cm.setValue(value);
|
||||
this.updateAndRender();
|
||||
});
|
||||
|
||||
this.codeMirrorSetup();
|
||||
}
|
||||
|
||||
// Update the input content and render the display.
|
||||
updateAndRender() {
|
||||
let content = this.cm.getValue();
|
||||
this.input.value = content;
|
||||
let html = this.markdown.render(content);
|
||||
window.$events.emit('editor-html-change', html);
|
||||
window.$events.emit('editor-markdown-change', content);
|
||||
this.display.innerHTML = html;
|
||||
this.htmlInput.value = html;
|
||||
}
|
||||
|
||||
onMarkdownScroll(lineCount) {
|
||||
let elems = this.display.children;
|
||||
if (elems.length <= lineCount) return;
|
||||
|
||||
let topElem = (lineCount === -1) ? elems[elems.length-1] : elems[lineCount];
|
||||
// TODO - Replace jQuery
|
||||
$(this.display).animate({
|
||||
scrollTop: topElem.offsetTop
|
||||
}, {queue: false, duration: 200, easing: 'linear'});
|
||||
}
|
||||
|
||||
codeMirrorSetup() {
|
||||
let cm = this.cm;
|
||||
// Custom key commands
|
||||
let metaKey = code.getMetaKey();
|
||||
const extraKeys = {};
|
||||
// Insert Image shortcut
|
||||
extraKeys[`${metaKey}-Alt-I`] = function(cm) {
|
||||
let selectedText = cm.getSelection();
|
||||
let newText = `![${selectedText}](http://)`;
|
||||
let cursorPos = cm.getCursor('from');
|
||||
cm.replaceSelection(newText);
|
||||
cm.setCursor(cursorPos.line, cursorPos.ch + newText.length -1);
|
||||
};
|
||||
// Save draft
|
||||
extraKeys[`${metaKey}-S`] = cm => {window.$events.emit('editor-save-draft')};
|
||||
// Show link selector
|
||||
extraKeys[`Shift-${metaKey}-K`] = cm => {this.actionShowLinkSelector()};
|
||||
// Insert Link
|
||||
extraKeys[`${metaKey}-K`] = cm => {insertLink()};
|
||||
// FormatShortcuts
|
||||
extraKeys[`${metaKey}-1`] = cm => {replaceLineStart('##');};
|
||||
extraKeys[`${metaKey}-2`] = cm => {replaceLineStart('###');};
|
||||
extraKeys[`${metaKey}-3`] = cm => {replaceLineStart('####');};
|
||||
extraKeys[`${metaKey}-4`] = cm => {replaceLineStart('#####');};
|
||||
extraKeys[`${metaKey}-5`] = cm => {replaceLineStart('');};
|
||||
extraKeys[`${metaKey}-d`] = cm => {replaceLineStart('');};
|
||||
extraKeys[`${metaKey}-6`] = cm => {replaceLineStart('>');};
|
||||
extraKeys[`${metaKey}-q`] = cm => {replaceLineStart('>');};
|
||||
extraKeys[`${metaKey}-7`] = cm => {wrapSelection('\n```\n', '\n```');};
|
||||
extraKeys[`${metaKey}-8`] = cm => {wrapSelection('`', '`');};
|
||||
extraKeys[`Shift-${metaKey}-E`] = cm => {wrapSelection('`', '`');};
|
||||
extraKeys[`${metaKey}-9`] = cm => {wrapSelection('<p class="callout info">', '</p>');};
|
||||
cm.setOption('extraKeys', extraKeys);
|
||||
|
||||
// Update data on content change
|
||||
cm.on('change', (instance, changeObj) => {
|
||||
this.updateAndRender();
|
||||
});
|
||||
|
||||
// Handle scroll to sync display view
|
||||
cm.on('scroll', instance => {
|
||||
// Thanks to http://liuhao.im/english/2015/11/10/the-sync-scroll-of-markdown-editor-in-javascript.html
|
||||
let scroll = instance.getScrollInfo();
|
||||
let atEnd = scroll.top + scroll.clientHeight === scroll.height;
|
||||
if (atEnd) {
|
||||
this.onMarkdownScroll(-1);
|
||||
return;
|
||||
}
|
||||
|
||||
let lineNum = instance.lineAtHeight(scroll.top, 'local');
|
||||
let range = instance.getRange({line: 0, ch: null}, {line: lineNum, ch: null});
|
||||
let parser = new DOMParser();
|
||||
let doc = parser.parseFromString(this.markdown.render(range), 'text/html');
|
||||
let totalLines = doc.documentElement.querySelectorAll('body > *');
|
||||
this.onMarkdownScroll(totalLines.length);
|
||||
});
|
||||
|
||||
// Handle image paste
|
||||
cm.on('paste', (cm, event) => {
|
||||
if (!event.clipboardData || !event.clipboardData.items) return;
|
||||
for (let i = 0; i < event.clipboardData.items.length; i++) {
|
||||
uploadImage(event.clipboardData.items[i].getAsFile());
|
||||
}
|
||||
});
|
||||
|
||||
// Handle images on drag-drop
|
||||
cm.on('drop', (cm, event) => {
|
||||
event.stopPropagation();
|
||||
event.preventDefault();
|
||||
let cursorPos = cm.coordsChar({left: event.pageX, top: event.pageY});
|
||||
cm.setCursor(cursorPos);
|
||||
if (!event.dataTransfer || !event.dataTransfer.files) return;
|
||||
for (let i = 0; i < event.dataTransfer.files.length; i++) {
|
||||
uploadImage(event.dataTransfer.files[i]);
|
||||
}
|
||||
});
|
||||
|
||||
// Helper to replace editor content
|
||||
function replaceContent(search, replace) {
|
||||
let text = cm.getValue();
|
||||
let cursor = cm.listSelections();
|
||||
cm.setValue(text.replace(search, replace));
|
||||
cm.setSelections(cursor);
|
||||
}
|
||||
|
||||
// Helper to replace the start of the line
|
||||
function replaceLineStart(newStart) {
|
||||
let cursor = cm.getCursor();
|
||||
let lineContent = cm.getLine(cursor.line);
|
||||
let lineLen = lineContent.length;
|
||||
let lineStart = lineContent.split(' ')[0];
|
||||
|
||||
// Remove symbol if already set
|
||||
if (lineStart === newStart) {
|
||||
lineContent = lineContent.replace(`${newStart} `, '');
|
||||
cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
|
||||
cm.setCursor({line: cursor.line, ch: cursor.ch - (newStart.length + 1)});
|
||||
return;
|
||||
}
|
||||
|
||||
let alreadySymbol = /^[#>`]/.test(lineStart);
|
||||
let posDif = 0;
|
||||
if (alreadySymbol) {
|
||||
posDif = newStart.length - lineStart.length;
|
||||
lineContent = lineContent.replace(lineStart, newStart).trim();
|
||||
} else if (newStart !== '') {
|
||||
posDif = newStart.length + 1;
|
||||
lineContent = newStart + ' ' + lineContent;
|
||||
}
|
||||
cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
|
||||
cm.setCursor({line: cursor.line, ch: cursor.ch + posDif});
|
||||
}
|
||||
|
||||
function wrapLine(start, end) {
|
||||
let cursor = cm.getCursor();
|
||||
let lineContent = cm.getLine(cursor.line);
|
||||
let lineLen = lineContent.length;
|
||||
let newLineContent = lineContent;
|
||||
|
||||
if (lineContent.indexOf(start) === 0 && lineContent.slice(-end.length) === end) {
|
||||
newLineContent = lineContent.slice(start.length, lineContent.length - end.length);
|
||||
} else {
|
||||
newLineContent = `${start}${lineContent}${end}`;
|
||||
}
|
||||
|
||||
cm.replaceRange(newLineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
|
||||
cm.setCursor({line: cursor.line, ch: cursor.ch + start.length});
|
||||
}
|
||||
|
||||
function wrapSelection(start, end) {
|
||||
let selection = cm.getSelection();
|
||||
if (selection === '') return wrapLine(start, end);
|
||||
|
||||
let newSelection = selection;
|
||||
let frontDiff = 0;
|
||||
let endDiff = 0;
|
||||
|
||||
if (selection.indexOf(start) === 0 && selection.slice(-end.length) === end) {
|
||||
newSelection = selection.slice(start.length, selection.length - end.length);
|
||||
endDiff = -(end.length + start.length);
|
||||
} else {
|
||||
newSelection = `${start}${selection}${end}`;
|
||||
endDiff = start.length + end.length;
|
||||
}
|
||||
|
||||
let selections = cm.listSelections()[0];
|
||||
cm.replaceSelection(newSelection);
|
||||
let headFirst = selections.head.ch <= selections.anchor.ch;
|
||||
selections.head.ch += headFirst ? frontDiff : endDiff;
|
||||
selections.anchor.ch += headFirst ? endDiff : frontDiff;
|
||||
cm.setSelections([selections]);
|
||||
}
|
||||
|
||||
// Handle image upload and add image into markdown content
|
||||
function uploadImage(file) {
|
||||
if (file === null || file.type.indexOf('image') !== 0) return;
|
||||
let ext = 'png';
|
||||
|
||||
if (file.name) {
|
||||
let fileNameMatches = file.name.match(/\.(.+)$/);
|
||||
if (fileNameMatches.length > 1) ext = fileNameMatches[1];
|
||||
}
|
||||
|
||||
// Insert image into markdown
|
||||
let id = "image-" + Math.random().toString(16).slice(2);
|
||||
let placeholderImage = window.baseUrl(`/loading.gif#upload${id}`);
|
||||
let selectedText = cm.getSelection();
|
||||
let placeHolderText = `![${selectedText}](${placeholderImage})`;
|
||||
cm.replaceSelection(placeHolderText);
|
||||
|
||||
let remoteFilename = "image-" + Date.now() + "." + ext;
|
||||
let formData = new FormData();
|
||||
formData.append('file', file, remoteFilename);
|
||||
|
||||
window.$http.post('/images/gallery/upload', formData).then(resp => {
|
||||
replaceContent(placeholderImage, resp.data.thumbs.display);
|
||||
}).catch(err => {
|
||||
events.emit('error', trans('errors.image_upload_error'));
|
||||
replaceContent(placeHolderText, selectedText);
|
||||
console.log(err);
|
||||
});
|
||||
}
|
||||
|
||||
function insertLink() {
|
||||
let cursorPos = cm.getCursor('from');
|
||||
let selectedText = cm.getSelection() || '';
|
||||
let newText = `[${selectedText}]()`;
|
||||
cm.focus();
|
||||
cm.replaceSelection(newText);
|
||||
let cursorPosDiff = (selectedText === '') ? -3 : -1;
|
||||
cm.setCursor(cursorPos.line, cursorPos.ch + newText.length+cursorPosDiff);
|
||||
}
|
||||
|
||||
this.updateAndRender();
|
||||
}
|
||||
|
||||
actionInsertImage() {
|
||||
let cursorPos = this.cm.getCursor('from');
|
||||
window.ImageManager.show(image => {
|
||||
let selectedText = this.cm.getSelection();
|
||||
let newText = "![" + (selectedText || image.name) + "](" + image.thumbs.display + ")";
|
||||
this.cm.focus();
|
||||
this.cm.replaceSelection(newText);
|
||||
this.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
|
||||
});
|
||||
}
|
||||
|
||||
// Show the popup link selector and insert a link when finished
|
||||
actionShowLinkSelector() {
|
||||
let cursorPos = this.cm.getCursor('from');
|
||||
window.EntitySelectorPopup.show(entity => {
|
||||
let selectedText = this.cm.getSelection() || entity.name;
|
||||
let newText = `[${selectedText}](${entity.link})`;
|
||||
this.cm.focus();
|
||||
this.cm.replaceSelection(newText);
|
||||
this.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
module.exports = MarkdownEditor ;
|
11
resources/assets/js/components/wysiwyg-editor.js
Normal file
11
resources/assets/js/components/wysiwyg-editor.js
Normal file
@ -0,0 +1,11 @@
|
||||
class WysiwygEditor {
|
||||
|
||||
constructor(elem) {
|
||||
this.elem = elem;
|
||||
this.options = require("../pages/page-form");
|
||||
tinymce.init(this.options);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
module.exports = WysiwygEditor;
|
@ -2,7 +2,6 @@
|
||||
|
||||
const moment = require('moment');
|
||||
require('moment/locale/en-gb');
|
||||
const editorOptions = require("./pages/page-form");
|
||||
|
||||
moment.locale('en-gb');
|
||||
|
||||
@ -12,8 +11,9 @@ module.exports = function (ngApp, events) {
|
||||
ngApp.controller('PageEditController', ['$scope', '$http', '$attrs', '$interval', '$timeout', '$sce',
|
||||
function ($scope, $http, $attrs, $interval, $timeout, $sce) {
|
||||
|
||||
$scope.editorOptions = editorOptions();
|
||||
$scope.editContent = '';
|
||||
$scope.editorHTML = '';
|
||||
$scope.editorMarkdown = '';
|
||||
|
||||
$scope.draftText = '';
|
||||
let pageId = Number($attrs.pageId);
|
||||
let isEdit = pageId !== 0;
|
||||
@ -43,19 +43,6 @@ module.exports = function (ngApp, events) {
|
||||
}, 1000);
|
||||
}
|
||||
|
||||
// Actions specifically for the markdown editor
|
||||
if (isMarkdown) {
|
||||
$scope.displayContent = '';
|
||||
// Editor change event
|
||||
$scope.editorChange = function (content) {
|
||||
$scope.displayContent = $sce.trustAsHtml(content);
|
||||
}
|
||||
}
|
||||
|
||||
if (!isMarkdown) {
|
||||
$scope.editorChange = function() {};
|
||||
}
|
||||
|
||||
let lastSave = 0;
|
||||
|
||||
/**
|
||||
@ -64,13 +51,13 @@ module.exports = function (ngApp, events) {
|
||||
*/
|
||||
function startAutoSave() {
|
||||
currentContent.title = $('#name').val();
|
||||
currentContent.html = $scope.editContent;
|
||||
currentContent.html = $scope.editorHTML;
|
||||
|
||||
autoSave = $interval(() => {
|
||||
// Return if manually saved recently to prevent bombarding the server
|
||||
if (Date.now() - lastSave < (1000*autosaveFrequency)/2) return;
|
||||
let newTitle = $('#name').val();
|
||||
let newHtml = $scope.editContent;
|
||||
let newHtml = $scope.editorHTML;
|
||||
|
||||
if (newTitle !== currentContent.title || newHtml !== currentContent.html) {
|
||||
currentContent.html = newHtml;
|
||||
@ -87,12 +74,12 @@ module.exports = function (ngApp, events) {
|
||||
*/
|
||||
function saveDraft() {
|
||||
if (!$scope.draftsEnabled) return;
|
||||
|
||||
let data = {
|
||||
name: $('#name').val(),
|
||||
html: isMarkdown ? $sce.getTrustedHtml($scope.displayContent) : $scope.editContent
|
||||
html: $scope.editorHTML
|
||||
};
|
||||
|
||||
if (isMarkdown) data.markdown = $scope.editContent;
|
||||
if (isMarkdown) data.markdown = $scope.editorMarkdown;
|
||||
|
||||
let url = window.baseUrl('/ajax/page/' + pageId + '/save-draft');
|
||||
$http.put(url, data).then(responseData => {
|
||||
@ -121,7 +108,15 @@ module.exports = function (ngApp, events) {
|
||||
};
|
||||
|
||||
// Listen to save draft events from editor
|
||||
$scope.$on('save-draft', saveDraft);
|
||||
window.$events.listen('editor-save-draft', saveDraft);
|
||||
|
||||
// Listen to content changes from the editor
|
||||
window.$events.listen('editor-html-change', html => {
|
||||
$scope.editorHTML = html;
|
||||
});
|
||||
window.$events.listen('editor-markdown-change', markdown => {
|
||||
$scope.editorMarkdown = markdown;
|
||||
});
|
||||
|
||||
/**
|
||||
* Discard the current draft and grab the current page
|
||||
@ -131,10 +126,12 @@ module.exports = function (ngApp, events) {
|
||||
let url = window.baseUrl('/ajax/page/' + pageId);
|
||||
$http.get(url).then(responseData => {
|
||||
if (autoSave) $interval.cancel(autoSave);
|
||||
|
||||
$scope.draftText = trans('entities.pages_editing_page');
|
||||
$scope.isUpdateDraft = false;
|
||||
$scope.$broadcast('html-update', responseData.data.html);
|
||||
$scope.$broadcast('markdown-update', responseData.data.markdown || responseData.data.html);
|
||||
window.$events.emit('editor-html-update', responseData.data.html);
|
||||
window.$events.emit('editor-markdown-update', responseData.data.markdown || responseData.data.html);
|
||||
|
||||
$('#name').val(responseData.data.name);
|
||||
$timeout(() => {
|
||||
startAutoSave();
|
||||
|
@ -1,354 +1,7 @@
|
||||
"use strict";
|
||||
const MarkdownIt = require("markdown-it");
|
||||
const mdTasksLists = require('markdown-it-task-lists');
|
||||
const code = require('./code');
|
||||
|
||||
|
||||
module.exports = function (ngApp, events) {
|
||||
|
||||
/**
|
||||
* TinyMCE
|
||||
* An angular wrapper around the tinyMCE editor.
|
||||
*/
|
||||
ngApp.directive('tinymce', ['$timeout', function ($timeout) {
|
||||
return {
|
||||
restrict: 'A',
|
||||
scope: {
|
||||
tinymce: '=',
|
||||
mceModel: '=',
|
||||
mceChange: '='
|
||||
},
|
||||
link: function (scope, element, attrs) {
|
||||
|
||||
function tinyMceSetup(editor) {
|
||||
editor.on('ExecCommand change input NodeChange ObjectResized', (e) => {
|
||||
let content = editor.getContent();
|
||||
$timeout(() => {
|
||||
scope.mceModel = content;
|
||||
});
|
||||
scope.mceChange(content);
|
||||
});
|
||||
|
||||
editor.on('keydown', (event) => {
|
||||
if (event.keyCode === 83 && (navigator.platform.match("Mac") ? event.metaKey : event.ctrlKey)) {
|
||||
event.preventDefault();
|
||||
scope.$emit('save-draft', event);
|
||||
}
|
||||
});
|
||||
|
||||
editor.on('init', (e) => {
|
||||
scope.mceModel = editor.getContent();
|
||||
});
|
||||
|
||||
scope.$on('html-update', (event, value) => {
|
||||
editor.setContent(value);
|
||||
editor.selection.select(editor.getBody(), true);
|
||||
editor.selection.collapse(false);
|
||||
scope.mceModel = editor.getContent();
|
||||
});
|
||||
}
|
||||
|
||||
scope.tinymce.extraSetups.push(tinyMceSetup);
|
||||
tinymce.init(scope.tinymce);
|
||||
}
|
||||
}
|
||||
}]);
|
||||
|
||||
const md = new MarkdownIt({html: true});
|
||||
md.use(mdTasksLists, {label: true});
|
||||
|
||||
/**
|
||||
* Markdown input
|
||||
* Handles the logic for just the editor input field.
|
||||
*/
|
||||
ngApp.directive('markdownInput', ['$timeout', function ($timeout) {
|
||||
return {
|
||||
restrict: 'A',
|
||||
scope: {
|
||||
mdModel: '=',
|
||||
mdChange: '='
|
||||
},
|
||||
link: function (scope, element, attrs) {
|
||||
|
||||
// Codemirror Setup
|
||||
element = element.find('textarea').first();
|
||||
let cm = code.markdownEditor(element[0]);
|
||||
|
||||
// Custom key commands
|
||||
let metaKey = code.getMetaKey();
|
||||
const extraKeys = {};
|
||||
// Insert Image shortcut
|
||||
extraKeys[`${metaKey}-Alt-I`] = function(cm) {
|
||||
let selectedText = cm.getSelection();
|
||||
let newText = `![${selectedText}](http://)`;
|
||||
let cursorPos = cm.getCursor('from');
|
||||
cm.replaceSelection(newText);
|
||||
cm.setCursor(cursorPos.line, cursorPos.ch + newText.length -1);
|
||||
};
|
||||
// Save draft
|
||||
extraKeys[`${metaKey}-S`] = function(cm) {scope.$emit('save-draft');};
|
||||
// Show link selector
|
||||
extraKeys[`Shift-${metaKey}-K`] = function(cm) {showLinkSelector()};
|
||||
// Insert Link
|
||||
extraKeys[`${metaKey}-K`] = function(cm) {insertLink()};
|
||||
// FormatShortcuts
|
||||
extraKeys[`${metaKey}-1`] = function(cm) {replaceLineStart('##');};
|
||||
extraKeys[`${metaKey}-2`] = function(cm) {replaceLineStart('###');};
|
||||
extraKeys[`${metaKey}-3`] = function(cm) {replaceLineStart('####');};
|
||||
extraKeys[`${metaKey}-4`] = function(cm) {replaceLineStart('#####');};
|
||||
extraKeys[`${metaKey}-5`] = function(cm) {replaceLineStart('');};
|
||||
extraKeys[`${metaKey}-d`] = function(cm) {replaceLineStart('');};
|
||||
extraKeys[`${metaKey}-6`] = function(cm) {replaceLineStart('>');};
|
||||
extraKeys[`${metaKey}-q`] = function(cm) {replaceLineStart('>');};
|
||||
extraKeys[`${metaKey}-7`] = function(cm) {wrapSelection('\n```\n', '\n```');};
|
||||
extraKeys[`${metaKey}-8`] = function(cm) {wrapSelection('`', '`');};
|
||||
extraKeys[`Shift-${metaKey}-E`] = function(cm) {wrapSelection('`', '`');};
|
||||
extraKeys[`${metaKey}-9`] = function(cm) {wrapSelection('<p class="callout info">', '</p>');};
|
||||
cm.setOption('extraKeys', extraKeys);
|
||||
|
||||
// Update data on content change
|
||||
cm.on('change', (instance, changeObj) => {
|
||||
update(instance);
|
||||
});
|
||||
|
||||
// Handle scroll to sync display view
|
||||
cm.on('scroll', instance => {
|
||||
// Thanks to http://liuhao.im/english/2015/11/10/the-sync-scroll-of-markdown-editor-in-javascript.html
|
||||
let scroll = instance.getScrollInfo();
|
||||
let atEnd = scroll.top + scroll.clientHeight === scroll.height;
|
||||
if (atEnd) {
|
||||
scope.$emit('markdown-scroll', -1);
|
||||
return;
|
||||
}
|
||||
let lineNum = instance.lineAtHeight(scroll.top, 'local');
|
||||
let range = instance.getRange({line: 0, ch: null}, {line: lineNum, ch: null});
|
||||
let parser = new DOMParser();
|
||||
let doc = parser.parseFromString(md.render(range), 'text/html');
|
||||
let totalLines = doc.documentElement.querySelectorAll('body > *');
|
||||
scope.$emit('markdown-scroll', totalLines.length);
|
||||
});
|
||||
|
||||
// Handle image paste
|
||||
cm.on('paste', (cm, event) => {
|
||||
if (!event.clipboardData || !event.clipboardData.items) return;
|
||||
for (let i = 0; i < event.clipboardData.items.length; i++) {
|
||||
uploadImage(event.clipboardData.items[i].getAsFile());
|
||||
}
|
||||
});
|
||||
|
||||
// Handle images on drag-drop
|
||||
cm.on('drop', (cm, event) => {
|
||||
event.stopPropagation();
|
||||
event.preventDefault();
|
||||
let cursorPos = cm.coordsChar({left: event.pageX, top: event.pageY});
|
||||
cm.setCursor(cursorPos);
|
||||
if (!event.dataTransfer || !event.dataTransfer.files) return;
|
||||
for (let i = 0; i < event.dataTransfer.files.length; i++) {
|
||||
uploadImage(event.dataTransfer.files[i]);
|
||||
}
|
||||
});
|
||||
|
||||
// Helper to replace editor content
|
||||
function replaceContent(search, replace) {
|
||||
let text = cm.getValue();
|
||||
let cursor = cm.listSelections();
|
||||
cm.setValue(text.replace(search, replace));
|
||||
cm.setSelections(cursor);
|
||||
}
|
||||
|
||||
// Helper to replace the start of the line
|
||||
function replaceLineStart(newStart) {
|
||||
let cursor = cm.getCursor();
|
||||
let lineContent = cm.getLine(cursor.line);
|
||||
let lineLen = lineContent.length;
|
||||
let lineStart = lineContent.split(' ')[0];
|
||||
|
||||
// Remove symbol if already set
|
||||
if (lineStart === newStart) {
|
||||
lineContent = lineContent.replace(`${newStart} `, '');
|
||||
cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
|
||||
cm.setCursor({line: cursor.line, ch: cursor.ch - (newStart.length + 1)});
|
||||
return;
|
||||
}
|
||||
|
||||
let alreadySymbol = /^[#>`]/.test(lineStart);
|
||||
let posDif = 0;
|
||||
if (alreadySymbol) {
|
||||
posDif = newStart.length - lineStart.length;
|
||||
lineContent = lineContent.replace(lineStart, newStart).trim();
|
||||
} else if (newStart !== '') {
|
||||
posDif = newStart.length + 1;
|
||||
lineContent = newStart + ' ' + lineContent;
|
||||
}
|
||||
cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
|
||||
cm.setCursor({line: cursor.line, ch: cursor.ch + posDif});
|
||||
}
|
||||
|
||||
function wrapLine(start, end) {
|
||||
let cursor = cm.getCursor();
|
||||
let lineContent = cm.getLine(cursor.line);
|
||||
let lineLen = lineContent.length;
|
||||
let newLineContent = lineContent;
|
||||
|
||||
if (lineContent.indexOf(start) === 0 && lineContent.slice(-end.length) === end) {
|
||||
newLineContent = lineContent.slice(start.length, lineContent.length - end.length);
|
||||
} else {
|
||||
newLineContent = `${start}${lineContent}${end}`;
|
||||
}
|
||||
|
||||
cm.replaceRange(newLineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
|
||||
cm.setCursor({line: cursor.line, ch: cursor.ch + start.length});
|
||||
}
|
||||
|
||||
function wrapSelection(start, end) {
|
||||
let selection = cm.getSelection();
|
||||
if (selection === '') return wrapLine(start, end);
|
||||
|
||||
let newSelection = selection;
|
||||
let frontDiff = 0;
|
||||
let endDiff = 0;
|
||||
|
||||
if (selection.indexOf(start) === 0 && selection.slice(-end.length) === end) {
|
||||
newSelection = selection.slice(start.length, selection.length - end.length);
|
||||
endDiff = -(end.length + start.length);
|
||||
} else {
|
||||
newSelection = `${start}${selection}${end}`;
|
||||
endDiff = start.length + end.length;
|
||||
}
|
||||
|
||||
let selections = cm.listSelections()[0];
|
||||
cm.replaceSelection(newSelection);
|
||||
let headFirst = selections.head.ch <= selections.anchor.ch;
|
||||
selections.head.ch += headFirst ? frontDiff : endDiff;
|
||||
selections.anchor.ch += headFirst ? endDiff : frontDiff;
|
||||
cm.setSelections([selections]);
|
||||
}
|
||||
|
||||
// Handle image upload and add image into markdown content
|
||||
function uploadImage(file) {
|
||||
if (file === null || file.type.indexOf('image') !== 0) return;
|
||||
let ext = 'png';
|
||||
|
||||
if (file.name) {
|
||||
let fileNameMatches = file.name.match(/\.(.+)$/);
|
||||
if (fileNameMatches.length > 1) ext = fileNameMatches[1];
|
||||
}
|
||||
|
||||
// Insert image into markdown
|
||||
let id = "image-" + Math.random().toString(16).slice(2);
|
||||
let placeholderImage = window.baseUrl(`/loading.gif#upload${id}`);
|
||||
let selectedText = cm.getSelection();
|
||||
let placeHolderText = `![${selectedText}](${placeholderImage})`;
|
||||
cm.replaceSelection(placeHolderText);
|
||||
|
||||
let remoteFilename = "image-" + Date.now() + "." + ext;
|
||||
let formData = new FormData();
|
||||
formData.append('file', file, remoteFilename);
|
||||
|
||||
window.$http.post('/images/gallery/upload', formData).then(resp => {
|
||||
replaceContent(placeholderImage, resp.data.thumbs.display);
|
||||
}).catch(err => {
|
||||
events.emit('error', trans('errors.image_upload_error'));
|
||||
replaceContent(placeHolderText, selectedText);
|
||||
console.log(err);
|
||||
});
|
||||
}
|
||||
|
||||
// Show the popup link selector and insert a link when finished
|
||||
function showLinkSelector() {
|
||||
let cursorPos = cm.getCursor('from');
|
||||
window.EntitySelectorPopup.show(entity => {
|
||||
let selectedText = cm.getSelection() || entity.name;
|
||||
let newText = `[${selectedText}](${entity.link})`;
|
||||
cm.focus();
|
||||
cm.replaceSelection(newText);
|
||||
cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
|
||||
});
|
||||
}
|
||||
|
||||
function insertLink() {
|
||||
let cursorPos = cm.getCursor('from');
|
||||
let selectedText = cm.getSelection() || '';
|
||||
let newText = `[${selectedText}]()`;
|
||||
cm.focus();
|
||||
cm.replaceSelection(newText);
|
||||
let cursorPosDiff = (selectedText === '') ? -3 : -1;
|
||||
cm.setCursor(cursorPos.line, cursorPos.ch + newText.length+cursorPosDiff);
|
||||
}
|
||||
|
||||
// Show the image manager and handle image insertion
|
||||
function showImageManager() {
|
||||
let cursorPos = cm.getCursor('from');
|
||||
window.ImageManager.show(image => {
|
||||
let selectedText = cm.getSelection();
|
||||
let newText = "![" + (selectedText || image.name) + "](" + image.thumbs.display + ")";
|
||||
cm.focus();
|
||||
cm.replaceSelection(newText);
|
||||
cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
|
||||
});
|
||||
}
|
||||
|
||||
// Update the data models and rendered output
|
||||
function update(instance) {
|
||||
let content = instance.getValue();
|
||||
element.val(content);
|
||||
$timeout(() => {
|
||||
scope.mdModel = content;
|
||||
scope.mdChange(md.render(content));
|
||||
});
|
||||
}
|
||||
update(cm);
|
||||
|
||||
// Listen to commands from parent scope
|
||||
scope.$on('md-insert-link', showLinkSelector);
|
||||
scope.$on('md-insert-image', showImageManager);
|
||||
scope.$on('markdown-update', (event, value) => {
|
||||
cm.setValue(value);
|
||||
element.val(value);
|
||||
scope.mdModel = value;
|
||||
scope.mdChange(md.render(value));
|
||||
});
|
||||
|
||||
}
|
||||
}
|
||||
}]);
|
||||
|
||||
/**
|
||||
* Markdown Editor
|
||||
* Handles all functionality of the markdown editor.
|
||||
*/
|
||||
ngApp.directive('markdownEditor', ['$timeout', '$rootScope', function ($timeout, $rootScope) {
|
||||
return {
|
||||
restrict: 'A',
|
||||
link: function (scope, element, attrs) {
|
||||
|
||||
// Editor Elements
|
||||
const $display = element.find('.markdown-display').first();
|
||||
const $insertImage = element.find('button[data-action="insertImage"]');
|
||||
const $insertEntityLink = element.find('button[data-action="insertEntityLink"]');
|
||||
|
||||
// Prevent markdown display link click redirect
|
||||
$display.on('click', 'a', function(event) {
|
||||
event.preventDefault();
|
||||
window.open(this.getAttribute('href'));
|
||||
});
|
||||
|
||||
// Editor UI Actions
|
||||
$insertEntityLink.click(e => {scope.$broadcast('md-insert-link');});
|
||||
$insertImage.click(e => {scope.$broadcast('md-insert-image');});
|
||||
|
||||
// Handle scroll sync event from editor scroll
|
||||
$rootScope.$on('markdown-scroll', (event, lineCount) => {
|
||||
let elems = $display[0].children[0].children;
|
||||
if (elems.length > lineCount) {
|
||||
let topElem = (lineCount === -1) ? elems[elems.length-1] : elems[lineCount];
|
||||
$display.animate({
|
||||
scrollTop: topElem.offsetTop
|
||||
}, {queue: false, duration: 200, easing: 'linear'});
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}]);
|
||||
|
||||
/**
|
||||
* Page Editor Toolbox
|
||||
|
@ -1,5 +1,4 @@
|
||||
"use strict";
|
||||
|
||||
const Code = require('../code');
|
||||
|
||||
/**
|
||||
@ -66,6 +65,12 @@ function registerEditorShortcuts(editor) {
|
||||
editor.shortcuts.add('meta+e', '', ['codeeditor', false, 'pre']);
|
||||
editor.shortcuts.add('meta+8', '', ['FormatBlock', false, 'code']);
|
||||
editor.shortcuts.add('meta+shift+E', '', ['FormatBlock', false, 'code']);
|
||||
|
||||
// Save draft shortcut
|
||||
editor.shortcuts.add('meta+S', '', () => {
|
||||
window.$events.emit('editor-save-draft');
|
||||
});
|
||||
|
||||
// Loop through callout styles
|
||||
editor.shortcuts.add('meta+9', '', function() {
|
||||
let selectedNode = editor.selection.getNode();
|
||||
@ -84,6 +89,7 @@ function registerEditorShortcuts(editor) {
|
||||
}
|
||||
editor.formatter.apply('p');
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
|
||||
@ -196,9 +202,9 @@ function codePlugin() {
|
||||
|
||||
});
|
||||
}
|
||||
codePlugin();
|
||||
|
||||
function hrPlugin() {
|
||||
window.tinymce.PluginManager.add('customhr', function (editor) {
|
||||
window.tinymce.PluginManager.add('customhr', function (editor) {
|
||||
editor.addCommand('InsertHorizontalRule', function () {
|
||||
let hrElem = document.createElement('hr');
|
||||
let cNode = editor.selection.getNode();
|
||||
@ -218,13 +224,11 @@ function hrPlugin() {
|
||||
cmd: 'InsertHorizontalRule',
|
||||
context: 'insert'
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = function() {
|
||||
hrPlugin();
|
||||
codePlugin();
|
||||
let settings = {
|
||||
|
||||
|
||||
module.exports = {
|
||||
selector: '#html-editor',
|
||||
content_css: [
|
||||
window.baseUrl('/css/styles.css'),
|
||||
@ -313,15 +317,22 @@ module.exports = function() {
|
||||
args.content = '';
|
||||
}
|
||||
},
|
||||
extraSetups: [],
|
||||
setup: function (editor) {
|
||||
|
||||
// Run additional setup actions
|
||||
// Used by the angular side of things
|
||||
for (let i = 0; i < settings.extraSetups.length; i++) {
|
||||
settings.extraSetups[i](editor);
|
||||
editor.on('init ExecCommand change input NodeChange ObjectResized', editorChange);
|
||||
|
||||
function editorChange() {
|
||||
let content = editor.getContent();
|
||||
window.$events.emit('editor-html-change', content);
|
||||
}
|
||||
|
||||
window.$events.listen('editor-html-update', html => {
|
||||
editor.setContent(html);
|
||||
editor.selection.select(editor.getBody(), true);
|
||||
editor.selection.collapse(false);
|
||||
editorChange(html);
|
||||
});
|
||||
|
||||
registerEditorShortcuts(editor);
|
||||
|
||||
let wrap;
|
||||
@ -379,6 +390,4 @@ module.exports = function() {
|
||||
// Paste image-uploads
|
||||
editor.on('paste', event => { editorPaste(event, editor) });
|
||||
}
|
||||
};
|
||||
return settings;
|
||||
};
|
@ -62,7 +62,7 @@
|
||||
|
||||
{{--WYSIWYG Editor--}}
|
||||
@if(setting('app-editor') === 'wysiwyg')
|
||||
<div tinymce="editorOptions" mce-change="editorChange" mce-model="editContent" class="flex-fill flex">
|
||||
<div wysiwyg-editor class="flex-fill flex">
|
||||
<textarea id="html-editor" name="html" rows="5" ng-non-bindable
|
||||
@if($errors->has('html')) class="neg" @endif>@if(isset($model) || old('html')){{htmlspecialchars( old('html') ? old('html') : $model->html)}}@endif</textarea>
|
||||
</div>
|
||||
@ -74,7 +74,7 @@
|
||||
|
||||
{{--Markdown Editor--}}
|
||||
@if(setting('app-editor') === 'markdown')
|
||||
<div id="markdown-editor" markdown-editor class="flex-fill flex code-fill">
|
||||
<div ng-non-bindable id="markdown-editor" markdown-editor class="flex-fill flex code-fill">
|
||||
|
||||
<div class="markdown-editor-wrap">
|
||||
<div class="editor-toolbar">
|
||||
@ -82,12 +82,12 @@
|
||||
<div class="float right buttons">
|
||||
<button class="text-button" type="button" data-action="insertImage"><i class="zmdi zmdi-image"></i>{{ trans('entities.pages_md_insert_image') }}</button>
|
||||
|
|
||||
<button class="text-button" type="button" data-action="insertEntityLink"><i class="zmdi zmdi-link"></i>{{ trans('entities.pages_md_insert_link') }}</button>
|
||||
<button class="text-button" type="button" data-action="insertLink"><i class="zmdi zmdi-link"></i>{{ trans('entities.pages_md_insert_link') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div markdown-input md-change="editorChange" md-model="editContent" class="flex flex-fill">
|
||||
<textarea ng-non-bindable id="markdown-editor-input" name="markdown" rows="5"
|
||||
<textarea id="markdown-editor-input" name="markdown" rows="5"
|
||||
@if($errors->has('markdown')) class="neg" @endif>@if(isset($model) || old('markdown')){{htmlspecialchars( old('markdown') ? old('markdown') : ($model->markdown === '' ? $model->html : $model->markdown))}}@endif</textarea>
|
||||
</div>
|
||||
|
||||
@ -101,10 +101,11 @@
|
||||
<div class="page-content" ng-bind-html="displayContent"></div>
|
||||
</div>
|
||||
</div>
|
||||
<input type="hidden" name="html"/>
|
||||
|
||||
</div>
|
||||
|
||||
<input type="hidden" name="html" ng-value="displayContent">
|
||||
|
||||
|
||||
@if($errors->has('markdown'))
|
||||
<div class="text-neg text-small">{{ $errors->first('markdown') }}</div>
|
||||
|
Loading…
Reference in New Issue
Block a user