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