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