3 import moment from 'moment';
4 import 'moment/locale/en-gb';
5 import editorOptions from "./pages/page-form";
7 moment.locale('en-gb');
9 export default function (ngApp, events) {
11 ngApp.controller('ImageManagerController', ['$scope', '$attrs', '$http', '$timeout', 'imageManagerService',
12 function ($scope, $attrs, $http, $timeout, imageManagerService) {
15 $scope.imageType = $attrs.imageType;
16 $scope.selectedImage = false;
17 $scope.dependantPages = false;
18 $scope.showing = false;
19 $scope.hasMore = false;
20 $scope.imageUpdateSuccess = false;
21 $scope.imageDeleteSuccess = false;
22 $scope.uploadedTo = $attrs.uploadedTo;
25 $scope.searching = false;
26 $scope.searchTerm = '';
29 let previousClickTime = 0;
30 let previousClickImage = 0;
31 let dataLoaded = false;
34 let preSearchImages = [];
35 let preSearchHasMore = false;
38 * Used by dropzone to get the endpoint to upload to.
41 $scope.getUploadUrl = function () {
42 return window.baseUrl('/images/' + $scope.imageType + '/upload');
46 * Cancel the current search operation.
48 function cancelSearch() {
49 $scope.searching = false;
50 $scope.searchTerm = '';
51 $scope.images = preSearchImages;
52 $scope.hasMore = preSearchHasMore;
54 $scope.cancelSearch = cancelSearch;
58 * Runs on image upload, Adds an image to local list of images
59 * and shows a success message to the user.
63 $scope.uploadSuccess = function (file, data) {
65 $scope.images.unshift(data);
67 events.emit('success', trans('components.image_upload_success'));
71 * Runs the callback and hides the image manager.
74 function callbackAndHide(returnData) {
75 if (callback) callback(returnData);
80 * Image select action. Checks if a double-click was fired.
83 $scope.imageSelect = function (image) {
84 let dblClickTime = 300;
85 let currentTime = Date.now();
86 let timeDiff = currentTime - previousClickTime;
88 if (timeDiff < dblClickTime && image.id === previousClickImage) {
90 callbackAndHide(image);
93 $scope.selectedImage = image;
94 $scope.dependantPages = false;
96 previousClickTime = currentTime;
97 previousClickImage = image.id;
101 * Action that runs when the 'Select image' button is clicked.
102 * Runs the callback and hides the image manager.
104 $scope.selectButtonClick = function () {
105 callbackAndHide($scope.selectedImage);
109 * Show the image manager.
110 * Takes a callback to execute later on.
111 * @param doneCallback
113 function show(doneCallback) {
114 callback = doneCallback;
115 $scope.showing = true;
116 $('#image-manager').find('.overlay').css('display', 'flex').hide().fadeIn(240);
117 // Get initial images if they have not yet been loaded in.
124 // Connects up the image manger so it can be used externally
125 // such as from TinyMCE.
126 imageManagerService.show = show;
127 imageManagerService.showExternal = function (doneCallback) {
128 $scope.$apply(() => {
132 window.ImageManager = imageManagerService;
135 * Hide the image manager
137 $scope.hide = function () {
138 $scope.showing = false;
139 $('#image-manager').find('.overlay').fadeOut(240);
142 let baseUrl = window.baseUrl('/images/' + $scope.imageType + '/all/');
145 * Fetch the list image data from the server.
147 function fetchData() {
148 let url = baseUrl + page + '?';
150 if ($scope.uploadedTo) components['page_id'] = $scope.uploadedTo;
151 if ($scope.searching) components['term'] = $scope.searchTerm;
154 url += Object.keys(components).map((key) => {
155 return key + '=' + encodeURIComponent(components[key]);
158 $http.get(url).then((response) => {
159 $scope.images = $scope.images.concat(response.data.images);
160 $scope.hasMore = response.data.hasMore;
164 $scope.fetchData = fetchData;
167 * Start a search operation
169 $scope.searchImages = function() {
171 if ($scope.searchTerm === '') {
176 if (!$scope.searching) {
177 preSearchImages = $scope.images;
178 preSearchHasMore = $scope.hasMore;
181 $scope.searching = true;
183 $scope.hasMore = false;
185 baseUrl = window.baseUrl('/images/' + $scope.imageType + '/search/');
190 * Set the current image listing view.
193 $scope.setView = function(viewName) {
196 $scope.hasMore = false;
198 $scope.view = viewName;
199 baseUrl = window.baseUrl('/images/' + $scope.imageType + '/' + viewName + '/');
204 * Save the details of an image.
207 $scope.saveImageDetails = function (event) {
208 event.preventDefault();
209 let url = window.baseUrl('/images/update/' + $scope.selectedImage.id);
210 $http.put(url, this.selectedImage).then(response => {
211 events.emit('success', trans('components.image_update_success'));
213 if (response.status === 422) {
214 let errors = response.data;
216 Object.keys(errors).forEach((key) => {
217 message += errors[key].join('\n');
219 events.emit('error', message);
220 } else if (response.status === 403) {
221 events.emit('error', response.data.error);
227 * Delete an image from system and notify of success.
228 * Checks if it should force delete when an image
229 * has dependant pages.
232 $scope.deleteImage = function (event) {
233 event.preventDefault();
234 let force = $scope.dependantPages !== false;
235 let url = window.baseUrl('/images/' + $scope.selectedImage.id);
236 if (force) url += '?force=true';
237 $http.delete(url).then((response) => {
238 $scope.images.splice($scope.images.indexOf($scope.selectedImage), 1);
239 $scope.selectedImage = false;
240 events.emit('success', trans('components.image_delete_success'));
243 if (response.status === 400) {
244 $scope.dependantPages = response.data;
245 } else if (response.status === 403) {
246 events.emit('error', response.data.error);
252 * Simple date creator used to properly format dates.
256 $scope.getDate = function (stringDate) {
257 return new Date(stringDate);
263 ngApp.controller('BookShowController', ['$scope', '$http', '$attrs', '$sce', function ($scope, $http, $attrs, $sce) {
264 $scope.searching = false;
265 $scope.searchTerm = '';
266 $scope.searchResults = '';
268 $scope.searchBook = function (e) {
270 let term = $scope.searchTerm;
271 if (term.length == 0) return;
272 $scope.searching = true;
273 $scope.searchResults = '';
274 let searchUrl = window.baseUrl('/search/book/' + $attrs.bookId);
275 searchUrl += '?term=' + encodeURIComponent(term);
276 $http.get(searchUrl).then((response) => {
277 $scope.searchResults = $sce.trustAsHtml(response.data);
281 $scope.checkSearchForm = function () {
282 if ($scope.searchTerm.length < 1) {
283 $scope.searching = false;
287 $scope.clearSearch = function () {
288 $scope.searching = false;
289 $scope.searchTerm = '';
295 ngApp.controller('PageEditController', ['$scope', '$http', '$attrs', '$interval', '$timeout', '$sce',
296 function ($scope, $http, $attrs, $interval, $timeout, $sce) {
298 $scope.editorOptions = editorOptions();
299 $scope.editContent = '';
300 $scope.draftText = '';
301 let pageId = Number($attrs.pageId);
302 let isEdit = pageId !== 0;
303 let autosaveFrequency = 30; // AutoSave interval in seconds.
304 let isMarkdown = $attrs.editorType === 'markdown';
305 $scope.draftsEnabled = $attrs.draftsEnabled === 'true';
306 $scope.isUpdateDraft = Number($attrs.pageUpdateDraft) === 1;
307 $scope.isNewPageDraft = Number($attrs.pageNewDraft) === 1;
309 // Set initial header draft text
310 if ($scope.isUpdateDraft || $scope.isNewPageDraft) {
311 $scope.draftText = trans('entities.pages_editing_draft');
313 $scope.draftText = trans('entities.pages_editing_page');
316 let autoSave = false;
318 let currentContent = {
323 if (isEdit && $scope.draftsEnabled) {
329 // Actions specifically for the markdown editor
331 $scope.displayContent = '';
332 // Editor change event
333 $scope.editorChange = function (content) {
334 $scope.displayContent = $sce.trustAsHtml(content);
339 $scope.editorChange = function() {};
345 * Start the AutoSave loop, Checks for content change
346 * before performing the costly AJAX request.
348 function startAutoSave() {
349 currentContent.title = $('#name').val();
350 currentContent.html = $scope.editContent;
352 autoSave = $interval(() => {
353 // Return if manually saved recently to prevent bombarding the server
354 if (Date.now() - lastSave < (1000*autosaveFrequency)/2) return;
355 let newTitle = $('#name').val();
356 let newHtml = $scope.editContent;
358 if (newTitle !== currentContent.title || newHtml !== currentContent.html) {
359 currentContent.html = newHtml;
360 currentContent.title = newTitle;
364 }, 1000 * autosaveFrequency);
367 let draftErroring = false;
369 * Save a draft update into the system via an AJAX request.
371 function saveDraft() {
372 if (!$scope.draftsEnabled) return;
374 name: $('#name').val(),
375 html: isMarkdown ? $sce.getTrustedHtml($scope.displayContent) : $scope.editContent
378 if (isMarkdown) data.markdown = $scope.editContent;
380 let url = window.baseUrl('/ajax/page/' + pageId + '/save-draft');
381 $http.put(url, data).then(responseData => {
382 draftErroring = false;
383 let updateTime = moment.utc(moment.unix(responseData.data.timestamp)).toDate();
384 $scope.draftText = responseData.data.message + moment(updateTime).format('HH:mm');
385 if (!$scope.isNewPageDraft) $scope.isUpdateDraft = true;
386 showDraftSaveNotification();
387 lastSave = Date.now();
389 if (draftErroring) return;
390 events.emit('error', trans('errors.page_draft_autosave_fail'));
391 draftErroring = true;
395 function showDraftSaveNotification() {
396 $scope.draftUpdated = true;
398 $scope.draftUpdated = false;
402 $scope.forceDraftSave = function() {
406 // Listen to shortcuts coming via events
407 $scope.$on('editor-keydown', (event, data) => {
408 // Save shortcut (ctrl+s)
409 if (data.keyCode == 83 && (navigator.platform.match("Mac") ? data.metaKey : data.ctrlKey)) {
410 data.preventDefault();
416 * Discard the current draft and grab the current page
417 * content from the system via an AJAX request.
419 $scope.discardDraft = function () {
420 let url = window.baseUrl('/ajax/page/' + pageId);
421 $http.get(url).then((responseData) => {
422 if (autoSave) $interval.cancel(autoSave);
423 $scope.draftText = trans('entities.pages_editing_page');
424 $scope.isUpdateDraft = false;
425 $scope.$broadcast('html-update', responseData.data.html);
426 $scope.$broadcast('markdown-update', responseData.data.markdown || responseData.data.html);
427 $('#name').val(responseData.data.name);
431 events.emit('success', trans('entities.pages_draft_discarded'));
437 ngApp.controller('PageTagController', ['$scope', '$http', '$attrs',
438 function ($scope, $http, $attrs) {
440 const pageId = Number($attrs.pageId);
443 $scope.sortOptions = {
446 containment: "parent",
451 * Push an empty tag to the end of the scope tags.
453 function addEmptyTag() {
459 $scope.addEmptyTag = addEmptyTag;
462 * Get all tags for the current book and add into scope.
465 let url = window.baseUrl(`/ajax/tags/get/page/${pageId}`);
466 $http.get(url).then((responseData) => {
467 $scope.tags = responseData.data;
474 * Set the order property on all tags.
476 function setTagOrder() {
477 for (let i = 0; i < $scope.tags.length; i++) {
478 $scope.tags[i].order = i;
483 * When an tag changes check if another empty editable
484 * field needs to be added onto the end.
487 $scope.tagChange = function(tag) {
488 let cPos = $scope.tags.indexOf(tag);
489 if (cPos !== $scope.tags.length-1) return;
491 if (tag.name !== '' || tag.value !== '') {
497 * When an tag field loses focus check the tag to see if its
498 * empty and therefore could be removed from the list.
501 $scope.tagBlur = function(tag) {
502 let isLast = $scope.tags.length - 1 === $scope.tags.indexOf(tag);
503 if (tag.name === '' && tag.value === '' && !isLast) {
504 let cPos = $scope.tags.indexOf(tag);
505 $scope.tags.splice(cPos, 1);
510 * Remove a tag from the current list.
513 $scope.removeTag = function(tag) {
514 let cIndex = $scope.tags.indexOf(tag);
515 $scope.tags.splice(cIndex, 1);
521 ngApp.controller('PageAttachmentController', ['$scope', '$http', '$attrs',
522 function ($scope, $http, $attrs) {
524 const pageId = $scope.uploadedTo = $attrs.pageId;
525 let currentOrder = '';
527 $scope.editFile = false;
528 $scope.file = getCleanFile();
534 function getCleanFile() {
540 // Angular-UI-Sort options
541 $scope.sortOptions = {
544 containment: "parent",
550 * Event listener for sort changes.
551 * Updates the file ordering on the server.
555 function sortUpdate(event, ui) {
556 let newOrder = $scope.files.map(file => {return file.id}).join(':');
557 if (newOrder === currentOrder) return;
559 currentOrder = newOrder;
560 $http.put(window.baseUrl(`/attachments/sort/page/${pageId}`), {files: $scope.files}).then(resp => {
561 events.emit('success', resp.data.message);
562 }, checkError('sort'));
566 * Used by dropzone to get the endpoint to upload to.
569 $scope.getUploadUrl = function (file) {
570 let suffix = (typeof file !== 'undefined') ? `/${file.id}` : '';
571 return window.baseUrl(`/attachments/upload${suffix}`);
575 * Get files for the current page from the server.
577 function getFiles() {
578 let url = window.baseUrl(`/attachments/get/page/${pageId}`);
579 $http.get(url).then(resp => {
580 $scope.files = resp.data;
581 currentOrder = resp.data.map(file => {return file.id}).join(':');
582 }, checkError('get'));
587 * Runs on file upload, Adds an file to local file list
588 * and shows a success message to the user.
592 $scope.uploadSuccess = function (file, data) {
593 $scope.$apply(() => {
594 $scope.files.push(data);
596 events.emit('success', trans('entities.attachments_file_uploaded'));
600 * Upload and overwrite an existing file.
604 $scope.uploadSuccessUpdate = function (file, data) {
605 $scope.$apply(() => {
606 let search = filesIndexOf(data);
607 if (search !== -1) $scope.files[search] = data;
609 if ($scope.editFile) {
610 $scope.editFile = angular.copy(data);
614 events.emit('success', trans('entities.attachments_file_updated'));
618 * Delete a file from the server and, on success, the local listing.
621 $scope.deleteFile = function(file) {
622 if (!file.deleting) {
623 file.deleting = true;
626 $http.delete(window.baseUrl(`/attachments/${file.id}`)).then(resp => {
627 events.emit('success', resp.data.message);
628 $scope.files.splice($scope.files.indexOf(file), 1);
629 }, checkError('delete'));
633 * Attach a link to a page.
636 $scope.attachLinkSubmit = function(file) {
637 file.uploaded_to = pageId;
638 $http.post(window.baseUrl('/attachments/link'), file).then(resp => {
639 $scope.files.push(resp.data);
640 events.emit('success', trans('entities.attachments_link_attached'));
641 $scope.file = getCleanFile();
642 }, checkError('link'));
646 * Start the edit mode for a file.
649 $scope.startEdit = function(file) {
650 $scope.editFile = angular.copy(file);
651 $scope.editFile.link = (file.external) ? file.path : '';
657 $scope.cancelEdit = function() {
658 $scope.editFile = false;
662 * Update the name and link of a file.
665 $scope.updateFile = function(file) {
666 $http.put(window.baseUrl(`/attachments/${file.id}`), file).then(resp => {
667 let search = filesIndexOf(resp.data);
668 if (search !== -1) $scope.files[search] = resp.data;
670 if ($scope.editFile && !file.external) {
671 $scope.editFile.link = '';
673 $scope.editFile = false;
674 events.emit('success', trans('entities.attachments_updated_success'));
675 }, checkError('edit'));
679 * Get the url of a file.
681 $scope.getFileUrl = function(file) {
682 return window.baseUrl('/attachments/' + file.id);
686 * Search the local files via another file object.
687 * Used to search via object copies.
691 function filesIndexOf(file) {
692 for (let i = 0; i < $scope.files.length; i++) {
693 if ($scope.files[i].id == file.id) return i;
699 * Check for an error response in a ajax request.
700 * @param errorGroupName
702 function checkError(errorGroupName) {
703 $scope.errors[errorGroupName] = {};
704 return function(response) {
705 if (typeof response.data !== 'undefined' && typeof response.data.error !== 'undefined') {
706 events.emit('error', response.data.error);
708 if (typeof response.data !== 'undefined' && typeof response.data.validation !== 'undefined') {
709 $scope.errors[errorGroupName] = response.data.validation;
710 console.log($scope.errors[errorGroupName])