]> BookStack Code Mirror - bookstack/blob - resources/assets/js/controllers.js
Standardised JS vars and imports/exports
[bookstack] / resources / assets / js / controllers.js
1 "use strict";
2
3 import moment from 'moment';
4 import 'moment/locale/en-gb';
5 import editorOptions from "./pages/page-form";
6
7 moment.locale('en-gb');
8
9 export default function (ngApp, events) {
10
11     ngApp.controller('ImageManagerController', ['$scope', '$attrs', '$http', '$timeout', 'imageManagerService',
12         function ($scope, $attrs, $http, $timeout, imageManagerService) {
13
14             $scope.images = [];
15             $scope.imageType = $attrs.imageType;
16             $scope.selectedImage = false;
17             $scope.dependantPages = false;
18             $scope.showing = false;
19             $scope.hasMore = false;
20             $scope.imageUpdateSuccess = false;
21             $scope.imageDeleteSuccess = false;
22             $scope.uploadedTo = $attrs.uploadedTo;
23             $scope.view = 'all';
24
25             $scope.searching = false;
26             $scope.searchTerm = '';
27
28             let page = 0;
29             let previousClickTime = 0;
30             let previousClickImage = 0;
31             let dataLoaded = false;
32             let callback = false;
33
34             let preSearchImages = [];
35             let preSearchHasMore = false;
36
37             /**
38              * Used by dropzone to get the endpoint to upload to.
39              * @returns {string}
40              */
41             $scope.getUploadUrl = function () {
42                 return window.baseUrl('/images/' + $scope.imageType + '/upload');
43             };
44
45             /**
46              * Cancel the current search operation.
47              */
48             function cancelSearch() {
49                 $scope.searching = false;
50                 $scope.searchTerm = '';
51                 $scope.images = preSearchImages;
52                 $scope.hasMore = preSearchHasMore;
53             }
54             $scope.cancelSearch = cancelSearch;
55
56
57             /**
58              * Runs on image upload, Adds an image to local list of images
59              * and shows a success message to the user.
60              * @param file
61              * @param data
62              */
63             $scope.uploadSuccess = function (file, data) {
64                 $scope.$apply(() => {
65                     $scope.images.unshift(data);
66                 });
67                 events.emit('success', 'Image uploaded');
68             };
69
70             /**
71              * Runs the callback and hides the image manager.
72              * @param returnData
73              */
74             function callbackAndHide(returnData) {
75                 if (callback) callback(returnData);
76                 $scope.hide();
77             }
78
79             /**
80              * Image select action. Checks if a double-click was fired.
81              * @param image
82              */
83             $scope.imageSelect = function (image) {
84                 let dblClickTime = 300;
85                 let currentTime = Date.now();
86                 let timeDiff = currentTime - previousClickTime;
87
88                 if (timeDiff < dblClickTime && image.id === previousClickImage) {
89                     // If double click
90                     callbackAndHide(image);
91                 } else {
92                     // If single
93                     $scope.selectedImage = image;
94                     $scope.dependantPages = false;
95                 }
96                 previousClickTime = currentTime;
97                 previousClickImage = image.id;
98             };
99
100             /**
101              * Action that runs when the 'Select image' button is clicked.
102              * Runs the callback and hides the image manager.
103              */
104             $scope.selectButtonClick = function () {
105                 callbackAndHide($scope.selectedImage);
106             };
107
108             /**
109              * Show the image manager.
110              * Takes a callback to execute later on.
111              * @param doneCallback
112              */
113             function show(doneCallback) {
114                 callback = doneCallback;
115                 $scope.showing = true;
116                 $('#image-manager').find('.overlay').css('display', 'flex').hide().fadeIn(240);
117                 // Get initial images if they have not yet been loaded in.
118                 if (!dataLoaded) {
119                     fetchData();
120                     dataLoaded = true;
121                 }
122             }
123
124             // Connects up the image manger so it can be used externally
125             // such as from TinyMCE.
126             imageManagerService.show = show;
127             imageManagerService.showExternal = function (doneCallback) {
128                 $scope.$apply(() => {
129                     show(doneCallback);
130                 });
131             };
132             window.ImageManager = imageManagerService;
133
134             /**
135              * Hide the image manager
136              */
137             $scope.hide = function () {
138                 $scope.showing = false;
139                 $('#image-manager').find('.overlay').fadeOut(240);
140             };
141
142             let baseUrl = window.baseUrl('/images/' + $scope.imageType + '/all/');
143
144             /**
145              * Fetch the list image data from the server.
146              */
147             function fetchData() {
148                 let url = baseUrl + page + '?';
149                 let components = {};
150                 if ($scope.uploadedTo) components['page_id'] = $scope.uploadedTo;
151                 if ($scope.searching) components['term'] = $scope.searchTerm;
152
153
154                 let urlQueryString = Object.keys(components).map((key) => {
155                     return key + '=' + encodeURIComponent(components[key]);
156                 }).join('&');
157                 url += urlQueryString;
158
159                 $http.get(url).then((response) => {
160                     $scope.images = $scope.images.concat(response.data.images);
161                     $scope.hasMore = response.data.hasMore;
162                     page++;
163                 });
164             }
165             $scope.fetchData = fetchData;
166
167             /**
168              * Start a search operation
169              */
170             $scope.searchImages = function() {
171
172                 if ($scope.searchTerm === '') {
173                     cancelSearch();
174                     return;
175                 }
176
177                 if (!$scope.searching) {
178                     preSearchImages = $scope.images;
179                     preSearchHasMore = $scope.hasMore;
180                 }
181
182                 $scope.searching = true;
183                 $scope.images = [];
184                 $scope.hasMore = false;
185                 page = 0;
186                 baseUrl = window.baseUrl('/images/' + $scope.imageType + '/search/');
187                 fetchData();
188             };
189
190             /**
191              * Set the current image listing view.
192              * @param viewName
193              */
194             $scope.setView = function(viewName) {
195                 cancelSearch();
196                 $scope.images = [];
197                 $scope.hasMore = false;
198                 page = 0;
199                 $scope.view = viewName;
200                 baseUrl = window.baseUrl('/images/' + $scope.imageType  + '/' + viewName + '/');
201                 fetchData();
202             };
203
204             /**
205              * Save the details of an image.
206              * @param event
207              */
208             $scope.saveImageDetails = function (event) {
209                 event.preventDefault();
210                 let url = window.baseUrl('/images/update/' + $scope.selectedImage.id);
211                 $http.put(url, this.selectedImage).then(response => {
212                     events.emit('success', 'Image details updated');
213                 }, (response) => {
214                     if (response.status === 422) {
215                         let errors = response.data;
216                         let message = '';
217                         Object.keys(errors).forEach((key) => {
218                             message += errors[key].join('\n');
219                         });
220                         events.emit('error', message);
221                     } else if (response.status === 403) {
222                         events.emit('error', response.data.error);
223                     }
224                 });
225             };
226
227             /**
228              * Delete an image from system and notify of success.
229              * Checks if it should force delete when an image
230              * has dependant pages.
231              * @param event
232              */
233             $scope.deleteImage = function (event) {
234                 event.preventDefault();
235                 let force = $scope.dependantPages !== false;
236                 let url = window.baseUrl('/images/' + $scope.selectedImage.id);
237                 if (force) url += '?force=true';
238                 $http.delete(url).then((response) => {
239                     $scope.images.splice($scope.images.indexOf($scope.selectedImage), 1);
240                     $scope.selectedImage = false;
241                     events.emit('success', 'Image successfully deleted');
242                 }, (response) => {
243                     // Pages failure
244                     if (response.status === 400) {
245                         $scope.dependantPages = response.data;
246                     } else if (response.status === 403) {
247                         events.emit('error', response.data.error);
248                     }
249                 });
250             };
251
252             /**
253              * Simple date creator used to properly format dates.
254              * @param stringDate
255              * @returns {Date}
256              */
257             $scope.getDate = function (stringDate) {
258                 return new Date(stringDate);
259             };
260
261         }]);
262
263
264     ngApp.controller('BookShowController', ['$scope', '$http', '$attrs', '$sce', function ($scope, $http, $attrs, $sce) {
265         $scope.searching = false;
266         $scope.searchTerm = '';
267         $scope.searchResults = '';
268
269         $scope.searchBook = function (e) {
270             e.preventDefault();
271             let term = $scope.searchTerm;
272             if (term.length == 0) return;
273             $scope.searching = true;
274             $scope.searchResults = '';
275             let searchUrl = window.baseUrl('/search/book/' + $attrs.bookId);
276             searchUrl += '?term=' + encodeURIComponent(term);
277             $http.get(searchUrl).then((response) => {
278                 $scope.searchResults = $sce.trustAsHtml(response.data);
279             });
280         };
281
282         $scope.checkSearchForm = function () {
283             if ($scope.searchTerm.length < 1) {
284                 $scope.searching = false;
285             }
286         };
287
288         $scope.clearSearch = function () {
289             $scope.searching = false;
290             $scope.searchTerm = '';
291         };
292
293     }]);
294
295
296     ngApp.controller('PageEditController', ['$scope', '$http', '$attrs', '$interval', '$timeout', '$sce',
297         function ($scope, $http, $attrs, $interval, $timeout, $sce) {
298
299         $scope.editorOptions = editorOptions();
300         $scope.editContent = '';
301         $scope.draftText = '';
302         let pageId = Number($attrs.pageId);
303         let isEdit = pageId !== 0;
304         let autosaveFrequency = 30; // AutoSave interval in seconds.
305         let isMarkdown = $attrs.editorType === 'markdown';
306         $scope.draftsEnabled = $attrs.draftsEnabled === 'true';
307         $scope.isUpdateDraft = Number($attrs.pageUpdateDraft) === 1;
308         $scope.isNewPageDraft = Number($attrs.pageNewDraft) === 1;
309
310         // Set initial header draft text
311         if ($scope.isUpdateDraft || $scope.isNewPageDraft) {
312             $scope.draftText = 'Editing Draft'
313         } else {
314             $scope.draftText = 'Editing Page'
315         }
316
317         let autoSave = false;
318
319         let currentContent = {
320             title: false,
321             html: false
322         };
323
324         if (isEdit && $scope.draftsEnabled) {
325             setTimeout(() => {
326                 startAutoSave();
327             }, 1000);
328         }
329
330         // Actions specifically for the markdown editor
331         if (isMarkdown) {
332             $scope.displayContent = '';
333             // Editor change event
334             $scope.editorChange = function (content) {
335                 $scope.displayContent = $sce.trustAsHtml(content);
336             }
337         }
338
339         if (!isMarkdown) {
340             $scope.editorChange = function() {};
341         }
342
343         let lastSave = 0;
344
345         /**
346          * Start the AutoSave loop, Checks for content change
347          * before performing the costly AJAX request.
348          */
349         function startAutoSave() {
350             currentContent.title = $('#name').val();
351             currentContent.html = $scope.editContent;
352
353             autoSave = $interval(() => {
354                 // Return if manually saved recently to prevent bombarding the server
355                 if (Date.now() - lastSave < (1000*autosaveFrequency)/2) return;
356                 let newTitle = $('#name').val();
357                 let newHtml = $scope.editContent;
358
359                 if (newTitle !== currentContent.title || newHtml !== currentContent.html) {
360                     currentContent.html = newHtml;
361                     currentContent.title = newTitle;
362                     saveDraft();
363                 }
364
365             }, 1000 * autosaveFrequency);
366         }
367
368         let draftErroring = false;
369         /**
370          * Save a draft update into the system via an AJAX request.
371          */
372         function saveDraft() {
373             if (!$scope.draftsEnabled) return;
374             let data = {
375                 name: $('#name').val(),
376                 html: isMarkdown ? $sce.getTrustedHtml($scope.displayContent) : $scope.editContent
377             };
378
379             if (isMarkdown) data.markdown = $scope.editContent;
380
381             let url = window.baseUrl('/ajax/page/' + pageId + '/save-draft');
382             $http.put(url, data).then(responseData => {
383                 draftErroring = false;
384                 let updateTime = moment.utc(moment.unix(responseData.data.timestamp)).toDate();
385                 $scope.draftText = responseData.data.message + moment(updateTime).format('HH:mm');
386                 if (!$scope.isNewPageDraft) $scope.isUpdateDraft = true;
387                 showDraftSaveNotification();
388                 lastSave = Date.now();
389             }, errorRes => {
390                 if (draftErroring) return;
391                 events.emit('error', 'Failed to save draft. Ensure you have internet connection before saving this page.')
392                 draftErroring = true;
393             });
394         }
395
396         function showDraftSaveNotification() {
397             $scope.draftUpdated = true;
398             $timeout(() => {
399                 $scope.draftUpdated = false;
400             }, 2000)
401         }
402
403         $scope.forceDraftSave = function() {
404             saveDraft();
405         };
406
407         // Listen to shortcuts coming via events
408         $scope.$on('editor-keydown', (event, data) => {
409             // Save shortcut (ctrl+s)
410             if (data.keyCode == 83 && (navigator.platform.match("Mac") ? data.metaKey : data.ctrlKey)) {
411                 data.preventDefault();
412                 saveDraft();
413             }
414         });
415
416         /**
417          * Discard the current draft and grab the current page
418          * content from the system via an AJAX request.
419          */
420         $scope.discardDraft = function () {
421             let url = window.baseUrl('/ajax/page/' + pageId);
422             $http.get(url).then((responseData) => {
423                 if (autoSave) $interval.cancel(autoSave);
424                 $scope.draftText = 'Editing Page';
425                 $scope.isUpdateDraft = false;
426                 $scope.$broadcast('html-update', responseData.data.html);
427                 $scope.$broadcast('markdown-update', responseData.data.markdown || responseData.data.html);
428                 $('#name').val(responseData.data.name);
429                 $timeout(() => {
430                     startAutoSave();
431                 }, 1000);
432                 events.emit('success', 'Draft discarded, The editor has been updated with the current page content');
433             });
434         };
435
436     }]);
437
438     ngApp.controller('PageTagController', ['$scope', '$http', '$attrs',
439         function ($scope, $http, $attrs) {
440
441             const pageId = Number($attrs.pageId);
442             $scope.tags = [];
443
444             $scope.sortOptions = {
445                 handle: '.handle',
446                 items: '> tr',
447                 containment: "parent",
448                 axis: "y"
449             };
450
451             /**
452              * Push an empty tag to the end of the scope tags.
453              */
454             function addEmptyTag() {
455                 $scope.tags.push({
456                     name: '',
457                     value: ''
458                 });
459             }
460             $scope.addEmptyTag = addEmptyTag;
461
462             /**
463              * Get all tags for the current book and add into scope.
464              */
465             function getTags() {
466                 let url = window.baseUrl(`/ajax/tags/get/page/${pageId}`);
467                 $http.get(url).then((responseData) => {
468                     $scope.tags = responseData.data;
469                     addEmptyTag();
470                 });
471             }
472             getTags();
473
474             /**
475              * Set the order property on all tags.
476              */
477             function setTagOrder() {
478                 for (let i = 0; i < $scope.tags.length; i++) {
479                     $scope.tags[i].order = i;
480                 }
481             }
482
483             /**
484              * When an tag changes check if another empty editable
485              * field needs to be added onto the end.
486              * @param tag
487              */
488             $scope.tagChange = function(tag) {
489                 let cPos = $scope.tags.indexOf(tag);
490                 if (cPos !== $scope.tags.length-1) return;
491
492                 if (tag.name !== '' || tag.value !== '') {
493                     addEmptyTag();
494                 }
495             };
496
497             /**
498              * When an tag field loses focus check the tag to see if its
499              * empty and therefore could be removed from the list.
500              * @param tag
501              */
502             $scope.tagBlur = function(tag) {
503                 let isLast = $scope.tags.length - 1 === $scope.tags.indexOf(tag);
504                 if (tag.name === '' && tag.value === '' && !isLast) {
505                     let cPos = $scope.tags.indexOf(tag);
506                     $scope.tags.splice(cPos, 1);
507                 }
508             };
509
510             /**
511              * Remove a tag from the current list.
512              * @param tag
513              */
514             $scope.removeTag = function(tag) {
515                 let cIndex = $scope.tags.indexOf(tag);
516                 $scope.tags.splice(cIndex, 1);
517             };
518
519         }]);
520
521
522     ngApp.controller('PageAttachmentController', ['$scope', '$http', '$attrs',
523         function ($scope, $http, $attrs) {
524
525             const pageId = $scope.uploadedTo = $attrs.pageId;
526             let currentOrder = '';
527             $scope.files = [];
528             $scope.editFile = false;
529             $scope.file = getCleanFile();
530             $scope.errors = {
531                 link: {},
532                 edit: {}
533             };
534
535             function getCleanFile() {
536                 return {
537                     page_id: pageId
538                 };
539             }
540
541             // Angular-UI-Sort options
542             $scope.sortOptions = {
543                 handle: '.handle',
544                 items: '> tr',
545                 containment: "parent",
546                 axis: "y",
547                 stop: sortUpdate,
548             };
549
550             /**
551              * Event listener for sort changes.
552              * Updates the file ordering on the server.
553              * @param event
554              * @param ui
555              */
556             function sortUpdate(event, ui) {
557                 let newOrder = $scope.files.map(file => {return file.id}).join(':');
558                 if (newOrder === currentOrder) return;
559
560                 currentOrder = newOrder;
561                 $http.put(window.baseUrl(`/attachments/sort/page/${pageId}`), {files: $scope.files}).then(resp => {
562                     events.emit('success', resp.data.message);
563                 }, checkError('sort'));
564             }
565
566             /**
567              * Used by dropzone to get the endpoint to upload to.
568              * @returns {string}
569              */
570             $scope.getUploadUrl = function (file) {
571                 let suffix = (typeof file !== 'undefined') ? `/${file.id}` : '';
572                 return window.baseUrl(`/attachments/upload${suffix}`);
573             };
574
575             /**
576              * Get files for the current page from the server.
577              */
578             function getFiles() {
579                 let url = window.baseUrl(`/attachments/get/page/${pageId}`)
580                 $http.get(url).then(resp => {
581                     $scope.files = resp.data;
582                     currentOrder = resp.data.map(file => {return file.id}).join(':');
583                 }, checkError('get'));
584             }
585             getFiles();
586
587             /**
588              * Runs on file upload, Adds an file to local file list
589              * and shows a success message to the user.
590              * @param file
591              * @param data
592              */
593             $scope.uploadSuccess = function (file, data) {
594                 $scope.$apply(() => {
595                     $scope.files.push(data);
596                 });
597                 events.emit('success', 'File uploaded');
598             };
599
600             /**
601              * Upload and overwrite an existing file.
602              * @param file
603              * @param data
604              */
605             $scope.uploadSuccessUpdate = function (file, data) {
606                 $scope.$apply(() => {
607                     let search = filesIndexOf(data);
608                     if (search !== -1) $scope.files[search] = data;
609
610                     if ($scope.editFile) {
611                         $scope.editFile = angular.copy(data);
612                         data.link = '';
613                     }
614                 });
615                 events.emit('success', 'File updated');
616             };
617
618             /**
619              * Delete a file from the server and, on success, the local listing.
620              * @param file
621              */
622             $scope.deleteFile = function(file) {
623                 if (!file.deleting) {
624                     file.deleting = true;
625                     return;
626                 }
627                   $http.delete(window.baseUrl(`/attachments/${file.id}`)).then(resp => {
628                       events.emit('success', resp.data.message);
629                       $scope.files.splice($scope.files.indexOf(file), 1);
630                   }, checkError('delete'));
631             };
632
633             /**
634              * Attach a link to a page.
635              * @param file
636              */
637             $scope.attachLinkSubmit = function(file) {
638                 file.uploaded_to = pageId;
639                 $http.post(window.baseUrl('/attachments/link'), file).then(resp => {
640                     $scope.files.push(resp.data);
641                     events.emit('success', 'Link attached');
642                     $scope.file = getCleanFile();
643                 }, checkError('link'));
644             };
645
646             /**
647              * Start the edit mode for a file.
648              * @param file
649              */
650             $scope.startEdit = function(file) {
651                 $scope.editFile = angular.copy(file);
652                 $scope.editFile.link = (file.external) ? file.path : '';
653             };
654
655             /**
656              * Cancel edit mode
657              */
658             $scope.cancelEdit = function() {
659                 $scope.editFile = false;
660             };
661
662             /**
663              * Update the name and link of a file.
664              * @param file
665              */
666             $scope.updateFile = function(file) {
667                 $http.put(window.baseUrl(`/attachments/${file.id}`), file).then(resp => {
668                     let search = filesIndexOf(resp.data);
669                     if (search !== -1) $scope.files[search] = resp.data;
670
671                     if ($scope.editFile && !file.external) {
672                         $scope.editFile.link = '';
673                     }
674                     $scope.editFile = false;
675                     events.emit('success', 'Attachment details updated');
676                 }, checkError('edit'));
677             };
678
679             /**
680              * Get the url of a file.
681              */
682             $scope.getFileUrl = function(file) {
683                 return window.baseUrl('/attachments/' + file.id);
684             };
685
686             /**
687              * Search the local files via another file object.
688              * Used to search via object copies.
689              * @param file
690              * @returns int
691              */
692             function filesIndexOf(file) {
693                 for (let i = 0; i < $scope.files.length; i++) {
694                     if ($scope.files[i].id == file.id) return i;
695                 }
696                 return -1;
697             }
698
699             /**
700              * Check for an error response in a ajax request.
701              * @param errorGroupName
702              */
703             function checkError(errorGroupName) {
704                 $scope.errors[errorGroupName] = {};
705                 return function(response) {
706                     if (typeof response.data !== 'undefined' && typeof response.data.error !== 'undefined') {
707                         events.emit('error', response.data.error);
708                     }
709                     if (typeof response.data !== 'undefined' && typeof response.data.validation !== 'undefined') {
710                         $scope.errors[errorGroupName] = response.data.validation;
711                         console.log($scope.errors[errorGroupName])
712                     }
713                 }
714             }
715
716         }]);
717
718 };