3 import moment from 'moment';
4 import 'moment/locale/en-gb';
5 moment.locale('en-gb');
7 export default function (ngApp, events) {
9 ngApp.controller('ImageManagerController', ['$scope', '$attrs', '$http', '$timeout', 'imageManagerService',
10 function ($scope, $attrs, $http, $timeout, imageManagerService) {
13 $scope.imageType = $attrs.imageType;
14 $scope.selectedImage = false;
15 $scope.dependantPages = false;
16 $scope.showing = false;
17 $scope.hasMore = false;
18 $scope.imageUpdateSuccess = false;
19 $scope.imageDeleteSuccess = false;
20 $scope.uploadedTo = $attrs.uploadedTo;
23 $scope.searching = false;
24 $scope.searchTerm = '';
27 var previousClickTime = 0;
28 var previousClickImage = 0;
29 var dataLoaded = false;
32 var preSearchImages = [];
33 var preSearchHasMore = false;
36 * Used by dropzone to get the endpoint to upload to.
39 $scope.getUploadUrl = function () {
40 return window.baseUrl('/images/' + $scope.imageType + '/upload');
44 * Cancel the current search operation.
46 function cancelSearch() {
47 $scope.searching = false;
48 $scope.searchTerm = '';
49 $scope.images = preSearchImages;
50 $scope.hasMore = preSearchHasMore;
52 $scope.cancelSearch = cancelSearch;
56 * Runs on image upload, Adds an image to local list of images
57 * and shows a success message to the user.
61 $scope.uploadSuccess = function (file, data) {
63 $scope.images.unshift(data);
65 events.emit('success', 'Image uploaded');
69 * Runs the callback and hides the image manager.
72 function callbackAndHide(returnData) {
73 if (callback) callback(returnData);
78 * Image select action. Checks if a double-click was fired.
81 $scope.imageSelect = function (image) {
82 var dblClickTime = 300;
83 var currentTime = Date.now();
84 var timeDiff = currentTime - previousClickTime;
86 if (timeDiff < dblClickTime && image.id === previousClickImage) {
88 callbackAndHide(image);
91 $scope.selectedImage = image;
92 $scope.dependantPages = false;
94 previousClickTime = currentTime;
95 previousClickImage = image.id;
99 * Action that runs when the 'Select image' button is clicked.
100 * Runs the callback and hides the image manager.
102 $scope.selectButtonClick = function () {
103 callbackAndHide($scope.selectedImage);
107 * Show the image manager.
108 * Takes a callback to execute later on.
109 * @param doneCallback
111 function show(doneCallback) {
112 callback = doneCallback;
113 $scope.showing = true;
114 $('#image-manager').find('.overlay').css('display', 'flex').hide().fadeIn(240);
115 // Get initial images if they have not yet been loaded in.
122 // Connects up the image manger so it can be used externally
123 // such as from TinyMCE.
124 imageManagerService.show = show;
125 imageManagerService.showExternal = function (doneCallback) {
126 $scope.$apply(() => {
130 window.ImageManager = imageManagerService;
133 * Hide the image manager
135 $scope.hide = function () {
136 $scope.showing = false;
137 $('#image-manager').find('.overlay').fadeOut(240);
140 var baseUrl = window.baseUrl('/images/' + $scope.imageType + '/all/');
143 * Fetch the list image data from the server.
145 function fetchData() {
146 var url = baseUrl + page + '?';
148 if ($scope.uploadedTo) components['page_id'] = $scope.uploadedTo;
149 if ($scope.searching) components['term'] = $scope.searchTerm;
152 var urlQueryString = Object.keys(components).map((key) => {
153 return key + '=' + encodeURIComponent(components[key]);
155 url += urlQueryString;
157 $http.get(url).then((response) => {
158 $scope.images = $scope.images.concat(response.data.images);
159 $scope.hasMore = response.data.hasMore;
163 $scope.fetchData = fetchData;
166 * Start a search operation
168 $scope.searchImages = function() {
170 if ($scope.searchTerm === '') {
175 if (!$scope.searching) {
176 preSearchImages = $scope.images;
177 preSearchHasMore = $scope.hasMore;
180 $scope.searching = true;
182 $scope.hasMore = false;
184 baseUrl = window.baseUrl('/images/' + $scope.imageType + '/search/');
189 * Set the current image listing view.
192 $scope.setView = function(viewName) {
195 $scope.hasMore = false;
197 $scope.view = viewName;
198 baseUrl = window.baseUrl('/images/' + $scope.imageType + '/' + viewName + '/');
203 * Save the details of an image.
206 $scope.saveImageDetails = function (event) {
207 event.preventDefault();
208 var url = window.baseUrl('/images/update/' + $scope.selectedImage.id);
209 $http.put(url, this.selectedImage).then(response => {
210 events.emit('success', 'Image details updated');
212 if (response.status === 422) {
213 var errors = response.data;
215 Object.keys(errors).forEach((key) => {
216 message += errors[key].join('\n');
218 events.emit('error', message);
219 } else if (response.status === 403) {
220 events.emit('error', response.data.error);
226 * Delete an image from system and notify of success.
227 * Checks if it should force delete when an image
228 * has dependant pages.
231 $scope.deleteImage = function (event) {
232 event.preventDefault();
233 var force = $scope.dependantPages !== false;
234 var url = window.baseUrl('/images/' + $scope.selectedImage.id);
235 if (force) url += '?force=true';
236 $http.delete(url).then((response) => {
237 $scope.images.splice($scope.images.indexOf($scope.selectedImage), 1);
238 $scope.selectedImage = false;
239 events.emit('success', 'Image successfully deleted');
242 if (response.status === 400) {
243 $scope.dependantPages = response.data;
244 } else if (response.status === 403) {
245 events.emit('error', response.data.error);
251 * Simple date creator used to properly format dates.
255 $scope.getDate = function (stringDate) {
256 return new Date(stringDate);
262 ngApp.controller('BookShowController', ['$scope', '$http', '$attrs', '$sce', function ($scope, $http, $attrs, $sce) {
263 $scope.searching = false;
264 $scope.searchTerm = '';
265 $scope.searchResults = '';
267 $scope.searchBook = function (e) {
269 var term = $scope.searchTerm;
270 if (term.length == 0) return;
271 $scope.searching = true;
272 $scope.searchResults = '';
273 var searchUrl = window.baseUrl('/search/book/' + $attrs.bookId);
274 searchUrl += '?term=' + encodeURIComponent(term);
275 $http.get(searchUrl).then((response) => {
276 $scope.searchResults = $sce.trustAsHtml(response.data);
280 $scope.checkSearchForm = function () {
281 if ($scope.searchTerm.length < 1) {
282 $scope.searching = false;
286 $scope.clearSearch = function () {
287 $scope.searching = false;
288 $scope.searchTerm = '';
294 ngApp.controller('PageEditController', ['$scope', '$http', '$attrs', '$interval', '$timeout', '$sce',
295 function ($scope, $http, $attrs, $interval, $timeout, $sce) {
297 $scope.editorOptions = require('./pages/page-form');
298 $scope.editContent = '';
299 $scope.draftText = '';
300 var pageId = Number($attrs.pageId);
301 var isEdit = pageId !== 0;
302 var autosaveFrequency = 30; // AutoSave interval in seconds.
303 var isMarkdown = $attrs.editorType === 'markdown';
304 $scope.draftsEnabled = $attrs.draftsEnabled === 'true';
305 $scope.isUpdateDraft = Number($attrs.pageUpdateDraft) === 1;
306 $scope.isNewPageDraft = Number($attrs.pageNewDraft) === 1;
308 // Set initial header draft text
309 if ($scope.isUpdateDraft || $scope.isNewPageDraft) {
310 $scope.draftText = 'Editing Draft'
312 $scope.draftText = 'Editing Page'
315 var autoSave = false;
317 var currentContent = {
322 if (isEdit && $scope.draftsEnabled) {
328 // Actions specifically for the markdown editor
330 $scope.displayContent = '';
331 // Editor change event
332 $scope.editorChange = function (content) {
333 $scope.displayContent = $sce.trustAsHtml(content);
338 $scope.editorChange = function() {};
344 * Start the AutoSave loop, Checks for content change
345 * before performing the costly AJAX request.
347 function startAutoSave() {
348 currentContent.title = $('#name').val();
349 currentContent.html = $scope.editContent;
351 autoSave = $interval(() => {
352 // Return if manually saved recently to prevent bombarding the server
353 if (Date.now() - lastSave < (1000*autosaveFrequency)/2) return;
354 var newTitle = $('#name').val();
355 var newHtml = $scope.editContent;
357 if (newTitle !== currentContent.title || newHtml !== currentContent.html) {
358 currentContent.html = newHtml;
359 currentContent.title = newTitle;
363 }, 1000 * autosaveFrequency);
366 let draftErroring = false;
368 * Save a draft update into the system via an AJAX request.
370 function saveDraft() {
371 if (!$scope.draftsEnabled) return;
373 name: $('#name').val(),
374 html: isMarkdown ? $sce.getTrustedHtml($scope.displayContent) : $scope.editContent
377 if (isMarkdown) data.markdown = $scope.editContent;
379 let url = window.baseUrl('/ajax/page/' + pageId + '/save-draft');
380 $http.put(url, data).then(responseData => {
381 draftErroring = false;
382 var updateTime = moment.utc(moment.unix(responseData.data.timestamp)).toDate();
383 $scope.draftText = responseData.data.message + moment(updateTime).format('HH:mm');
384 if (!$scope.isNewPageDraft) $scope.isUpdateDraft = true;
385 showDraftSaveNotification();
386 lastSave = Date.now();
388 if (draftErroring) return;
389 events.emit('error', 'Failed to save draft. Ensure you have internet connection before saving this page.')
390 draftErroring = true;
394 function showDraftSaveNotification() {
395 $scope.draftUpdated = true;
397 $scope.draftUpdated = false;
401 $scope.forceDraftSave = function() {
405 // Listen to shortcuts coming via events
406 $scope.$on('editor-keydown', (event, data) => {
407 // Save shortcut (ctrl+s)
408 if (data.keyCode == 83 && (navigator.platform.match("Mac") ? data.metaKey : data.ctrlKey)) {
409 data.preventDefault();
415 * Discard the current draft and grab the current page
416 * content from the system via an AJAX request.
418 $scope.discardDraft = function () {
419 let url = window.baseUrl('/ajax/page/' + pageId);
420 $http.get(url).then((responseData) => {
421 if (autoSave) $interval.cancel(autoSave);
422 $scope.draftText = 'Editing Page';
423 $scope.isUpdateDraft = false;
424 $scope.$broadcast('html-update', responseData.data.html);
425 $scope.$broadcast('markdown-update', responseData.data.markdown || responseData.data.html);
426 $('#name').val(responseData.data.name);
430 events.emit('success', 'Draft discarded, The editor has been updated with the current page content');
436 ngApp.controller('PageTagController', ['$scope', '$http', '$attrs',
437 function ($scope, $http, $attrs) {
439 const pageId = Number($attrs.pageId);
442 $scope.sortOptions = {
445 containment: "parent",
450 * Push an empty tag to the end of the scope tags.
452 function addEmptyTag() {
458 $scope.addEmptyTag = addEmptyTag;
461 * Get all tags for the current book and add into scope.
464 let url = window.baseUrl(`/ajax/tags/get/page/${pageId}`);
465 $http.get(url).then((responseData) => {
466 $scope.tags = responseData.data;
473 * Set the order property on all tags.
475 function setTagOrder() {
476 for (let i = 0; i < $scope.tags.length; i++) {
477 $scope.tags[i].order = i;
482 * When an tag changes check if another empty editable
483 * field needs to be added onto the end.
486 $scope.tagChange = function(tag) {
487 let cPos = $scope.tags.indexOf(tag);
488 if (cPos !== $scope.tags.length-1) return;
490 if (tag.name !== '' || tag.value !== '') {
496 * When an tag field loses focus check the tag to see if its
497 * empty and therefore could be removed from the list.
500 $scope.tagBlur = function(tag) {
501 let isLast = $scope.tags.length - 1 === $scope.tags.indexOf(tag);
502 if (tag.name === '' && tag.value === '' && !isLast) {
503 let cPos = $scope.tags.indexOf(tag);
504 $scope.tags.splice(cPos, 1);
509 * Save the tags to the current page.
511 $scope.saveTags = function() {
513 let postData = {tags: $scope.tags};
514 let url = window.baseUrl('/ajax/tags/update/page/' + pageId);
515 $http.post(url, postData).then((responseData) => {
516 $scope.tags = responseData.data.tags;
518 events.emit('success', responseData.data.message);
523 * Remove a tag from the current list.
526 $scope.removeTag = function(tag) {
527 let cIndex = $scope.tags.indexOf(tag);
528 $scope.tags.splice(cIndex, 1);
534 ngApp.controller('PageAttachmentController', ['$scope', '$http', '$attrs',
535 function ($scope, $http, $attrs) {
537 const pageId = $scope.uploadedTo = $attrs.pageId;
538 let currentOrder = '';
540 $scope.editFile = false;
541 $scope.file = getCleanFile();
547 function getCleanFile() {
553 // Angular-UI-Sort options
554 $scope.sortOptions = {
557 containment: "parent",
563 * Event listener for sort changes.
564 * Updates the file ordering on the server.
568 function sortUpdate(event, ui) {
569 let newOrder = $scope.files.map(file => {return file.id}).join(':');
570 if (newOrder === currentOrder) return;
572 currentOrder = newOrder;
573 $http.put(window.baseUrl(`/files/sort/page/${pageId}`), {files: $scope.files}).then(resp => {
574 events.emit('success', resp.data.message);
575 }, checkError('sort'));
579 * Used by dropzone to get the endpoint to upload to.
582 $scope.getUploadUrl = function (file) {
583 let suffix = (typeof file !== 'undefined') ? `/${file.id}` : '';
584 return window.baseUrl(`/files/upload${suffix}`);
588 * Get files for the current page from the server.
590 function getFiles() {
591 let url = window.baseUrl(`/files/get/page/${pageId}`)
592 $http.get(url).then(resp => {
593 $scope.files = resp.data;
594 currentOrder = resp.data.map(file => {return file.id}).join(':');
595 }, checkError('get'));
600 * Runs on file upload, Adds an file to local file list
601 * and shows a success message to the user.
605 $scope.uploadSuccess = function (file, data) {
606 $scope.$apply(() => {
607 $scope.files.push(data);
609 events.emit('success', 'File uploaded');
613 * Upload and overwrite an existing file.
617 $scope.uploadSuccessUpdate = function (file, data) {
618 $scope.$apply(() => {
619 let search = filesIndexOf(data);
620 if (search !== -1) $scope.files[search] = data;
622 if ($scope.editFile) {
623 $scope.editFile = angular.copy(data);
627 events.emit('success', 'File updated');
631 * Delete a file from the server and, on success, the local listing.
634 $scope.deleteFile = function(file) {
635 if (!file.deleting) {
636 file.deleting = true;
639 $http.delete(window.baseUrl(`/files/${file.id}`)).then(resp => {
640 events.emit('success', resp.data.message);
641 $scope.files.splice($scope.files.indexOf(file), 1);
642 }, checkError('delete'));
646 * Attach a link to a page.
649 $scope.attachLinkSubmit = function(file) {
650 file.uploaded_to = pageId;
651 $http.post(window.baseUrl('/files/link'), file).then(resp => {
652 $scope.files.push(resp.data);
653 events.emit('success', 'Link attached');
654 $scope.file = getCleanFile();
655 }, checkError('link'));
659 * Start the edit mode for a file.
662 $scope.startEdit = function(file) {
663 $scope.editFile = angular.copy(file);
664 $scope.editFile.link = (file.external) ? file.path : '';
670 $scope.cancelEdit = function() {
671 $scope.editFile = false;
675 * Update the name and link of a file.
678 $scope.updateFile = function(file) {
679 $http.put(window.baseUrl(`/files/${file.id}`), file).then(resp => {
680 let search = filesIndexOf(resp.data);
681 if (search !== -1) $scope.files[search] = resp.data;
683 if ($scope.editFile && !file.external) {
684 $scope.editFile.link = '';
686 $scope.editFile = false;
687 events.emit('success', 'Attachment details updated');
688 }, checkError('edit'));
692 * Get the url of a file.
694 $scope.getFileUrl = function(file) {
695 return window.baseUrl('/files/' + file.id);
699 * Search the local files via another file object.
700 * Used to search via object copies.
704 function filesIndexOf(file) {
705 for (let i = 0; i < $scope.files.length; i++) {
706 if ($scope.files[i].id == file.id) return i;
712 * Check for an error response in a ajax request.
713 * @param errorGroupName
715 function checkError(errorGroupName) {
716 $scope.errors[errorGroupName] = {};
717 return function(response) {
718 if (typeof response.data !== 'undefined' && typeof response.data.error !== 'undefined') {
719 events.emit('error', response.data.error);
721 if (typeof response.data !== 'undefined' && typeof response.data.validation !== 'undefined') {
722 $scope.errors[errorGroupName] = response.data.validation;
723 console.log($scope.errors[errorGroupName])