]> BookStack Code Mirror - bookstack/blob - resources/assets/js/controllers.js
Updated popup design and started integrating link selector
[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          * @param title
363          * @param html
364          */
365         function saveDraft() {
366             var data = {
367                 name: $('#name').val(),
368                 html: isMarkdown ? $sce.getTrustedHtml($scope.displayContent) : $scope.editContent
369             };
370
371             if (isMarkdown) data.markdown = $scope.editContent;
372
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;
378             });
379         }
380
381         $scope.forceDraftSave = function() {
382             saveDraft();
383         };
384
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();
390                 saveDraft();
391             }
392         });
393
394         /**
395          * Discard the current draft and grab the current page
396          * content from the system via an AJAX request.
397          */
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);
407                 $timeout(() => {
408                     startAutoSave();
409                 }, 1000);
410                 events.emit('success', 'Draft discarded, The editor has been updated with the current page content');
411             });
412         };
413
414     }]);
415
416     ngApp.controller('PageTagController', ['$scope', '$http', '$attrs',
417         function ($scope, $http, $attrs) {
418
419             const pageId = Number($attrs.pageId);
420             $scope.tags = [];
421             
422             $scope.sortOptions = {
423                 handle: '.handle',
424                 items: '> tr',
425                 containment: "parent",
426                 axis: "y"
427             };
428
429             /**
430              * Push an empty tag to the end of the scope tags.
431              */
432             function addEmptyTag() {
433                 $scope.tags.push({
434                     name: '',
435                     value: ''
436                 });
437             }
438             $scope.addEmptyTag = addEmptyTag;
439
440             /**
441              * Get all tags for the current book and add into scope.
442              */
443             function getTags() {
444                 let url = window.baseUrl('/ajax/tags/get/page/' + pageId);
445                 $http.get(url).then((responseData) => {
446                     $scope.tags = responseData.data;
447                     addEmptyTag();
448                 });
449             }
450             getTags();
451
452             /**
453              * Set the order property on all tags.
454              */
455             function setTagOrder() {
456                 for (let i = 0; i < $scope.tags.length; i++) {
457                     $scope.tags[i].order = i;
458                 }
459             }
460
461             /**
462              * When an tag changes check if another empty editable
463              * field needs to be added onto the end.
464              * @param tag
465              */
466             $scope.tagChange = function(tag) {
467                 let cPos = $scope.tags.indexOf(tag);
468                 if (cPos !== $scope.tags.length-1) return;
469
470                 if (tag.name !== '' || tag.value !== '') {
471                     addEmptyTag();
472                 }
473             };
474
475             /**
476              * When an tag field loses focus check the tag to see if its
477              * empty and therefore could be removed from the list.
478              * @param tag
479              */
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);
485                 }
486             };
487
488             /**
489              * Save the tags to the current page.
490              */
491             $scope.saveTags = function() {
492                 setTagOrder();
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;
497                     addEmptyTag();
498                     events.emit('success', responseData.data.message);
499                 })
500             };
501
502             /**
503              * Remove a tag from the current list.
504              * @param tag
505              */
506             $scope.removeTag = function(tag) {
507                 let cIndex = $scope.tags.indexOf(tag);
508                 $scope.tags.splice(cIndex, 1);
509             };
510
511         }]);
512
513 };
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530