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.isUpdateDraft = Number($attrs.pageUpdateDraft) === 1;
304 $scope.isNewPageDraft = Number($attrs.pageNewDraft) === 1;
306 // Set inital header draft text
307 if ($scope.isUpdateDraft || $scope.isNewPageDraft) {
308 $scope.draftText = 'Editing Draft'
310 $scope.draftText = 'Editing Page'
313 var autoSave = false;
315 var currentContent = {
326 // Actions specifically for the markdown editor
328 $scope.displayContent = '';
329 // Editor change event
330 $scope.editorChange = function (content) {
331 $scope.displayContent = $sce.trustAsHtml(content);
336 $scope.editorChange = function() {};
340 * Start the AutoSave loop, Checks for content change
341 * before performing the costly AJAX request.
343 function startAutoSave() {
344 currentContent.title = $('#name').val();
345 currentContent.html = $scope.editContent;
347 autoSave = $interval(() => {
348 var newTitle = $('#name').val();
349 var newHtml = $scope.editContent;
351 if (newTitle !== currentContent.title || newHtml !== currentContent.html) {
352 currentContent.html = newHtml;
353 currentContent.title = newTitle;
357 }, 1000 * autosaveFrequency);
361 * Save a draft update into the system via an AJAX request.
365 function saveDraft() {
367 name: $('#name').val(),
368 html: isMarkdown ? $sce.getTrustedHtml($scope.displayContent) : $scope.editContent
371 if (isMarkdown) data.markdown = $scope.editContent;
373 let url = window.baseUrl('/ajax/page/' + pageId + '/save-draft');
374 $http.put(url, data).then((responseData) => {
375 var updateTime = moment.utc(moment.unix(responseData.data.timestamp)).toDate();
376 $scope.draftText = responseData.data.message + moment(updateTime).format('HH:mm');
377 if (!$scope.isNewPageDraft) $scope.isUpdateDraft = true;
381 $scope.forceDraftSave = function() {
385 // Listen to shortcuts coming via events
386 $scope.$on('editor-keydown', (event, data) => {
387 // Save shortcut (ctrl+s)
388 if (data.keyCode == 83 && (navigator.platform.match("Mac") ? data.metaKey : data.ctrlKey)) {
389 data.preventDefault();
395 * Discard the current draft and grab the current page
396 * content from the system via an AJAX request.
398 $scope.discardDraft = function () {
399 let url = window.baseUrl('/ajax/page/' + pageId);
400 $http.get(url).then((responseData) => {
401 if (autoSave) $interval.cancel(autoSave);
402 $scope.draftText = 'Editing Page';
403 $scope.isUpdateDraft = false;
404 $scope.$broadcast('html-update', responseData.data.html);
405 $scope.$broadcast('markdown-update', responseData.data.markdown || responseData.data.html);
406 $('#name').val(responseData.data.name);
410 events.emit('success', 'Draft discarded, The editor has been updated with the current page content');
416 ngApp.controller('PageTagController', ['$scope', '$http', '$attrs',
417 function ($scope, $http, $attrs) {
419 const pageId = Number($attrs.pageId);
422 $scope.sortOptions = {
425 containment: "parent",
430 * Push an empty tag to the end of the scope tags.
432 function addEmptyTag() {
438 $scope.addEmptyTag = addEmptyTag;
441 * Get all tags for the current book and add into scope.
444 let url = window.baseUrl('/ajax/tags/get/page/' + pageId);
445 $http.get(url).then((responseData) => {
446 $scope.tags = responseData.data;
453 * Set the order property on all tags.
455 function setTagOrder() {
456 for (let i = 0; i < $scope.tags.length; i++) {
457 $scope.tags[i].order = i;
462 * When an tag changes check if another empty editable
463 * field needs to be added onto the end.
466 $scope.tagChange = function(tag) {
467 let cPos = $scope.tags.indexOf(tag);
468 if (cPos !== $scope.tags.length-1) return;
470 if (tag.name !== '' || tag.value !== '') {
476 * When an tag field loses focus check the tag to see if its
477 * empty and therefore could be removed from the list.
480 $scope.tagBlur = function(tag) {
481 let isLast = $scope.tags.length - 1 === $scope.tags.indexOf(tag);
482 if (tag.name === '' && tag.value === '' && !isLast) {
483 let cPos = $scope.tags.indexOf(tag);
484 $scope.tags.splice(cPos, 1);
489 * Save the tags to the current page.
491 $scope.saveTags = function() {
493 let postData = {tags: $scope.tags};
494 let url = window.baseUrl('/ajax/tags/update/page/' + pageId);
495 $http.post(url, postData).then((responseData) => {
496 $scope.tags = responseData.data.tags;
498 events.emit('success', responseData.data.message);
503 * Remove a tag from the current list.
506 $scope.removeTag = function(tag) {
507 let cIndex = $scope.tags.indexOf(tag);
508 $scope.tags.splice(cIndex, 1);