]> BookStack Code Mirror - bookstack/blob - resources/assets/js/controllers.js
Migrated attachment manager to vue
[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     // Controller used to reply to and add new comments
149     ngApp.controller('CommentReplyController', ['$scope', '$http', '$timeout', function ($scope, $http, $timeout) {
150         const MarkdownIt = require("markdown-it");
151         const md = new MarkdownIt({html: true});
152         let vm = this;
153
154         vm.saveComment = function () {
155             let pageId = $scope.comment.pageId || $scope.pageId;
156             let comment = $scope.comment.text;
157             if (!comment) {
158                 return events.emit('warning', trans('errors.empty_comment'));
159             }
160             let commentHTML = md.render($scope.comment.text);
161             let serviceUrl = `/ajax/page/${pageId}/comment/`;
162             let httpMethod = 'post';
163             let reqObj = {
164                 text: comment,
165                 html: commentHTML
166             };
167
168             if ($scope.isEdit === true) {
169                 // this will be set when editing the comment.
170                 serviceUrl = `/ajax/page/${pageId}/comment/${$scope.comment.id}`;
171                 httpMethod = 'put';
172             } else if ($scope.isReply === true) {
173                 // if its reply, get the parent comment id
174                 reqObj.parent_id = $scope.parentId;
175             }
176             $http[httpMethod](window.baseUrl(serviceUrl), reqObj).then(resp => {
177                 if (!isCommentOpSuccess(resp)) {
178                      return;
179                 }
180                 // hide the comments first, and then retrigger the refresh
181                 if ($scope.isEdit) {
182                     updateComment($scope.comment, resp.data);
183                     $scope.$emit('evt.comment-success', $scope.comment.id);
184                 } else {
185                     $scope.comment.text = '';
186                     if ($scope.isReply === true && $scope.parent.sub_comments) {
187                         $scope.parent.sub_comments.push(resp.data.comment);
188                     } else {
189                         $scope.$emit('evt.new-comment', resp.data.comment);
190                     }
191                     $scope.$emit('evt.comment-success', null, true);
192                 }
193                 $scope.comment.is_hidden = true;
194                 $timeout(function() {
195                     $scope.comment.is_hidden = false;
196                 });
197
198                 events.emit('success', trans(resp.data.message));
199
200             }, checkError);
201
202         };
203
204         function checkError(response) {
205             let msg = null;
206             if (isCommentOpSuccess(response)) {
207                 // all good
208                 return;
209             } else if (response.data) {
210                 msg = response.data.message;
211             } else {
212                 msg = trans('errors.comment_add');
213             }
214             if (msg) {
215                 events.emit('success', msg);
216             }
217         }
218     }]);
219
220     // Controller used to delete comments
221     ngApp.controller('CommentDeleteController', ['$scope', '$http', '$timeout', function ($scope, $http, $timeout) {
222         let vm = this;
223
224         vm.delete = function(comment) {
225             $http.delete(window.baseUrl(`/ajax/comment/${comment.id}`)).then(resp => {
226                 if (!isCommentOpSuccess(resp)) {
227                     return;
228                 }
229                 updateComment(comment, resp.data, $timeout, true);
230             }, function (resp) {
231                 if (isCommentOpSuccess(resp)) {
232                     events.emit('success', trans('entities.comment_deleted'));
233                 } else {
234                     events.emit('error', trans('error.comment_delete'));
235                 }
236             });
237         };
238     }]);
239
240     // Controller used to fetch all comments for a page
241     ngApp.controller('CommentListController', ['$scope', '$http', '$timeout', '$location', function ($scope, $http, $timeout, $location) {
242         let vm = this;
243         $scope.errors = {};
244         // keep track of comment levels
245         $scope.level = 1;
246         vm.totalCommentsStr = trans('entities.comments_loading');
247         vm.permissions = {};
248         vm.trans = window.trans;
249
250         $scope.$on('evt.new-comment', function (event, comment) {
251             // add the comment to the comment list.
252             vm.comments.push(comment);
253             ++vm.totalComments;
254             setTotalCommentMsg();
255             event.stopPropagation();
256             event.preventDefault();
257         });
258
259         vm.canEditDelete = function (comment, prop) {
260             if (!comment.active) {
261                 return false;
262             }
263             let propAll = prop + '_all';
264             let propOwn = prop + '_own';
265
266             if (vm.permissions[propAll]) {
267                 return true;
268             }
269
270             if (vm.permissions[propOwn] && comment.created_by.id === vm.current_user_id) {
271                 return true;
272             }
273
274             return false;
275         };
276
277         vm.canComment = function () {
278             return vm.permissions.comment_create;
279         };
280
281         // check if there are is any direct linking
282         let linkedCommentId = $location.search().cm;
283
284         $timeout(function() {
285             $http.get(window.baseUrl(`/ajax/page/${$scope.pageId}/comments/`)).then(resp => {
286                 if (!isCommentOpSuccess(resp)) {
287                     // just show that no comments are available.
288                     vm.totalComments = 0;
289                     setTotalCommentMsg();
290                     return;
291                 }
292                 vm.comments = resp.data.comments;
293                 vm.totalComments = +resp.data.total;
294                 vm.permissions = resp.data.permissions;
295                 vm.current_user_id = resp.data.user_id;
296                 setTotalCommentMsg();
297                 if (!linkedCommentId) {
298                     return;
299                 }
300                 $timeout(function() {
301                     // wait for the UI to render.
302                     focusLinkedComment(linkedCommentId);
303                 });
304             }, checkError);
305         });
306
307         function setTotalCommentMsg () {
308             if (vm.totalComments === 0) {
309                 vm.totalCommentsStr = trans('entities.no_comments');
310             } else if (vm.totalComments === 1) {
311                 vm.totalCommentsStr = trans('entities.one_comment');
312             } else {
313                 vm.totalCommentsStr = trans('entities.x_comments', {
314                     numComments: vm.totalComments
315                 });
316             }
317         }
318
319         function focusLinkedComment(linkedCommentId) {
320             let comment = angular.element('#' + linkedCommentId);
321             if (comment.length === 0) {
322                 return;
323             }
324
325             window.setupPageShow.goToText(linkedCommentId);
326         }
327
328         function checkError(response) {
329             let msg = null;
330             if (isCommentOpSuccess(response)) {
331                 // all good
332                 return;
333             } else if (response.data) {
334                 msg = response.data.message;
335             } else {
336                 msg = trans('errors.comment_list');
337             }
338             if (msg) {
339                 events.emit('success', msg);
340             }
341         }
342     }]);
343
344     function updateComment(comment, resp, $timeout, isDelete) {
345         comment.text = resp.comment.text;
346         comment.updated = resp.comment.updated;
347         comment.updated_by = resp.comment.updated_by;
348         comment.active = resp.comment.active;
349         if (isDelete && !resp.comment.active) {
350             comment.html = trans('entities.comment_deleted');
351         } else {
352             comment.html = resp.comment.html;
353         }
354         if (!$timeout) {
355             return;
356         }
357         comment.is_hidden = true;
358         $timeout(function() {
359             comment.is_hidden = false;
360         });
361     }
362
363     function isCommentOpSuccess(resp) {
364         if (resp && resp.data && resp.data.status === 'success') {
365             return true;
366         }
367         return false;
368     }
369 };