X-Git-Url: http://source.bookstackapp.com/bookstack/blobdiff_plain/242dc218764ff502913a99ca1fda0777b0b9ac0f..refs/pull/422/head:/resources/assets/js/directives.js diff --git a/resources/assets/js/directives.js b/resources/assets/js/directives.js index 0ff7c0fcc..9a38add9a 100644 --- a/resources/assets/js/directives.js +++ b/resources/assets/js/directives.js @@ -1,8 +1,10 @@ "use strict"; -import DropZone from "dropzone"; -import markdown from "marked"; +const DropZone = require("dropzone"); +const MarkdownIt = require("markdown-it"); +const mdTasksLists = require('markdown-it-task-lists'); +const code = require('./code'); -export default function (ngApp, events) { +module.exports = function (ngApp, events) { /** * Common tab controls using simple jQuery functions. @@ -35,7 +37,7 @@ export default function (ngApp, events) { }); /** - * Sub form component to allow inner-form sections to act like thier own forms. + * Sub form component to allow inner-form sections to act like their own forms. */ ngApp.directive('subForm', function() { return { @@ -50,96 +52,13 @@ export default function (ngApp, events) { element.find('button[type="submit"]').click(submitEvent); function submitEvent(e) { - e.preventDefault() + e.preventDefault(); if (attrs.subForm) scope.$eval(attrs.subForm); } } }; }); - - /** - * Image Picker - * Is a simple front-end interface that connects to an ImageManager if present. - */ - ngApp.directive('imagePicker', ['$http', 'imageManagerService', function ($http, imageManagerService) { - return { - restrict: 'E', - template: ` -
-
- Image Preview - Image Preview -
- -
- - - | - - - -
- `, - scope: { - name: '@', - resizeHeight: '@', - resizeWidth: '@', - resizeCrop: '@', - showRemove: '=', - currentImage: '@', - currentId: '@', - defaultImage: '@', - imageClass: '@' - }, - link: function (scope, element, attrs) { - let usingIds = typeof scope.currentId !== 'undefined' || scope.currentId === 'false'; - scope.image = scope.currentImage; - scope.value = scope.currentImage || ''; - if (usingIds) scope.value = scope.currentId; - - function setImage(imageModel, imageUrl) { - scope.image = imageUrl; - scope.value = usingIds ? imageModel.id : imageUrl; - } - - scope.reset = function () { - setImage({id: 0}, scope.defaultImage); - }; - - scope.remove = function () { - scope.image = 'none'; - scope.value = 'none'; - }; - - scope.showImageManager = function () { - imageManagerService.show((image) => { - scope.updateImageFromModel(image); - }); - }; - - scope.updateImageFromModel = function (model) { - let isResized = scope.resizeWidth && scope.resizeHeight; - - if (!isResized) { - scope.$apply(() => { - setImage(model, model.url); - }); - return; - } - - let cropped = scope.resizeCrop ? 'true' : 'false'; - let requestString = '/images/thumb/' + model.id + '/' + scope.resizeWidth + '/' + scope.resizeHeight + '/' + cropped; - requestString = window.baseUrl(requestString); - $http.get(requestString).then((response) => { - setImage(model, response.data.url); - }); - }; - - } - }; - }]); - /** * DropZone * Used for uploading images @@ -149,16 +68,17 @@ export default function (ngApp, events) { restrict: 'E', template: `
-
Drop files or click here to upload
+
{{message}}
`, scope: { uploadUrl: '@', eventSuccess: '=', eventError: '=', - uploadedTo: '@' + uploadedTo: '@', }, link: function (scope, element, attrs) { + scope.message = attrs.message; if (attrs.placeholder) element[0].querySelector('.dz-message').textContent = attrs.placeholder; let dropZone = new DropZone(element[0].querySelector('.dropzone-container'), { url: scope.uploadUrl, @@ -184,7 +104,7 @@ export default function (ngApp, events) { $(file.previewElement).find('[data-dz-errormessage]').text(message); } - if (xhr.status === 413) setMessage('The server does not allow uploads of this size. Please try a smaller file.'); + if (xhr.status === 413) setMessage(trans('errors.server_upload_limit')); if (errorMessage.file) setMessage(errorMessage.file[0]); }); @@ -296,6 +216,9 @@ export default function (ngApp, events) { } }]); + const md = new MarkdownIt({html: true}); + md.use(mdTasksLists, {label: true}); + /** * Markdown input * Handles the logic for just the editor input field. @@ -311,22 +234,44 @@ export default function (ngApp, events) { // Set initial model content element = element.find('textarea').first(); - let content = element.val(); - scope.mdModel = content; - scope.mdChange(markdown(content)); - element.on('change input', (event) => { - content = element.val(); + // Codemirror Setup + let cm = code.markdownEditor(element[0]); + cm.on('change', (instance, changeObj) => { + update(instance); + }); + + 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); + }); + + function update(instance) { + let content = instance.getValue(); + element.val(content); $timeout(() => { scope.mdModel = content; - scope.mdChange(markdown(content)); + scope.mdChange(md.render(content)); }); - }); + } + update(cm); scope.$on('markdown-update', (event, value) => { + cm.setValue(value); element.val(value); scope.mdModel = value; - scope.mdChange(markdown(value)); + scope.mdChange(md.render(value)); }); } @@ -337,65 +282,52 @@ export default function (ngApp, events) { * Markdown Editor * Handles all functionality of the markdown editor. */ - ngApp.directive('markdownEditor', ['$timeout', function ($timeout) { + ngApp.directive('markdownEditor', ['$timeout', '$rootScope', function ($timeout, $rootScope) { return { restrict: 'A', link: function (scope, element, attrs) { // Elements - const input = element.find('[markdown-input] textarea').first(); - const display = element.find('.markdown-display').first(); - const insertImage = element.find('button[data-action="insertImage"]'); - const insertEntityLink = element.find('button[data-action="insertEntityLink"]') + const $input = element.find('[markdown-input] textarea').first(); + 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')); + }); let currentCaretPos = 0; - input.blur(event => { - currentCaretPos = input[0].selectionStart; + $input.blur(event => { + currentCaretPos = $input[0].selectionStart; }); - // Scroll sync - let inputScrollHeight, - inputHeight, - displayScrollHeight, - displayHeight; - - function setScrollHeights() { - inputScrollHeight = input[0].scrollHeight; - inputHeight = input.height(); - displayScrollHeight = display[0].scrollHeight; - displayHeight = display.height(); - } - - setTimeout(() => { - setScrollHeights(); - }, 200); - window.addEventListener('resize', setScrollHeights); - let scrollDebounceTime = 800; - let lastScroll = 0; - input.on('scroll', event => { - let now = Date.now(); - if (now - lastScroll > scrollDebounceTime) { - setScrollHeights() + // 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'}); } - let scrollPercent = (input.scrollTop() / (inputScrollHeight - inputHeight)); - let displayScrollY = (displayScrollHeight - displayHeight) * scrollPercent; - display.scrollTop(displayScrollY); - lastScroll = now; }); // Editor key-presses - input.keydown(event => { + $input.keydown(event => { // Insert image shortcut if (event.which === 73 && event.ctrlKey && event.shiftKey) { event.preventDefault(); - let caretPos = input[0].selectionStart; - let currentContent = input.val(); + let caretPos = $input[0].selectionStart; + let currentContent = $input.val(); const mdImageText = "![](http://)"; - input.val(currentContent.substring(0, caretPos) + mdImageText + currentContent.substring(caretPos)); - input.focus(); - input[0].selectionStart = caretPos + ("![](".length); - input[0].selectionEnd = caretPos + ('![](http://'.length); + $input.val(currentContent.substring(0, caretPos) + mdImageText + currentContent.substring(caretPos)); + $input.focus(); + $input[0].selectionStart = caretPos + ("![](".length); + $input[0].selectionEnd = caretPos + ('![](http://'.length); return; } @@ -410,35 +342,35 @@ export default function (ngApp, events) { }); // Insert image from image manager - insertImage.click(event => { + $insertImage.click(event => { window.ImageManager.showExternal(image => { let caretPos = currentCaretPos; - let currentContent = input.val(); + let currentContent = $input.val(); let mdImageText = "![" + image.name + "](" + image.thumbs.display + ")"; - input.val(currentContent.substring(0, caretPos) + mdImageText + currentContent.substring(caretPos)); - input.change(); + $input.val(currentContent.substring(0, caretPos) + mdImageText + currentContent.substring(caretPos)); + $input.change(); }); }); function showLinkSelector() { window.showEntityLinkSelector((entity) => { let selectionStart = currentCaretPos; - let selectionEnd = input[0].selectionEnd; + let selectionEnd = $input[0].selectionEnd; let textSelected = (selectionEnd !== selectionStart); - let currentContent = input.val(); + let currentContent = $input.val(); if (textSelected) { let selectedText = currentContent.substring(selectionStart, selectionEnd); let linkText = `[${selectedText}](${entity.link})`; - input.val(currentContent.substring(0, selectionStart) + linkText + currentContent.substring(selectionEnd)); + $input.val(currentContent.substring(0, selectionStart) + linkText + currentContent.substring(selectionEnd)); } else { let linkText = ` [${entity.name}](${entity.link}) `; - input.val(currentContent.substring(0, selectionStart) + linkText + currentContent.substring(selectionStart)) + $input.val(currentContent.substring(0, selectionStart) + linkText + currentContent.substring(selectionStart)) } - input.change(); + $input.change(); }); } - insertEntityLink.click(showLinkSelector); + $insertEntityLink.click(showLinkSelector); // Upload and insert image on paste function editorPaste(e) { @@ -451,7 +383,7 @@ export default function (ngApp, events) { } } - input.on('paste', editorPaste); + $input.on('paste', editorPaste); // Handle image drop, Uploads images to BookStack. function handleImageDrop(event) { @@ -463,11 +395,11 @@ export default function (ngApp, events) { } } - input.on('drop', handleImageDrop); + $input.on('drop', handleImageDrop); // Handle image upload and add image into markdown content function uploadImage(file) { - if (file.type.indexOf('image') !== 0) return; + if (file === null || !file.type.indexOf('image') !== 0) return; let formData = new FormData(); let ext = 'png'; let xhr = new XMLHttpRequest(); @@ -481,17 +413,17 @@ export default function (ngApp, events) { // Insert image into markdown let id = "image-" + Math.random().toString(16).slice(2); - let selectStart = input[0].selectionStart; - let selectEnd = input[0].selectionEnd; - let content = input[0].value; + let selectStart = $input[0].selectionStart; + let selectEnd = $input[0].selectionEnd; + let content = $input[0].value; let selectText = content.substring(selectStart, selectEnd); let placeholderImage = window.baseUrl(`/loading.gif#upload${id}`); let innerContent = ((selectEnd > selectStart) ? `![${selectText}]` : '![]') + `(${placeholderImage})`; - input[0].value = content.substring(0, selectStart) + innerContent + content.substring(selectEnd); + $input[0].value = content.substring(0, selectStart) + innerContent + content.substring(selectEnd); - input.focus(); - input[0].selectionStart = selectStart; - input[0].selectionEnd = selectStart; + $input.focus(); + $input[0].selectionStart = selectStart; + $input[0].selectionEnd = selectStart; let remoteFilename = "image-" + Date.now() + "." + ext; formData.append('file', file, remoteFilename); @@ -499,20 +431,20 @@ export default function (ngApp, events) { xhr.open('POST', window.baseUrl('/images/gallery/upload')); xhr.onload = function () { - let selectStart = input[0].selectionStart; + let selectStart = $input[0].selectionStart; if (xhr.status === 200 || xhr.status === 201) { let result = JSON.parse(xhr.responseText); - input[0].value = input[0].value.replace(placeholderImage, result.thumbs.display); - input.change(); + $input[0].value = $input[0].value.replace(placeholderImage, result.thumbs.display); + $input.change(); } else { - console.log('An error occurred uploading the image'); + console.log(trans('errors.image_upload_error')); console.log(xhr.responseText); - input[0].value = input[0].value.replace(innerContent, ''); - input.change(); + $input[0].value = $input[0].value.replace(innerContent, ''); + $input.change(); } - input.focus(); - input[0].selectionStart = selectStart; - input[0].selectionEnd = selectStart; + $input.focus(); + $input[0].selectionStart = selectStart; + $input[0].selectionEnd = selectStart; }; xhr.send(formData); } @@ -650,8 +582,7 @@ export default function (ngApp, events) { } // Enter or tab key else if ((event.keyCode === 13 || event.keyCode === 9) && !event.shiftKey) { - let text = suggestionElems[active].textContent; - currentInput[0].value = text; + currentInput[0].value = suggestionElems[active].textContent; currentInput.focus(); $suggestionBox.hide(); isShowing = false; @@ -747,7 +678,7 @@ export default function (ngApp, events) { ngApp.directive('entityLinkSelector', [function($http) { return { - restict: 'A', + restrict: 'A', link: function(scope, element, attrs) { const selectButton = element.find('.entity-link-selector-confirm');