3 const moment = require('moment');
5 module.exports = function (ngApp, events) {
7 ngApp.controller('ImageManagerController', ['$scope', '$attrs', '$http', '$timeout', 'imageManagerService',
8 function ($scope, $attrs, $http, $timeout, imageManagerService) {
11 $scope.imageType = $attrs.imageType;
12 $scope.selectedImage = false;
13 $scope.dependantPages = false;
14 $scope.showing = false;
15 $scope.hasMore = false;
16 $scope.imageUpdateSuccess = false;
17 $scope.imageDeleteSuccess = false;
18 $scope.uploadedTo = $attrs.uploadedTo;
21 $scope.searching = false;
22 $scope.searchTerm = '';
25 var previousClickTime = 0;
26 var previousClickImage = 0;
27 var dataLoaded = false;
30 var preSearchImages = [];
31 var preSearchHasMore = false;
34 * Used by dropzone to get the endpoint to upload to.
37 $scope.getUploadUrl = function () {
38 return window.baseUrl('/images/' + $scope.imageType + '/upload');
42 * Cancel the current search operation.
44 function cancelSearch() {
45 $scope.searching = false;
46 $scope.searchTerm = '';
47 $scope.images = preSearchImages;
48 $scope.hasMore = preSearchHasMore;
50 $scope.cancelSearch = cancelSearch;
54 * Runs on image upload, Adds an image to local list of images
55 * and shows a success message to the user.
59 $scope.uploadSuccess = function (file, data) {
61 $scope.images.unshift(data);
63 events.emit('success', 'Image uploaded');
67 * Runs the callback and hides the image manager.
70 function callbackAndHide(returnData) {
71 if (callback) callback(returnData);
76 * Image select action. Checks if a double-click was fired.
79 $scope.imageSelect = function (image) {
80 var dblClickTime = 300;
81 var currentTime = Date.now();
82 var timeDiff = currentTime - previousClickTime;
84 if (timeDiff < dblClickTime && image.id === previousClickImage) {
86 callbackAndHide(image);
89 $scope.selectedImage = image;
90 $scope.dependantPages = false;
92 previousClickTime = currentTime;
93 previousClickImage = image.id;
97 * Action that runs when the 'Select image' button is clicked.
98 * Runs the callback and hides the image manager.
100 $scope.selectButtonClick = function () {
101 callbackAndHide($scope.selectedImage);
105 * Show the image manager.
106 * Takes a callback to execute later on.
107 * @param doneCallback
109 function show(doneCallback) {
110 callback = doneCallback;
111 $scope.showing = true;
112 $('#image-manager').find('.overlay').css('display', 'flex').hide().fadeIn(240);
113 // Get initial images if they have not yet been loaded in.
120 // Connects up the image manger so it can be used externally
121 // such as from TinyMCE.
122 imageManagerService.show = show;
123 imageManagerService.showExternal = function (doneCallback) {
124 $scope.$apply(() => {
128 window.ImageManager = imageManagerService;
131 * Hide the image manager
133 $scope.hide = function () {
134 $scope.showing = false;
135 $('#image-manager').find('.overlay').fadeOut(240);
138 var baseUrl = window.baseUrl('/images/' + $scope.imageType + '/all/');
141 * Fetch the list image data from the server.
143 function fetchData() {
144 var url = baseUrl + page + '?';
146 if ($scope.uploadedTo) components['page_id'] = $scope.uploadedTo;
147 if ($scope.searching) components['term'] = $scope.searchTerm;
150 var urlQueryString = Object.keys(components).map((key) => {
151 return key + '=' + encodeURIComponent(components[key]);
153 url += urlQueryString;
155 $http.get(url).then((response) => {
156 $scope.images = $scope.images.concat(response.data.images);
157 $scope.hasMore = response.data.hasMore;
161 $scope.fetchData = fetchData;
164 * Start a search operation
167 $scope.searchImages = function() {
169 if ($scope.searchTerm === '') {
174 if (!$scope.searching) {
175 preSearchImages = $scope.images;
176 preSearchHasMore = $scope.hasMore;
179 $scope.searching = true;
181 $scope.hasMore = false;
183 baseUrl = window.baseUrl('/images/' + $scope.imageType + '/search/');
188 * Set the current image listing view.
191 $scope.setView = function(viewName) {
194 $scope.hasMore = false;
196 $scope.view = viewName;
197 baseUrl = window.baseUrl('/images/' + $scope.imageType + '/' + viewName + '/');
202 * Save the details of an image.
205 $scope.saveImageDetails = function (event) {
206 event.preventDefault();
207 var url = window.baseUrl('/images/update/' + $scope.selectedImage.id);
208 $http.put(url, this.selectedImage).then((response) => {
209 events.emit('success', 'Image details updated');
211 if (response.status === 422) {
212 var errors = response.data;
214 Object.keys(errors).forEach((key) => {
215 message += errors[key].join('\n');
217 events.emit('error', message);
218 } else if (response.status === 403) {
219 events.emit('error', response.data.error);
225 * Delete an image from system and notify of success.
226 * Checks if it should force delete when an image
227 * has dependant pages.
230 $scope.deleteImage = function (event) {
231 event.preventDefault();
232 var force = $scope.dependantPages !== false;
233 var url = window.baseUrl('/images/' + $scope.selectedImage.id);
234 if (force) url += '?force=true';
235 $http.delete(url).then((response) => {
236 $scope.images.splice($scope.images.indexOf($scope.selectedImage), 1);
237 $scope.selectedImage = false;
238 events.emit('success', 'Image successfully deleted');
241 if (response.status === 400) {
242 $scope.dependantPages = response.data;
243 } else if (response.status === 403) {
244 events.emit('error', response.data.error);
250 * Simple date creator used to properly format dates.
254 $scope.getDate = function (stringDate) {
255 return new Date(stringDate);
261 ngApp.controller('BookShowController', ['$scope', '$http', '$attrs', '$sce', function ($scope, $http, $attrs, $sce) {
262 $scope.searching = false;
263 $scope.searchTerm = '';
264 $scope.searchResults = '';
266 $scope.searchBook = function (e) {
268 var term = $scope.searchTerm;
269 if (term.length == 0) return;
270 $scope.searching = true;
271 $scope.searchResults = '';
272 var searchUrl = window.baseUrl('/search/book/' + $attrs.bookId);
273 searchUrl += '?term=' + encodeURIComponent(term);
274 $http.get(searchUrl).then((response) => {
275 $scope.searchResults = $sce.trustAsHtml(response.data);
279 $scope.checkSearchForm = function () {
280 if ($scope.searchTerm.length < 1) {
281 $scope.searching = false;
285 $scope.clearSearch = function () {
286 $scope.searching = false;
287 $scope.searchTerm = '';
293 ngApp.controller('PageEditController', ['$scope', '$http', '$attrs', '$interval', '$timeout', '$sce',
294 function ($scope, $http, $attrs, $interval, $timeout, $sce) {
296 $scope.editorOptions = require('./pages/page-form');
297 $scope.editContent = '';
298 $scope.draftText = '';
299 var pageId = Number($attrs.pageId);
300 var isEdit = pageId !== 0;
301 var autosaveFrequency = 30; // AutoSave interval in seconds.
302 var isMarkdown = $attrs.editorType === 'markdown';
303 $scope.draftsEnabled = $attrs.draftsEnabled === 'true';
304 $scope.isUpdateDraft = Number($attrs.pageUpdateDraft) === 1;
305 $scope.isNewPageDraft = Number($attrs.pageNewDraft) === 1;
307 // Set inital header draft text
308 if ($scope.isUpdateDraft || $scope.isNewPageDraft) {
309 $scope.draftText = 'Editing Draft'
311 $scope.draftText = 'Editing Page'
314 var autoSave = false;
316 var currentContent = {
321 if (isEdit && $scope.draftsEnabled) {
327 // Actions specifically for the markdown editor
329 $scope.displayContent = '';
330 // Editor change event
331 $scope.editorChange = function (content) {
332 $scope.displayContent = $sce.trustAsHtml(content);
337 $scope.editorChange = function() {};
343 * Start the AutoSave loop, Checks for content change
344 * before performing the costly AJAX request.
346 function startAutoSave() {
347 currentContent.title = $('#name').val();
348 currentContent.html = $scope.editContent;
350 autoSave = $interval(() => {
351 // Return if manually saved recently to prevent bombarding the server
352 if (Date.now() - lastSave < (1000*autosaveFrequency)/2) return;
353 var newTitle = $('#name').val();
354 var newHtml = $scope.editContent;
356 if (newTitle !== currentContent.title || newHtml !== currentContent.html) {
357 currentContent.html = newHtml;
358 currentContent.title = newTitle;
362 }, 1000 * autosaveFrequency);
365 let draftErroring = false;
367 * Save a draft update into the system via an AJAX request.
369 function saveDraft() {
370 if (!$scope.draftsEnabled) return;
372 name: $('#name').val(),
373 html: isMarkdown ? $sce.getTrustedHtml($scope.displayContent) : $scope.editContent
376 if (isMarkdown) data.markdown = $scope.editContent;
378 let url = window.baseUrl('/ajax/page/' + pageId + '/save-draft');
379 $http.put(url, data).then(responseData => {
380 draftErroring = false;
381 var updateTime = moment.utc(moment.unix(responseData.data.timestamp)).toDate();
382 $scope.draftText = responseData.data.message + moment(updateTime).format('HH:mm');
383 if (!$scope.isNewPageDraft) $scope.isUpdateDraft = true;
384 showDraftSaveNotification();
385 lastSave = Date.now();
387 if (draftErroring) return;
388 events.emit('error', 'Failed to save draft. Ensure you have internet connection before saving this page.')
389 draftErroring = true;
393 function showDraftSaveNotification() {
394 $scope.draftUpdated = true;
396 $scope.draftUpdated = false;
400 $scope.forceDraftSave = function() {
404 // Listen to shortcuts coming via events
405 $scope.$on('editor-keydown', (event, data) => {
406 // Save shortcut (ctrl+s)
407 if (data.keyCode == 83 && (navigator.platform.match("Mac") ? data.metaKey : data.ctrlKey)) {
408 data.preventDefault();
414 * Discard the current draft and grab the current page
415 * content from the system via an AJAX request.
417 $scope.discardDraft = function () {
418 let url = window.baseUrl('/ajax/page/' + pageId);
419 $http.get(url).then((responseData) => {
420 if (autoSave) $interval.cancel(autoSave);
421 $scope.draftText = 'Editing Page';
422 $scope.isUpdateDraft = false;
423 $scope.$broadcast('html-update', responseData.data.html);
424 $scope.$broadcast('markdown-update', responseData.data.markdown || responseData.data.html);
425 $('#name').val(responseData.data.name);
429 events.emit('success', 'Draft discarded, The editor has been updated with the current page content');
435 ngApp.controller('PageTagController', ['$scope', '$http', '$attrs',
436 function ($scope, $http, $attrs) {
438 const pageId = Number($attrs.pageId);
441 $scope.sortOptions = {
444 containment: "parent",
449 * Push an empty tag to the end of the scope tags.
451 function addEmptyTag() {
457 $scope.addEmptyTag = addEmptyTag;
460 * Get all tags for the current book and add into scope.
463 let url = window.baseUrl('/ajax/tags/get/page/' + pageId);
464 $http.get(url).then((responseData) => {
465 $scope.tags = responseData.data;
472 * Set the order property on all tags.
474 function setTagOrder() {
475 for (let i = 0; i < $scope.tags.length; i++) {
476 $scope.tags[i].order = i;
481 * When an tag changes check if another empty editable
482 * field needs to be added onto the end.
485 $scope.tagChange = function(tag) {
486 let cPos = $scope.tags.indexOf(tag);
487 if (cPos !== $scope.tags.length-1) return;
489 if (tag.name !== '' || tag.value !== '') {
495 * When an tag field loses focus check the tag to see if its
496 * empty and therefore could be removed from the list.
499 $scope.tagBlur = function(tag) {
500 let isLast = $scope.tags.length - 1 === $scope.tags.indexOf(tag);
501 if (tag.name === '' && tag.value === '' && !isLast) {
502 let cPos = $scope.tags.indexOf(tag);
503 $scope.tags.splice(cPos, 1);
508 * Save the tags to the current page.
510 $scope.saveTags = function() {
512 let postData = {tags: $scope.tags};
513 let url = window.baseUrl('/ajax/tags/update/page/' + pageId);
514 $http.post(url, postData).then((responseData) => {
515 $scope.tags = responseData.data.tags;
517 events.emit('success', responseData.data.message);
522 * Remove a tag from the current list.
525 $scope.removeTag = function(tag) {
526 let cIndex = $scope.tags.indexOf(tag);
527 $scope.tags.splice(cIndex, 1);