]> BookStack Code Mirror - bookstack/blob - resources/assets/js/controllers.js
Converted image manager into vue component
[bookstack] / resources / assets / js / controllers.js
1 "use strict";
2
3 const moment = require('moment');
4 require('moment/locale/en-gb');
5 const editorOptions = require("./pages/page-form");
6
7 moment.locale('en-gb');
8
9 module.exports = function (ngApp, events) {
10
11
12     ngApp.controller('PageEditController', ['$scope', '$http', '$attrs', '$interval', '$timeout', '$sce',
13         function ($scope, $http, $attrs, $interval, $timeout, $sce) {
14
15         $scope.editorOptions = editorOptions();
16         $scope.editContent = '';
17         $scope.draftText = '';
18         let pageId = Number($attrs.pageId);
19         let isEdit = pageId !== 0;
20         let autosaveFrequency = 30; // AutoSave interval in seconds.
21         let isMarkdown = $attrs.editorType === 'markdown';
22         $scope.draftsEnabled = $attrs.draftsEnabled === 'true';
23         $scope.isUpdateDraft = Number($attrs.pageUpdateDraft) === 1;
24         $scope.isNewPageDraft = Number($attrs.pageNewDraft) === 1;
25
26         // Set initial header draft text
27         if ($scope.isUpdateDraft || $scope.isNewPageDraft) {
28             $scope.draftText = trans('entities.pages_editing_draft');
29         } else {
30             $scope.draftText = trans('entities.pages_editing_page');
31         }
32
33         let autoSave = false;
34
35         let currentContent = {
36             title: false,
37             html: false
38         };
39
40         if (isEdit && $scope.draftsEnabled) {
41             setTimeout(() => {
42                 startAutoSave();
43             }, 1000);
44         }
45
46         // Actions specifically for the markdown editor
47         if (isMarkdown) {
48             $scope.displayContent = '';
49             // Editor change event
50             $scope.editorChange = function (content) {
51                 $scope.displayContent = $sce.trustAsHtml(content);
52             }
53         }
54
55         if (!isMarkdown) {
56             $scope.editorChange = function() {};
57         }
58
59         let lastSave = 0;
60
61         /**
62          * Start the AutoSave loop, Checks for content change
63          * before performing the costly AJAX request.
64          */
65         function startAutoSave() {
66             currentContent.title = $('#name').val();
67             currentContent.html = $scope.editContent;
68
69             autoSave = $interval(() => {
70                 // Return if manually saved recently to prevent bombarding the server
71                 if (Date.now() - lastSave < (1000*autosaveFrequency)/2) return;
72                 let newTitle = $('#name').val();
73                 let newHtml = $scope.editContent;
74
75                 if (newTitle !== currentContent.title || newHtml !== currentContent.html) {
76                     currentContent.html = newHtml;
77                     currentContent.title = newTitle;
78                     saveDraft();
79                 }
80
81             }, 1000 * autosaveFrequency);
82         }
83
84         let draftErroring = false;
85         /**
86          * Save a draft update into the system via an AJAX request.
87          */
88         function saveDraft() {
89             if (!$scope.draftsEnabled) return;
90             let data = {
91                 name: $('#name').val(),
92                 html: isMarkdown ? $sce.getTrustedHtml($scope.displayContent) : $scope.editContent
93             };
94
95             if (isMarkdown) data.markdown = $scope.editContent;
96
97             let url = window.baseUrl('/ajax/page/' + pageId + '/save-draft');
98             $http.put(url, data).then(responseData => {
99                 draftErroring = false;
100                 let updateTime = moment.utc(moment.unix(responseData.data.timestamp)).toDate();
101                 $scope.draftText = responseData.data.message + moment(updateTime).format('HH:mm');
102                 if (!$scope.isNewPageDraft) $scope.isUpdateDraft = true;
103                 showDraftSaveNotification();
104                 lastSave = Date.now();
105             }, errorRes => {
106                 if (draftErroring) return;
107                 events.emit('error', trans('errors.page_draft_autosave_fail'));
108                 draftErroring = true;
109             });
110         }
111
112         function showDraftSaveNotification() {
113             $scope.draftUpdated = true;
114             $timeout(() => {
115                 $scope.draftUpdated = false;
116             }, 2000)
117         }
118
119         $scope.forceDraftSave = function() {
120             saveDraft();
121         };
122
123         // Listen to save draft events from editor
124         $scope.$on('save-draft', saveDraft);
125
126         /**
127          * Discard the current draft and grab the current page
128          * content from the system via an AJAX request.
129          */
130         $scope.discardDraft = function () {
131             let url = window.baseUrl('/ajax/page/' + pageId);
132             $http.get(url).then(responseData => {
133                 if (autoSave) $interval.cancel(autoSave);
134                 $scope.draftText = trans('entities.pages_editing_page');
135                 $scope.isUpdateDraft = false;
136                 $scope.$broadcast('html-update', responseData.data.html);
137                 $scope.$broadcast('markdown-update', responseData.data.markdown || responseData.data.html);
138                 $('#name').val(responseData.data.name);
139                 $timeout(() => {
140                     startAutoSave();
141                 }, 1000);
142                 events.emit('success', trans('entities.pages_draft_discarded'));
143             });
144         };
145
146     }]);
147
148     ngApp.controller('PageTagController', ['$scope', '$http', '$attrs',
149         function ($scope, $http, $attrs) {
150
151             const pageId = Number($attrs.pageId);
152             $scope.tags = [];
153
154             $scope.sortOptions = {
155                 handle: '.handle',
156                 items: '> tr',
157                 containment: "parent",
158                 axis: "y"
159             };
160
161             /**
162              * Push an empty tag to the end of the scope tags.
163              */
164             function addEmptyTag() {
165                 $scope.tags.push({
166                     name: '',
167                     value: ''
168                 });
169             }
170             $scope.addEmptyTag = addEmptyTag;
171
172             /**
173              * Get all tags for the current book and add into scope.
174              */
175             function getTags() {
176                 let url = window.baseUrl(`/ajax/tags/get/page/${pageId}`);
177                 $http.get(url).then((responseData) => {
178                     $scope.tags = responseData.data;
179                     addEmptyTag();
180                 });
181             }
182             getTags();
183
184             /**
185              * Set the order property on all tags.
186              */
187             function setTagOrder() {
188                 for (let i = 0; i < $scope.tags.length; i++) {
189                     $scope.tags[i].order = i;
190                 }
191             }
192
193             /**
194              * When an tag changes check if another empty editable
195              * field needs to be added onto the end.
196              * @param tag
197              */
198             $scope.tagChange = function(tag) {
199                 let cPos = $scope.tags.indexOf(tag);
200                 if (cPos !== $scope.tags.length-1) return;
201
202                 if (tag.name !== '' || tag.value !== '') {
203                     addEmptyTag();
204                 }
205             };
206
207             /**
208              * When an tag field loses focus check the tag to see if its
209              * empty and therefore could be removed from the list.
210              * @param tag
211              */
212             $scope.tagBlur = function(tag) {
213                 let isLast = $scope.tags.length - 1 === $scope.tags.indexOf(tag);
214                 if (tag.name === '' && tag.value === '' && !isLast) {
215                     let cPos = $scope.tags.indexOf(tag);
216                     $scope.tags.splice(cPos, 1);
217                 }
218             };
219
220             /**
221              * Remove a tag from the current list.
222              * @param tag
223              */
224             $scope.removeTag = function(tag) {
225                 let cIndex = $scope.tags.indexOf(tag);
226                 $scope.tags.splice(cIndex, 1);
227             };
228
229         }]);
230
231
232     ngApp.controller('PageAttachmentController', ['$scope', '$http', '$attrs',
233         function ($scope, $http, $attrs) {
234
235             const pageId = $scope.uploadedTo = $attrs.pageId;
236             let currentOrder = '';
237             $scope.files = [];
238             $scope.editFile = false;
239             $scope.file = getCleanFile();
240             $scope.errors = {
241                 link: {},
242                 edit: {}
243             };
244
245             function getCleanFile() {
246                 return {
247                     page_id: pageId
248                 };
249             }
250
251             // Angular-UI-Sort options
252             $scope.sortOptions = {
253                 handle: '.handle',
254                 items: '> tr',
255                 containment: "parent",
256                 axis: "y",
257                 stop: sortUpdate,
258             };
259
260             /**
261              * Event listener for sort changes.
262              * Updates the file ordering on the server.
263              * @param event
264              * @param ui
265              */
266             function sortUpdate(event, ui) {
267                 let newOrder = $scope.files.map(file => {return file.id}).join(':');
268                 if (newOrder === currentOrder) return;
269
270                 currentOrder = newOrder;
271                 $http.put(window.baseUrl(`/attachments/sort/page/${pageId}`), {files: $scope.files}).then(resp => {
272                     events.emit('success', resp.data.message);
273                 }, checkError('sort'));
274             }
275
276             /**
277              * Used by dropzone to get the endpoint to upload to.
278              * @returns {string}
279              */
280             $scope.getUploadUrl = function (file) {
281                 let suffix = (typeof file !== 'undefined') ? `/${file.id}` : '';
282                 return window.baseUrl(`/attachments/upload${suffix}`);
283             };
284
285             /**
286              * Get files for the current page from the server.
287              */
288             function getFiles() {
289                 let url = window.baseUrl(`/attachments/get/page/${pageId}`);
290                 $http.get(url).then(resp => {
291                     $scope.files = resp.data;
292                     currentOrder = resp.data.map(file => {return file.id}).join(':');
293                 }, checkError('get'));
294             }
295             getFiles();
296
297             /**
298              * Runs on file upload, Adds an file to local file list
299              * and shows a success message to the user.
300              * @param file
301              * @param data
302              */
303             $scope.uploadSuccess = function (file, data) {
304                 $scope.$apply(() => {
305                     $scope.files.push(data);
306                 });
307                 events.emit('success', trans('entities.attachments_file_uploaded'));
308             };
309
310             /**
311              * Upload and overwrite an existing file.
312              * @param file
313              * @param data
314              */
315             $scope.uploadSuccessUpdate = function (file, data) {
316                 $scope.$apply(() => {
317                     let search = filesIndexOf(data);
318                     if (search !== -1) $scope.files[search] = data;
319
320                     if ($scope.editFile) {
321                         $scope.editFile = angular.copy(data);
322                         data.link = '';
323                     }
324                 });
325                 events.emit('success', trans('entities.attachments_file_updated'));
326             };
327
328             /**
329              * Delete a file from the server and, on success, the local listing.
330              * @param file
331              */
332             $scope.deleteFile = function(file) {
333                 if (!file.deleting) {
334                     file.deleting = true;
335                     return;
336                 }
337                   $http.delete(window.baseUrl(`/attachments/${file.id}`)).then(resp => {
338                       events.emit('success', resp.data.message);
339                       $scope.files.splice($scope.files.indexOf(file), 1);
340                   }, checkError('delete'));
341             };
342
343             /**
344              * Attach a link to a page.
345              * @param file
346              */
347             $scope.attachLinkSubmit = function(file) {
348                 file.uploaded_to = pageId;
349                 $http.post(window.baseUrl('/attachments/link'), file).then(resp => {
350                     $scope.files.push(resp.data);
351                     events.emit('success', trans('entities.attachments_link_attached'));
352                     $scope.file = getCleanFile();
353                 }, checkError('link'));
354             };
355
356             /**
357              * Start the edit mode for a file.
358              * @param file
359              */
360             $scope.startEdit = function(file) {
361                 $scope.editFile = angular.copy(file);
362                 $scope.editFile.link = (file.external) ? file.path : '';
363             };
364
365             /**
366              * Cancel edit mode
367              */
368             $scope.cancelEdit = function() {
369                 $scope.editFile = false;
370             };
371
372             /**
373              * Update the name and link of a file.
374              * @param file
375              */
376             $scope.updateFile = function(file) {
377                 $http.put(window.baseUrl(`/attachments/${file.id}`), file).then(resp => {
378                     let search = filesIndexOf(resp.data);
379                     if (search !== -1) $scope.files[search] = resp.data;
380
381                     if ($scope.editFile && !file.external) {
382                         $scope.editFile.link = '';
383                     }
384                     $scope.editFile = false;
385                     events.emit('success', trans('entities.attachments_updated_success'));
386                 }, checkError('edit'));
387             };
388
389             /**
390              * Get the url of a file.
391              */
392             $scope.getFileUrl = function(file) {
393                 return window.baseUrl('/attachments/' + file.id);
394             };
395
396             /**
397              * Search the local files via another file object.
398              * Used to search via object copies.
399              * @param file
400              * @returns int
401              */
402             function filesIndexOf(file) {
403                 for (let i = 0; i < $scope.files.length; i++) {
404                     if ($scope.files[i].id == file.id) return i;
405                 }
406                 return -1;
407             }
408
409             /**
410              * Check for an error response in a ajax request.
411              * @param errorGroupName
412              */
413             function checkError(errorGroupName) {
414                 $scope.errors[errorGroupName] = {};
415                 return function(response) {
416                     if (typeof response.data !== 'undefined' && typeof response.data.error !== 'undefined') {
417                         events.emit('error', response.data.error);
418                     }
419                     if (typeof response.data !== 'undefined' && typeof response.data.validation !== 'undefined') {
420                         $scope.errors[errorGroupName] = response.data.validation;
421                         console.log($scope.errors[errorGroupName])
422                     }
423                 }
424             }
425
426         }]);
427
428     // Controller used to reply to and add new comments
429     ngApp.controller('CommentReplyController', ['$scope', '$http', '$timeout', function ($scope, $http, $timeout) {
430         const MarkdownIt = require("markdown-it");
431         const md = new MarkdownIt({html: true});
432         let vm = this;
433
434         vm.saveComment = function () {
435             let pageId = $scope.comment.pageId || $scope.pageId;
436             let comment = $scope.comment.text;
437             if (!comment) {
438                 return events.emit('warning', trans('errors.empty_comment'));
439             }
440             let commentHTML = md.render($scope.comment.text);
441             let serviceUrl = `/ajax/page/${pageId}/comment/`;
442             let httpMethod = 'post';
443             let reqObj = {
444                 text: comment,
445                 html: commentHTML
446             };
447
448             if ($scope.isEdit === true) {
449                 // this will be set when editing the comment.
450                 serviceUrl = `/ajax/page/${pageId}/comment/${$scope.comment.id}`;
451                 httpMethod = 'put';
452             } else if ($scope.isReply === true) {
453                 // if its reply, get the parent comment id
454                 reqObj.parent_id = $scope.parentId;
455             }
456             $http[httpMethod](window.baseUrl(serviceUrl), reqObj).then(resp => {
457                 if (!isCommentOpSuccess(resp)) {
458                      return;
459                 }
460                 // hide the comments first, and then retrigger the refresh
461                 if ($scope.isEdit) {
462                     updateComment($scope.comment, resp.data);
463                     $scope.$emit('evt.comment-success', $scope.comment.id);
464                 } else {
465                     $scope.comment.text = '';
466                     if ($scope.isReply === true && $scope.parent.sub_comments) {
467                         $scope.parent.sub_comments.push(resp.data.comment);
468                     } else {
469                         $scope.$emit('evt.new-comment', resp.data.comment);
470                     }
471                     $scope.$emit('evt.comment-success', null, true);
472                 }
473                 $scope.comment.is_hidden = true;
474                 $timeout(function() {
475                     $scope.comment.is_hidden = false;
476                 });
477
478                 events.emit('success', trans(resp.data.message));
479
480             }, checkError);
481
482         };
483
484         function checkError(response) {
485             let msg = null;
486             if (isCommentOpSuccess(response)) {
487                 // all good
488                 return;
489             } else if (response.data) {
490                 msg = response.data.message;
491             } else {
492                 msg = trans('errors.comment_add');
493             }
494             if (msg) {
495                 events.emit('success', msg);
496             }
497         }
498     }]);
499
500     // Controller used to delete comments
501     ngApp.controller('CommentDeleteController', ['$scope', '$http', '$timeout', function ($scope, $http, $timeout) {
502         let vm = this;
503
504         vm.delete = function(comment) {
505             $http.delete(window.baseUrl(`/ajax/comment/${comment.id}`)).then(resp => {
506                 if (!isCommentOpSuccess(resp)) {
507                     return;
508                 }
509                 updateComment(comment, resp.data, $timeout, true);
510             }, function (resp) {
511                 if (isCommentOpSuccess(resp)) {
512                     events.emit('success', trans('entities.comment_deleted'));
513                 } else {
514                     events.emit('error', trans('error.comment_delete'));
515                 }
516             });
517         };
518     }]);
519
520     // Controller used to fetch all comments for a page
521     ngApp.controller('CommentListController', ['$scope', '$http', '$timeout', '$location', function ($scope, $http, $timeout, $location) {
522         let vm = this;
523         $scope.errors = {};
524         // keep track of comment levels
525         $scope.level = 1;
526         vm.totalCommentsStr = trans('entities.comments_loading');
527         vm.permissions = {};
528         vm.trans = window.trans;
529
530         $scope.$on('evt.new-comment', function (event, comment) {
531             // add the comment to the comment list.
532             vm.comments.push(comment);
533             ++vm.totalComments;
534             setTotalCommentMsg();
535             event.stopPropagation();
536             event.preventDefault();
537         });
538
539         vm.canEditDelete = function (comment, prop) {
540             if (!comment.active) {
541                 return false;
542             }
543             let propAll = prop + '_all';
544             let propOwn = prop + '_own';
545
546             if (vm.permissions[propAll]) {
547                 return true;
548             }
549
550             if (vm.permissions[propOwn] && comment.created_by.id === vm.current_user_id) {
551                 return true;
552             }
553
554             return false;
555         };
556
557         vm.canComment = function () {
558             return vm.permissions.comment_create;
559         };
560
561         // check if there are is any direct linking
562         let linkedCommentId = $location.search().cm;
563
564         $timeout(function() {
565             $http.get(window.baseUrl(`/ajax/page/${$scope.pageId}/comments/`)).then(resp => {
566                 if (!isCommentOpSuccess(resp)) {
567                     // just show that no comments are available.
568                     vm.totalComments = 0;
569                     setTotalCommentMsg();
570                     return;
571                 }
572                 vm.comments = resp.data.comments;
573                 vm.totalComments = +resp.data.total;
574                 vm.permissions = resp.data.permissions;
575                 vm.current_user_id = resp.data.user_id;
576                 setTotalCommentMsg();
577                 if (!linkedCommentId) {
578                     return;
579                 }
580                 $timeout(function() {
581                     // wait for the UI to render.
582                     focusLinkedComment(linkedCommentId);
583                 });
584             }, checkError);
585         });
586
587         function setTotalCommentMsg () {
588             if (vm.totalComments === 0) {
589                 vm.totalCommentsStr = trans('entities.no_comments');
590             } else if (vm.totalComments === 1) {
591                 vm.totalCommentsStr = trans('entities.one_comment');
592             } else {
593                 vm.totalCommentsStr = trans('entities.x_comments', {
594                     numComments: vm.totalComments
595                 });
596             }
597         }
598
599         function focusLinkedComment(linkedCommentId) {
600             let comment = angular.element('#' + linkedCommentId);
601             if (comment.length === 0) {
602                 return;
603             }
604
605             window.setupPageShow.goToText(linkedCommentId);
606         }
607
608         function checkError(response) {
609             let msg = null;
610             if (isCommentOpSuccess(response)) {
611                 // all good
612                 return;
613             } else if (response.data) {
614                 msg = response.data.message;
615             } else {
616                 msg = trans('errors.comment_list');
617             }
618             if (msg) {
619                 events.emit('success', msg);
620             }
621         }
622     }]);
623
624     function updateComment(comment, resp, $timeout, isDelete) {
625         comment.text = resp.comment.text;
626         comment.updated = resp.comment.updated;
627         comment.updated_by = resp.comment.updated_by;
628         comment.active = resp.comment.active;
629         if (isDelete && !resp.comment.active) {
630             comment.html = trans('entities.comment_deleted');
631         } else {
632             comment.html = resp.comment.html;
633         }
634         if (!$timeout) {
635             return;
636         }
637         comment.is_hidden = true;
638         $timeout(function() {
639             comment.is_hidden = false;
640         });
641     }
642
643     function isCommentOpSuccess(resp) {
644         if (resp && resp.data && resp.data.status === 'success') {
645             return true;
646         }
647         return false;
648     }
649 };