]> BookStack Code Mirror - bookstack/blob - resources/assets/js/controllers.js
Fixed revision-based redirect on new pages
[bookstack] / resources / assets / js / controllers.js
1 "use strict";
2
3 var moment = require('moment');
4
5 module.exports = function (ngApp, events) {
6
7     ngApp.controller('ImageManagerController', ['$scope', '$attrs', '$http', '$timeout', 'imageManagerService',
8         function ($scope, $attrs, $http, $timeout, imageManagerService) {
9
10             $scope.images = [];
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;
19             $scope.view = 'all';
20             
21             $scope.searching = false;
22             $scope.searchTerm = '';
23
24             var page = 0;
25             var previousClickTime = 0;
26             var previousClickImage = 0;
27             var dataLoaded = false;
28             var callback = false;
29
30             var preSearchImages = [];
31             var preSearchHasMore = false;
32
33             /**
34              * Used by dropzone to get the endpoint to upload to.
35              * @returns {string}
36              */
37             $scope.getUploadUrl = function () {
38                 return '/images/' + $scope.imageType + '/upload';
39             };
40
41             /**
42              * Cancel the current search operation.
43              */
44             function cancelSearch() {
45                 $scope.searching = false;
46                 $scope.searchTerm = '';
47                 $scope.images = preSearchImages;
48                 $scope.hasMore = preSearchHasMore;
49             }
50             $scope.cancelSearch = cancelSearch;
51             
52
53             /**
54              * Runs on image upload, Adds an image to local list of images
55              * and shows a success message to the user.
56              * @param file
57              * @param data
58              */
59             $scope.uploadSuccess = function (file, data) {
60                 $scope.$apply(() => {
61                     $scope.images.unshift(data);
62                 });
63                 events.emit('success', 'Image uploaded');
64             };
65
66             /**
67              * Runs the callback and hides the image manager.
68              * @param returnData
69              */
70             function callbackAndHide(returnData) {
71                 if (callback) callback(returnData);
72                 $scope.showing = false;
73             }
74
75             /**
76              * Image select action. Checks if a double-click was fired.
77              * @param image
78              */
79             $scope.imageSelect = function (image) {
80                 var dblClickTime = 300;
81                 var currentTime = Date.now();
82                 var timeDiff = currentTime - previousClickTime;
83
84                 if (timeDiff < dblClickTime && image.id === previousClickImage) {
85                     // If double click
86                     callbackAndHide(image);
87                 } else {
88                     // If single
89                     $scope.selectedImage = image;
90                     $scope.dependantPages = false;
91                 }
92                 previousClickTime = currentTime;
93                 previousClickImage = image.id;
94             };
95
96             /**
97              * Action that runs when the 'Select image' button is clicked.
98              * Runs the callback and hides the image manager.
99              */
100             $scope.selectButtonClick = function () {
101                 callbackAndHide($scope.selectedImage);
102             };
103
104             /**
105              * Show the image manager.
106              * Takes a callback to execute later on.
107              * @param doneCallback
108              */
109             function show(doneCallback) {
110                 callback = doneCallback;
111                 $scope.showing = true;
112                 // Get initial images if they have not yet been loaded in.
113                 if (!dataLoaded) {
114                     fetchData();
115                     dataLoaded = true;
116                 }
117             }
118
119             // Connects up the image manger so it can be used externally
120             // such as from TinyMCE.
121             imageManagerService.show = show;
122             imageManagerService.showExternal = function (doneCallback) {
123                 $scope.$apply(() => {
124                     show(doneCallback);
125                 });
126             };
127             window.ImageManager = imageManagerService;
128
129             /**
130              * Hide the image manager
131              */
132             $scope.hide = function () {
133                 $scope.showing = false;
134             };
135
136             var baseUrl = '/images/' + $scope.imageType + '/all/'
137
138             /**
139              * Fetch the list image data from the server.
140              */
141             function fetchData() {
142                 var url = baseUrl + page + '?';
143                 var components = {};
144                 if ($scope.uploadedTo) components['page_id'] = $scope.uploadedTo;
145                 if ($scope.searching) components['term'] = $scope.searchTerm;
146
147
148                 var urlQueryString = Object.keys(components).map((key) => {
149                     return key + '=' + encodeURIComponent(components[key]);
150                 }).join('&');
151                 url += urlQueryString;
152
153                 $http.get(url).then((response) => {
154                     $scope.images = $scope.images.concat(response.data.images);
155                     $scope.hasMore = response.data.hasMore;
156                     page++;
157                 });
158             }
159             $scope.fetchData = fetchData;
160
161             /**
162              * Start a search operation
163              * @param searchTerm
164              */
165             $scope.searchImages = function() {
166
167                 if ($scope.searchTerm === '') {
168                     cancelSearch();
169                     return;
170                 }
171
172                 if (!$scope.searching) {
173                     preSearchImages = $scope.images;
174                     preSearchHasMore = $scope.hasMore;
175                 }
176
177                 $scope.searching = true;
178                 $scope.images = [];
179                 $scope.hasMore = false;
180                 page = 0;
181                 baseUrl = '/images/' + $scope.imageType + '/search/';
182                 fetchData();
183             };
184
185             /**
186              * Set the current image listing view.
187              * @param viewName
188              */
189             $scope.setView = function(viewName) {
190                 cancelSearch();
191                 $scope.images = [];
192                 $scope.hasMore = false;
193                 page = 0;
194                 $scope.view = viewName;
195                 baseUrl = '/images/' + $scope.imageType  + '/' + viewName + '/';
196                 fetchData();
197             }
198
199             /**
200              * Save the details of an image.
201              * @param event
202              */
203             $scope.saveImageDetails = function (event) {
204                 event.preventDefault();
205                 var url = '/images/update/' + $scope.selectedImage.id;
206                 $http.put(url, this.selectedImage).then((response) => {
207                     events.emit('success', 'Image details updated');
208                 }, (response) => {
209                     if (response.status === 422) {
210                         var errors = response.data;
211                         var message = '';
212                         Object.keys(errors).forEach((key) => {
213                             message += errors[key].join('\n');
214                         });
215                         events.emit('error', message);
216                     } else if (response.status === 403) {
217                         events.emit('error', response.data.error);
218                     }
219                 });
220             };
221
222             /**
223              * Delete an image from system and notify of success.
224              * Checks if it should force delete when an image
225              * has dependant pages.
226              * @param event
227              */
228             $scope.deleteImage = function (event) {
229                 event.preventDefault();
230                 var force = $scope.dependantPages !== false;
231                 var url = '/images/' + $scope.selectedImage.id;
232                 if (force) url += '?force=true';
233                 $http.delete(url).then((response) => {
234                     $scope.images.splice($scope.images.indexOf($scope.selectedImage), 1);
235                     $scope.selectedImage = false;
236                     events.emit('success', 'Image successfully deleted');
237                 }, (response) => {
238                     // Pages failure
239                     if (response.status === 400) {
240                         $scope.dependantPages = response.data;
241                     } else if (response.status === 403) {
242                         events.emit('error', response.data.error);
243                     }
244                 });
245             };
246
247             /**
248              * Simple date creator used to properly format dates.
249              * @param stringDate
250              * @returns {Date}
251              */
252             $scope.getDate = function (stringDate) {
253                 return new Date(stringDate);
254             };
255
256         }]);
257
258
259     ngApp.controller('BookShowController', ['$scope', '$http', '$attrs', '$sce', function ($scope, $http, $attrs, $sce) {
260         $scope.searching = false;
261         $scope.searchTerm = '';
262         $scope.searchResults = '';
263
264         $scope.searchBook = function (e) {
265             e.preventDefault();
266             var term = $scope.searchTerm;
267             if (term.length == 0) return;
268             $scope.searching = true;
269             $scope.searchResults = '';
270             var searchUrl = '/search/book/' + $attrs.bookId;
271             searchUrl += '?term=' + encodeURIComponent(term);
272             $http.get(searchUrl).then((response) => {
273                 $scope.searchResults = $sce.trustAsHtml(response.data);
274             });
275         };
276
277         $scope.checkSearchForm = function () {
278             if ($scope.searchTerm.length < 1) {
279                 $scope.searching = false;
280             }
281         };
282
283         $scope.clearSearch = function () {
284             $scope.searching = false;
285             $scope.searchTerm = '';
286         };
287
288     }]);
289
290
291     ngApp.controller('PageEditController', ['$scope', '$http', '$attrs', '$interval', '$timeout', '$sce',
292         function ($scope, $http, $attrs, $interval, $timeout, $sce) {
293
294         $scope.editorOptions = require('./pages/page-form');
295         $scope.editContent = '';
296         $scope.draftText = '';
297         var pageId = Number($attrs.pageId);
298         var isEdit = pageId !== 0;
299         var autosaveFrequency = 30; // AutoSave interval in seconds.
300         var isMarkdown = $attrs.editorType === 'markdown';
301         $scope.isUpdateDraft = Number($attrs.pageUpdateDraft) === 1;
302         $scope.isNewPageDraft = Number($attrs.pageNewDraft) === 1;
303
304         // Set inital header draft text
305         if ($scope.isUpdateDraft || $scope.isNewPageDraft) {
306             $scope.draftText = 'Editing Draft'
307         } else {
308             $scope.draftText = 'Editing Page'
309         };
310
311         var autoSave = false;
312
313         var currentContent = {
314             title: false,
315             html: false
316         };
317
318         if (isEdit) {
319             setTimeout(() => {
320                 startAutoSave();
321             }, 1000);
322         }
323
324         // Actions specifically for the markdown editor
325         if (isMarkdown) {
326             $scope.displayContent = '';
327             // Editor change event
328             $scope.editorChange = function (content) {
329                 $scope.displayContent = $sce.trustAsHtml(content);
330             }
331         }
332
333         if (!isMarkdown) {
334             $scope.editorChange = function() {};
335         }
336
337         /**
338          * Start the AutoSave loop, Checks for content change
339          * before performing the costly AJAX request.
340          */
341         function startAutoSave() {
342             currentContent.title = $('#name').val();
343             currentContent.html = $scope.editContent;
344
345             autoSave = $interval(() => {
346                 var newTitle = $('#name').val();
347                 var newHtml = $scope.editContent;
348
349                 if (newTitle !== currentContent.title || newHtml !== currentContent.html) {
350                     currentContent.html = newHtml;
351                     currentContent.title = newTitle;
352                     saveDraft();
353                 }
354
355             }, 1000 * autosaveFrequency);
356         }
357
358         /**
359          * Save a draft update into the system via an AJAX request.
360          * @param title
361          * @param html
362          */
363         function saveDraft() {
364             var data = {
365                 name: $('#name').val(),
366                 html: isMarkdown ? $sce.getTrustedHtml($scope.displayContent) : $scope.editContent
367             };
368
369             if (isMarkdown) data.markdown = $scope.editContent;
370
371             $http.put('/ajax/page/' + pageId + '/save-draft', data).then((responseData) => {
372                 var updateTime = moment.utc(moment.unix(responseData.data.timestamp)).toDate();
373                 $scope.draftText = responseData.data.message + moment(updateTime).format('HH:mm');
374                 if (!$scope.isNewPageDraft) $scope.isUpdateDraft = true;
375             });
376         }
377
378         $scope.forceDraftSave = function() {
379             saveDraft();
380         };
381
382         // Listen to shortcuts coming via events
383         $scope.$on('editor-keydown', (event, data) => {
384             // Save shortcut (ctrl+s)
385             if (data.keyCode == 83 && (navigator.platform.match("Mac") ? data.metaKey : data.ctrlKey)) {
386                 data.preventDefault();
387                 saveDraft();
388             }
389         });
390
391         /**
392          * Discard the current draft and grab the current page
393          * content from the system via an AJAX request.
394          */
395         $scope.discardDraft = function () {
396             $http.get('/ajax/page/' + pageId).then((responseData) => {
397                 if (autoSave) $interval.cancel(autoSave);
398                 $scope.draftText = 'Editing Page';
399                 $scope.isUpdateDraft = false;
400                 $scope.$broadcast('html-update', responseData.data.html);
401                 $scope.$broadcast('markdown-update', responseData.data.markdown || responseData.data.html);
402                 $('#name').val(responseData.data.name);
403                 $timeout(() => {
404                     startAutoSave();
405                 }, 1000);
406                 events.emit('success', 'Draft discarded, The editor has been updated with the current page content');
407             });
408         };
409
410     }]);
411
412     ngApp.controller('PageTagController', ['$scope', '$http', '$attrs',
413         function ($scope, $http, $attrs) {
414
415             const pageId = Number($attrs.pageId);
416             $scope.tags = [];
417             
418             $scope.sortOptions = {
419                 handle: '.handle',
420                 items: '> tr',
421                 containment: "parent",
422                 axis: "y"
423             };
424
425             /**
426              * Push an empty tag to the end of the scope tags.
427              */
428             function addEmptyTag() {
429                 $scope.tags.push({
430                     name: '',
431                     value: ''
432                 });
433             }
434             $scope.addEmptyTag = addEmptyTag;
435
436             /**
437              * Get all tags for the current book and add into scope.
438              */
439             function getTags() {
440                 $http.get('/ajax/tags/get/page/' + pageId).then((responseData) => {
441                     $scope.tags = responseData.data;
442                     addEmptyTag();
443                 });
444             }
445             getTags();
446
447             /**
448              * Set the order property on all tags.
449              */
450             function setTagOrder() {
451                 for (let i = 0; i < $scope.tags.length; i++) {
452                     $scope.tags[i].order = i;
453                 }
454             }
455
456             /**
457              * When an tag changes check if another empty editable
458              * field needs to be added onto the end.
459              * @param tag
460              */
461             $scope.tagChange = function(tag) {
462                 let cPos = $scope.tags.indexOf(tag);
463                 if (cPos !== $scope.tags.length-1) return;
464
465                 if (tag.name !== '' || tag.value !== '') {
466                     addEmptyTag();
467                 }
468             };
469
470             /**
471              * When an tag field loses focus check the tag to see if its
472              * empty and therefore could be removed from the list.
473              * @param tag
474              */
475             $scope.tagBlur = function(tag) {
476                 let isLast = $scope.tags.length - 1 === $scope.tags.indexOf(tag);
477                 if (tag.name === '' && tag.value === '' && !isLast) {
478                     let cPos = $scope.tags.indexOf(tag);
479                     $scope.tags.splice(cPos, 1);
480                 }
481             };
482
483             /**
484              * Save the tags to the current page.
485              */
486             $scope.saveTags = function() {
487                 setTagOrder();
488                 let postData = {tags: $scope.tags};
489                 $http.post('/ajax/tags/update/page/' + pageId, postData).then((responseData) => {
490                     $scope.tags = responseData.data.tags;
491                     addEmptyTag();
492                     events.emit('success', responseData.data.message);
493                 })
494             };
495
496             /**
497              * Remove a tag from the current list.
498              * @param tag
499              */
500             $scope.removeTag = function(tag) {
501                 let cIndex = $scope.tags.indexOf(tag);
502                 $scope.tags.splice(cIndex, 1);
503             };
504
505         }]);
506
507 };
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524