]> BookStack Code Mirror - bookstack/blob - resources/assets/js/controllers.js
Merge branch 'master' into release
[bookstack] / resources / assets / js / controllers.js
1 "use strict";
2
3 const 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 window.baseUrl('/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.hide();
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                 $('#image-manager').find('.overlay').css('display', 'flex').hide().fadeIn(240);
113                 // Get initial images if they have not yet been loaded in.
114                 if (!dataLoaded) {
115                     fetchData();
116                     dataLoaded = true;
117                 }
118             }
119
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(() => {
125                     show(doneCallback);
126                 });
127             };
128             window.ImageManager = imageManagerService;
129
130             /**
131              * Hide the image manager
132              */
133             $scope.hide = function () {
134                 $scope.showing = false;
135                 $('#image-manager').find('.overlay').fadeOut(240);
136             };
137
138             var baseUrl = window.baseUrl('/images/' + $scope.imageType + '/all/');
139
140             /**
141              * Fetch the list image data from the server.
142              */
143             function fetchData() {
144                 var url = baseUrl + page + '?';
145                 var components = {};
146                 if ($scope.uploadedTo) components['page_id'] = $scope.uploadedTo;
147                 if ($scope.searching) components['term'] = $scope.searchTerm;
148
149
150                 var urlQueryString = Object.keys(components).map((key) => {
151                     return key + '=' + encodeURIComponent(components[key]);
152                 }).join('&');
153                 url += urlQueryString;
154
155                 $http.get(url).then((response) => {
156                     $scope.images = $scope.images.concat(response.data.images);
157                     $scope.hasMore = response.data.hasMore;
158                     page++;
159                 });
160             }
161             $scope.fetchData = fetchData;
162
163             /**
164              * Start a search operation
165              * @param searchTerm
166              */
167             $scope.searchImages = function() {
168
169                 if ($scope.searchTerm === '') {
170                     cancelSearch();
171                     return;
172                 }
173
174                 if (!$scope.searching) {
175                     preSearchImages = $scope.images;
176                     preSearchHasMore = $scope.hasMore;
177                 }
178
179                 $scope.searching = true;
180                 $scope.images = [];
181                 $scope.hasMore = false;
182                 page = 0;
183                 baseUrl = window.baseUrl('/images/' + $scope.imageType + '/search/');
184                 fetchData();
185             };
186
187             /**
188              * Set the current image listing view.
189              * @param viewName
190              */
191             $scope.setView = function(viewName) {
192                 cancelSearch();
193                 $scope.images = [];
194                 $scope.hasMore = false;
195                 page = 0;
196                 $scope.view = viewName;
197                 baseUrl = window.baseUrl('/images/' + $scope.imageType  + '/' + viewName + '/');
198                 fetchData();
199             }
200
201             /**
202              * Save the details of an image.
203              * @param event
204              */
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');
210                 }, (response) => {
211                     if (response.status === 422) {
212                         var errors = response.data;
213                         var message = '';
214                         Object.keys(errors).forEach((key) => {
215                             message += errors[key].join('\n');
216                         });
217                         events.emit('error', message);
218                     } else if (response.status === 403) {
219                         events.emit('error', response.data.error);
220                     }
221                 });
222             };
223
224             /**
225              * Delete an image from system and notify of success.
226              * Checks if it should force delete when an image
227              * has dependant pages.
228              * @param event
229              */
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');
239                 }, (response) => {
240                     // Pages failure
241                     if (response.status === 400) {
242                         $scope.dependantPages = response.data;
243                     } else if (response.status === 403) {
244                         events.emit('error', response.data.error);
245                     }
246                 });
247             };
248
249             /**
250              * Simple date creator used to properly format dates.
251              * @param stringDate
252              * @returns {Date}
253              */
254             $scope.getDate = function (stringDate) {
255                 return new Date(stringDate);
256             };
257
258         }]);
259
260
261     ngApp.controller('BookShowController', ['$scope', '$http', '$attrs', '$sce', function ($scope, $http, $attrs, $sce) {
262         $scope.searching = false;
263         $scope.searchTerm = '';
264         $scope.searchResults = '';
265
266         $scope.searchBook = function (e) {
267             e.preventDefault();
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);
276             });
277         };
278
279         $scope.checkSearchForm = function () {
280             if ($scope.searchTerm.length < 1) {
281                 $scope.searching = false;
282             }
283         };
284
285         $scope.clearSearch = function () {
286             $scope.searching = false;
287             $scope.searchTerm = '';
288         };
289
290     }]);
291
292
293     ngApp.controller('PageEditController', ['$scope', '$http', '$attrs', '$interval', '$timeout', '$sce',
294         function ($scope, $http, $attrs, $interval, $timeout, $sce) {
295
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;
305
306         // Set inital header draft text
307         if ($scope.isUpdateDraft || $scope.isNewPageDraft) {
308             $scope.draftText = 'Editing Draft'
309         } else {
310             $scope.draftText = 'Editing Page'
311         };
312
313         var autoSave = false;
314
315         var currentContent = {
316             title: false,
317             html: false
318         };
319
320         if (isEdit) {
321             setTimeout(() => {
322                 startAutoSave();
323             }, 1000);
324         }
325
326         // Actions specifically for the markdown editor
327         if (isMarkdown) {
328             $scope.displayContent = '';
329             // Editor change event
330             $scope.editorChange = function (content) {
331                 $scope.displayContent = $sce.trustAsHtml(content);
332             }
333         }
334
335         if (!isMarkdown) {
336             $scope.editorChange = function() {};
337         }
338
339         /**
340          * Start the AutoSave loop, Checks for content change
341          * before performing the costly AJAX request.
342          */
343         function startAutoSave() {
344             currentContent.title = $('#name').val();
345             currentContent.html = $scope.editContent;
346
347             autoSave = $interval(() => {
348                 var newTitle = $('#name').val();
349                 var newHtml = $scope.editContent;
350
351                 if (newTitle !== currentContent.title || newHtml !== currentContent.html) {
352                     currentContent.html = newHtml;
353                     currentContent.title = newTitle;
354                     saveDraft();
355                 }
356
357             }, 1000 * autosaveFrequency);
358         }
359
360         /**
361          * Save a draft update into the system via an AJAX request.
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             let url = window.baseUrl('/ajax/page/' + pageId + '/save-draft');
372             $http.put(url, data).then((responseData) => {
373                 var updateTime = moment.utc(moment.unix(responseData.data.timestamp)).toDate();
374                 $scope.draftText = responseData.data.message + moment(updateTime).format('HH:mm');
375                 if (!$scope.isNewPageDraft) $scope.isUpdateDraft = true;
376                 showDraftSaveNotification();
377             });
378         }
379
380         function showDraftSaveNotification() {
381             $scope.draftUpdated = true;
382             $timeout(() => {
383                 $scope.draftUpdated = false;
384             }, 2000)
385         }
386
387         $scope.forceDraftSave = function() {
388             saveDraft();
389         };
390
391         // Listen to shortcuts coming via events
392         $scope.$on('editor-keydown', (event, data) => {
393             // Save shortcut (ctrl+s)
394             if (data.keyCode == 83 && (navigator.platform.match("Mac") ? data.metaKey : data.ctrlKey)) {
395                 data.preventDefault();
396                 saveDraft();
397             }
398         });
399
400         /**
401          * Discard the current draft and grab the current page
402          * content from the system via an AJAX request.
403          */
404         $scope.discardDraft = function () {
405             let url = window.baseUrl('/ajax/page/' + pageId);
406             $http.get(url).then((responseData) => {
407                 if (autoSave) $interval.cancel(autoSave);
408                 $scope.draftText = 'Editing Page';
409                 $scope.isUpdateDraft = false;
410                 $scope.$broadcast('html-update', responseData.data.html);
411                 $scope.$broadcast('markdown-update', responseData.data.markdown || responseData.data.html);
412                 $('#name').val(responseData.data.name);
413                 $timeout(() => {
414                     startAutoSave();
415                 }, 1000);
416                 events.emit('success', 'Draft discarded, The editor has been updated with the current page content');
417             });
418         };
419
420     }]);
421
422     ngApp.controller('PageTagController', ['$scope', '$http', '$attrs',
423         function ($scope, $http, $attrs) {
424
425             const pageId = Number($attrs.pageId);
426             $scope.tags = [];
427             
428             $scope.sortOptions = {
429                 handle: '.handle',
430                 items: '> tr',
431                 containment: "parent",
432                 axis: "y"
433             };
434
435             /**
436              * Push an empty tag to the end of the scope tags.
437              */
438             function addEmptyTag() {
439                 $scope.tags.push({
440                     name: '',
441                     value: ''
442                 });
443             }
444             $scope.addEmptyTag = addEmptyTag;
445
446             /**
447              * Get all tags for the current book and add into scope.
448              */
449             function getTags() {
450                 let url = window.baseUrl('/ajax/tags/get/page/' + pageId);
451                 $http.get(url).then((responseData) => {
452                     $scope.tags = responseData.data;
453                     addEmptyTag();
454                 });
455             }
456             getTags();
457
458             /**
459              * Set the order property on all tags.
460              */
461             function setTagOrder() {
462                 for (let i = 0; i < $scope.tags.length; i++) {
463                     $scope.tags[i].order = i;
464                 }
465             }
466
467             /**
468              * When an tag changes check if another empty editable
469              * field needs to be added onto the end.
470              * @param tag
471              */
472             $scope.tagChange = function(tag) {
473                 let cPos = $scope.tags.indexOf(tag);
474                 if (cPos !== $scope.tags.length-1) return;
475
476                 if (tag.name !== '' || tag.value !== '') {
477                     addEmptyTag();
478                 }
479             };
480
481             /**
482              * When an tag field loses focus check the tag to see if its
483              * empty and therefore could be removed from the list.
484              * @param tag
485              */
486             $scope.tagBlur = function(tag) {
487                 let isLast = $scope.tags.length - 1 === $scope.tags.indexOf(tag);
488                 if (tag.name === '' && tag.value === '' && !isLast) {
489                     let cPos = $scope.tags.indexOf(tag);
490                     $scope.tags.splice(cPos, 1);
491                 }
492             };
493
494             /**
495              * Save the tags to the current page.
496              */
497             $scope.saveTags = function() {
498                 setTagOrder();
499                 let postData = {tags: $scope.tags};
500                 let url = window.baseUrl('/ajax/tags/update/page/' + pageId);
501                 $http.post(url, postData).then((responseData) => {
502                     $scope.tags = responseData.data.tags;
503                     addEmptyTag();
504                     events.emit('success', responseData.data.message);
505                 })
506             };
507
508             /**
509              * Remove a tag from the current list.
510              * @param tag
511              */
512             $scope.removeTag = function(tag) {
513                 let cIndex = $scope.tags.indexOf(tag);
514                 $scope.tags.splice(cIndex, 1);
515             };
516
517         }]);
518
519 };
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536