]> BookStack Code Mirror - bookstack/blob - resources/assets/js/controllers.js
Added new page drafts and started image entity attaching
[bookstack] / resources / assets / js / controllers.js
1 "use strict";
2
3 module.exports = function (ngApp, events) {
4
5     ngApp.controller('ImageManagerController', ['$scope', '$attrs', '$http', '$timeout', 'imageManagerService',
6         function ($scope, $attrs, $http, $timeout, imageManagerService) {
7
8             $scope.images = [];
9             $scope.imageType = $attrs.imageType;
10             $scope.selectedImage = false;
11             $scope.dependantPages = false;
12             $scope.showing = false;
13             $scope.hasMore = false;
14             $scope.imageUpdateSuccess = false;
15             $scope.imageDeleteSuccess = false;
16
17             var page = 0;
18             var previousClickTime = 0;
19             var dataLoaded = false;
20             var callback = false;
21
22             /**
23              * Simple returns the appropriate upload url depending on the image type set.
24              * @returns {string}
25              */
26             $scope.getUploadUrl = function () {
27                 return '/images/' + $scope.imageType + '/upload';
28             };
29
30             /**
31              * Runs on image upload, Adds an image to local list of images
32              * and shows a success message to the user.
33              * @param file
34              * @param data
35              */
36             $scope.uploadSuccess = function (file, data) {
37                 $scope.$apply(() => {
38                     $scope.images.unshift(data);
39                 });
40                 events.emit('success', 'Image uploaded');
41             };
42
43             /**
44              * Runs the callback and hides the image manager.
45              * @param returnData
46              */
47             function callbackAndHide(returnData) {
48                 if (callback) callback(returnData);
49                 $scope.showing = false;
50             }
51
52             /**
53              * Image select action. Checks if a double-click was fired.
54              * @param image
55              */
56             $scope.imageSelect = function (image) {
57                 var dblClickTime = 300;
58                 var currentTime = Date.now();
59                 var timeDiff = currentTime - previousClickTime;
60
61                 if (timeDiff < dblClickTime) {
62                     // If double click
63                     callbackAndHide(image);
64                 } else {
65                     // If single
66                     $scope.selectedImage = image;
67                     $scope.dependantPages = false;
68                 }
69                 previousClickTime = currentTime;
70             };
71
72             /**
73              * Action that runs when the 'Select image' button is clicked.
74              * Runs the callback and hides the image manager.
75              */
76             $scope.selectButtonClick = function () {
77                 callbackAndHide($scope.selectedImage);
78             };
79
80             /**
81              * Show the image manager.
82              * Takes a callback to execute later on.
83              * @param doneCallback
84              */
85             function show(doneCallback) {
86                 callback = doneCallback;
87                 $scope.showing = true;
88                 // Get initial images if they have not yet been loaded in.
89                 if (!dataLoaded) {
90                     fetchData();
91                     dataLoaded = true;
92                 }
93             }
94
95             // Connects up the image manger so it can be used externally
96             // such as from TinyMCE.
97             imageManagerService.show = show;
98             imageManagerService.showExternal = function (doneCallback) {
99                 $scope.$apply(() => {
100                     show(doneCallback);
101                 });
102             };
103             window.ImageManager = imageManagerService;
104
105             /**
106              * Hide the image manager
107              */
108             $scope.hide = function () {
109                 $scope.showing = false;
110             };
111
112             /**
113              * Fetch the list image data from the server.
114              */
115             function fetchData() {
116                 var url = '/images/' + $scope.imageType + '/all/' + page;
117                 $http.get(url).then((response) => {
118                     $scope.images = $scope.images.concat(response.data.images);
119                     $scope.hasMore = response.data.hasMore;
120                     page++;
121                 });
122             }
123
124             $scope.fetchData = fetchData;
125
126             /**
127              * Save the details of an image.
128              * @param event
129              */
130             $scope.saveImageDetails = function (event) {
131                 event.preventDefault();
132                 var url = '/images/update/' + $scope.selectedImage.id;
133                 $http.put(url, this.selectedImage).then((response) => {
134                     events.emit('success', 'Image details updated');
135                 }, (response) => {
136                     if (response.status === 422) {
137                         var errors = response.data;
138                         var message = '';
139                         Object.keys(errors).forEach((key) => {
140                             message += errors[key].join('\n');
141                         });
142                         events.emit('error', message);
143                     } else if (response.status === 403) {
144                         events.emit('error', response.data.error);
145                     }
146                 });
147             };
148
149             /**
150              * Delete an image from system and notify of success.
151              * Checks if it should force delete when an image
152              * has dependant pages.
153              * @param event
154              */
155             $scope.deleteImage = function (event) {
156                 event.preventDefault();
157                 var force = $scope.dependantPages !== false;
158                 var url = '/images/' + $scope.selectedImage.id;
159                 if (force) url += '?force=true';
160                 $http.delete(url).then((response) => {
161                     $scope.images.splice($scope.images.indexOf($scope.selectedImage), 1);
162                     $scope.selectedImage = false;
163                     events.emit('success', 'Image successfully deleted');
164                 }, (response) => {
165                     // Pages failure
166                     if (response.status === 400) {
167                         $scope.dependantPages = response.data;
168                     } else if (response.status === 403) {
169                         events.emit('error', response.data.error);
170                     }
171                 });
172             };
173
174             /**
175              * Simple date creator used to properly format dates.
176              * @param stringDate
177              * @returns {Date}
178              */
179             $scope.getDate = function (stringDate) {
180                 return new Date(stringDate);
181             };
182
183         }]);
184
185
186     ngApp.controller('BookShowController', ['$scope', '$http', '$attrs', '$sce', function ($scope, $http, $attrs, $sce) {
187         $scope.searching = false;
188         $scope.searchTerm = '';
189         $scope.searchResults = '';
190
191         $scope.searchBook = function (e) {
192             e.preventDefault();
193             var term = $scope.searchTerm;
194             if (term.length == 0) return;
195             $scope.searching = true;
196             $scope.searchResults = '';
197             var searchUrl = '/search/book/' + $attrs.bookId;
198             searchUrl += '?term=' + encodeURIComponent(term);
199             $http.get(searchUrl).then((response) => {
200                 $scope.searchResults = $sce.trustAsHtml(response.data);
201             });
202         };
203
204         $scope.checkSearchForm = function () {
205             if ($scope.searchTerm.length < 1) {
206                 $scope.searching = false;
207             }
208         };
209
210         $scope.clearSearch = function () {
211             $scope.searching = false;
212             $scope.searchTerm = '';
213         };
214
215     }]);
216
217
218     ngApp.controller('PageEditController', ['$scope', '$http', '$attrs', '$interval', '$timeout', function ($scope, $http, $attrs, $interval, $timeout) {
219
220         $scope.editorOptions = require('./pages/page-form');
221         $scope.editorHtml = '';
222         $scope.draftText = '';
223         var pageId = Number($attrs.pageId);
224         var isEdit = pageId !== 0;
225         var autosaveFrequency = 30; // AutoSave interval in seconds.
226         $scope.isUpdateDraft = Number($attrs.pageUpdateDraft) === 1;
227         $scope.isNewPageDraft = Number($attrs.pageNewDraft) === 1;
228         if ($scope.isUpdateDraft || $scope.isNewPageDraft) {
229             $scope.draftText = 'Editing Draft'
230         } else {
231             $scope.draftText = 'Editing Page'
232         };
233
234         var autoSave = false;
235
236         var currentContent = {
237             title: false,
238             html: false
239         };
240
241         if (isEdit) {
242             setTimeout(() => {
243                 startAutoSave();
244             }, 1000);
245         }
246
247         $scope.editorChange = function () {}
248
249         /**
250          * Start the AutoSave loop, Checks for content change
251          * before performing the costly AJAX request.
252          */
253         function startAutoSave() {
254             currentContent.title = $('#name').val();
255             currentContent.html = $scope.editorHtml;
256
257             autoSave = $interval(() => {
258                 var newTitle = $('#name').val();
259                 var newHtml = $scope.editorHtml;
260
261                 if (newTitle !== currentContent.title || newHtml !== currentContent.html) {
262                     currentContent.html = newHtml;
263                     currentContent.title = newTitle;
264                     saveDraft(newTitle, newHtml);
265                 }
266             }, 1000 * autosaveFrequency);
267         }
268
269         /**
270          * Save a draft update into the system via an AJAX request.
271          * @param title
272          * @param html
273          */
274         function saveDraft(title, html) {
275             $http.put('/ajax/page/' + pageId + '/save-draft', {
276                 name: title,
277                 html: html
278             }).then((responseData) => {
279                 $scope.draftText = responseData.data.message;
280                 if (!$scope.isNewPageDraft) $scope.isUpdateDraft = true;
281             });
282         }
283
284         $scope.forceDraftSave = function() {
285             var newTitle = $('#name').val();
286             var newHtml = $scope.editorHtml;
287             saveDraft(newTitle, newHtml);
288         };
289
290         /**
291          * Discard the current draft and grab the current page
292          * content from the system via an AJAX request.
293          */
294         $scope.discardDraft = function () {
295             $http.get('/ajax/page/' + pageId).then((responseData) => {
296                 if (autoSave) $interval.cancel(autoSave);
297                 $scope.draftText = 'Editing Page';
298                 $scope.isUpdateDraft = false;
299                 $scope.$broadcast('html-update', responseData.data.html);
300                 $('#name').val(responseData.data.name);
301                 $timeout(() => {
302                     startAutoSave();
303                 }, 1000);
304                 events.emit('success', 'Draft discarded, The editor has been updated with the current page content');
305             });
306         };
307
308     }]);
309
310 };