]> BookStack Code Mirror - bookstack/blob - resources/assets/js/controllers.js
Started vueifying tag system
[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             // TODO - Delete
161
162         }]);
163
164
165     ngApp.controller('PageAttachmentController', ['$scope', '$http', '$attrs',
166         function ($scope, $http, $attrs) {
167
168             const pageId = $scope.uploadedTo = $attrs.pageId;
169             let currentOrder = '';
170             $scope.files = [];
171             $scope.editFile = false;
172             $scope.file = getCleanFile();
173             $scope.errors = {
174                 link: {},
175                 edit: {}
176             };
177
178             function getCleanFile() {
179                 return {
180                     page_id: pageId
181                 };
182             }
183
184             // Angular-UI-Sort options
185             $scope.sortOptions = {
186                 handle: '.handle',
187                 items: '> tr',
188                 containment: "parent",
189                 axis: "y",
190                 stop: sortUpdate,
191             };
192
193             /**
194              * Event listener for sort changes.
195              * Updates the file ordering on the server.
196              * @param event
197              * @param ui
198              */
199             function sortUpdate(event, ui) {
200                 let newOrder = $scope.files.map(file => {return file.id}).join(':');
201                 if (newOrder === currentOrder) return;
202
203                 currentOrder = newOrder;
204                 $http.put(window.baseUrl(`/attachments/sort/page/${pageId}`), {files: $scope.files}).then(resp => {
205                     events.emit('success', resp.data.message);
206                 }, checkError('sort'));
207             }
208
209             /**
210              * Used by dropzone to get the endpoint to upload to.
211              * @returns {string}
212              */
213             $scope.getUploadUrl = function (file) {
214                 let suffix = (typeof file !== 'undefined') ? `/${file.id}` : '';
215                 return window.baseUrl(`/attachments/upload${suffix}`);
216             };
217
218             /**
219              * Get files for the current page from the server.
220              */
221             function getFiles() {
222                 let url = window.baseUrl(`/attachments/get/page/${pageId}`);
223                 $http.get(url).then(resp => {
224                     $scope.files = resp.data;
225                     currentOrder = resp.data.map(file => {return file.id}).join(':');
226                 }, checkError('get'));
227             }
228             getFiles();
229
230             /**
231              * Runs on file upload, Adds an file to local file list
232              * and shows a success message to the user.
233              * @param file
234              * @param data
235              */
236             $scope.uploadSuccess = function (file, data) {
237                 $scope.$apply(() => {
238                     $scope.files.push(data);
239                 });
240                 events.emit('success', trans('entities.attachments_file_uploaded'));
241             };
242
243             /**
244              * Upload and overwrite an existing file.
245              * @param file
246              * @param data
247              */
248             $scope.uploadSuccessUpdate = function (file, data) {
249                 $scope.$apply(() => {
250                     let search = filesIndexOf(data);
251                     if (search !== -1) $scope.files[search] = data;
252
253                     if ($scope.editFile) {
254                         $scope.editFile = angular.copy(data);
255                         data.link = '';
256                     }
257                 });
258                 events.emit('success', trans('entities.attachments_file_updated'));
259             };
260
261             /**
262              * Delete a file from the server and, on success, the local listing.
263              * @param file
264              */
265             $scope.deleteFile = function(file) {
266                 if (!file.deleting) {
267                     file.deleting = true;
268                     return;
269                 }
270                   $http.delete(window.baseUrl(`/attachments/${file.id}`)).then(resp => {
271                       events.emit('success', resp.data.message);
272                       $scope.files.splice($scope.files.indexOf(file), 1);
273                   }, checkError('delete'));
274             };
275
276             /**
277              * Attach a link to a page.
278              * @param file
279              */
280             $scope.attachLinkSubmit = function(file) {
281                 file.uploaded_to = pageId;
282                 $http.post(window.baseUrl('/attachments/link'), file).then(resp => {
283                     $scope.files.push(resp.data);
284                     events.emit('success', trans('entities.attachments_link_attached'));
285                     $scope.file = getCleanFile();
286                 }, checkError('link'));
287             };
288
289             /**
290              * Start the edit mode for a file.
291              * @param file
292              */
293             $scope.startEdit = function(file) {
294                 $scope.editFile = angular.copy(file);
295                 $scope.editFile.link = (file.external) ? file.path : '';
296             };
297
298             /**
299              * Cancel edit mode
300              */
301             $scope.cancelEdit = function() {
302                 $scope.editFile = false;
303             };
304
305             /**
306              * Update the name and link of a file.
307              * @param file
308              */
309             $scope.updateFile = function(file) {
310                 $http.put(window.baseUrl(`/attachments/${file.id}`), file).then(resp => {
311                     let search = filesIndexOf(resp.data);
312                     if (search !== -1) $scope.files[search] = resp.data;
313
314                     if ($scope.editFile && !file.external) {
315                         $scope.editFile.link = '';
316                     }
317                     $scope.editFile = false;
318                     events.emit('success', trans('entities.attachments_updated_success'));
319                 }, checkError('edit'));
320             };
321
322             /**
323              * Get the url of a file.
324              */
325             $scope.getFileUrl = function(file) {
326                 return window.baseUrl('/attachments/' + file.id);
327             };
328
329             /**
330              * Search the local files via another file object.
331              * Used to search via object copies.
332              * @param file
333              * @returns int
334              */
335             function filesIndexOf(file) {
336                 for (let i = 0; i < $scope.files.length; i++) {
337                     if ($scope.files[i].id == file.id) return i;
338                 }
339                 return -1;
340             }
341
342             /**
343              * Check for an error response in a ajax request.
344              * @param errorGroupName
345              */
346             function checkError(errorGroupName) {
347                 $scope.errors[errorGroupName] = {};
348                 return function(response) {
349                     if (typeof response.data !== 'undefined' && typeof response.data.error !== 'undefined') {
350                         events.emit('error', response.data.error);
351                     }
352                     if (typeof response.data !== 'undefined' && typeof response.data.validation !== 'undefined') {
353                         $scope.errors[errorGroupName] = response.data.validation;
354                         console.log($scope.errors[errorGroupName])
355                     }
356                 }
357             }
358
359         }]);
360
361     // Controller used to reply to and add new comments
362     ngApp.controller('CommentReplyController', ['$scope', '$http', '$timeout', function ($scope, $http, $timeout) {
363         const MarkdownIt = require("markdown-it");
364         const md = new MarkdownIt({html: true});
365         let vm = this;
366
367         vm.saveComment = function () {
368             let pageId = $scope.comment.pageId || $scope.pageId;
369             let comment = $scope.comment.text;
370             if (!comment) {
371                 return events.emit('warning', trans('errors.empty_comment'));
372             }
373             let commentHTML = md.render($scope.comment.text);
374             let serviceUrl = `/ajax/page/${pageId}/comment/`;
375             let httpMethod = 'post';
376             let reqObj = {
377                 text: comment,
378                 html: commentHTML
379             };
380
381             if ($scope.isEdit === true) {
382                 // this will be set when editing the comment.
383                 serviceUrl = `/ajax/page/${pageId}/comment/${$scope.comment.id}`;
384                 httpMethod = 'put';
385             } else if ($scope.isReply === true) {
386                 // if its reply, get the parent comment id
387                 reqObj.parent_id = $scope.parentId;
388             }
389             $http[httpMethod](window.baseUrl(serviceUrl), reqObj).then(resp => {
390                 if (!isCommentOpSuccess(resp)) {
391                      return;
392                 }
393                 // hide the comments first, and then retrigger the refresh
394                 if ($scope.isEdit) {
395                     updateComment($scope.comment, resp.data);
396                     $scope.$emit('evt.comment-success', $scope.comment.id);
397                 } else {
398                     $scope.comment.text = '';
399                     if ($scope.isReply === true && $scope.parent.sub_comments) {
400                         $scope.parent.sub_comments.push(resp.data.comment);
401                     } else {
402                         $scope.$emit('evt.new-comment', resp.data.comment);
403                     }
404                     $scope.$emit('evt.comment-success', null, true);
405                 }
406                 $scope.comment.is_hidden = true;
407                 $timeout(function() {
408                     $scope.comment.is_hidden = false;
409                 });
410
411                 events.emit('success', trans(resp.data.message));
412
413             }, checkError);
414
415         };
416
417         function checkError(response) {
418             let msg = null;
419             if (isCommentOpSuccess(response)) {
420                 // all good
421                 return;
422             } else if (response.data) {
423                 msg = response.data.message;
424             } else {
425                 msg = trans('errors.comment_add');
426             }
427             if (msg) {
428                 events.emit('success', msg);
429             }
430         }
431     }]);
432
433     // Controller used to delete comments
434     ngApp.controller('CommentDeleteController', ['$scope', '$http', '$timeout', function ($scope, $http, $timeout) {
435         let vm = this;
436
437         vm.delete = function(comment) {
438             $http.delete(window.baseUrl(`/ajax/comment/${comment.id}`)).then(resp => {
439                 if (!isCommentOpSuccess(resp)) {
440                     return;
441                 }
442                 updateComment(comment, resp.data, $timeout, true);
443             }, function (resp) {
444                 if (isCommentOpSuccess(resp)) {
445                     events.emit('success', trans('entities.comment_deleted'));
446                 } else {
447                     events.emit('error', trans('error.comment_delete'));
448                 }
449             });
450         };
451     }]);
452
453     // Controller used to fetch all comments for a page
454     ngApp.controller('CommentListController', ['$scope', '$http', '$timeout', '$location', function ($scope, $http, $timeout, $location) {
455         let vm = this;
456         $scope.errors = {};
457         // keep track of comment levels
458         $scope.level = 1;
459         vm.totalCommentsStr = trans('entities.comments_loading');
460         vm.permissions = {};
461         vm.trans = window.trans;
462
463         $scope.$on('evt.new-comment', function (event, comment) {
464             // add the comment to the comment list.
465             vm.comments.push(comment);
466             ++vm.totalComments;
467             setTotalCommentMsg();
468             event.stopPropagation();
469             event.preventDefault();
470         });
471
472         vm.canEditDelete = function (comment, prop) {
473             if (!comment.active) {
474                 return false;
475             }
476             let propAll = prop + '_all';
477             let propOwn = prop + '_own';
478
479             if (vm.permissions[propAll]) {
480                 return true;
481             }
482
483             if (vm.permissions[propOwn] && comment.created_by.id === vm.current_user_id) {
484                 return true;
485             }
486
487             return false;
488         };
489
490         vm.canComment = function () {
491             return vm.permissions.comment_create;
492         };
493
494         // check if there are is any direct linking
495         let linkedCommentId = $location.search().cm;
496
497         $timeout(function() {
498             $http.get(window.baseUrl(`/ajax/page/${$scope.pageId}/comments/`)).then(resp => {
499                 if (!isCommentOpSuccess(resp)) {
500                     // just show that no comments are available.
501                     vm.totalComments = 0;
502                     setTotalCommentMsg();
503                     return;
504                 }
505                 vm.comments = resp.data.comments;
506                 vm.totalComments = +resp.data.total;
507                 vm.permissions = resp.data.permissions;
508                 vm.current_user_id = resp.data.user_id;
509                 setTotalCommentMsg();
510                 if (!linkedCommentId) {
511                     return;
512                 }
513                 $timeout(function() {
514                     // wait for the UI to render.
515                     focusLinkedComment(linkedCommentId);
516                 });
517             }, checkError);
518         });
519
520         function setTotalCommentMsg () {
521             if (vm.totalComments === 0) {
522                 vm.totalCommentsStr = trans('entities.no_comments');
523             } else if (vm.totalComments === 1) {
524                 vm.totalCommentsStr = trans('entities.one_comment');
525             } else {
526                 vm.totalCommentsStr = trans('entities.x_comments', {
527                     numComments: vm.totalComments
528                 });
529             }
530         }
531
532         function focusLinkedComment(linkedCommentId) {
533             let comment = angular.element('#' + linkedCommentId);
534             if (comment.length === 0) {
535                 return;
536             }
537
538             window.setupPageShow.goToText(linkedCommentId);
539         }
540
541         function checkError(response) {
542             let msg = null;
543             if (isCommentOpSuccess(response)) {
544                 // all good
545                 return;
546             } else if (response.data) {
547                 msg = response.data.message;
548             } else {
549                 msg = trans('errors.comment_list');
550             }
551             if (msg) {
552                 events.emit('success', msg);
553             }
554         }
555     }]);
556
557     function updateComment(comment, resp, $timeout, isDelete) {
558         comment.text = resp.comment.text;
559         comment.updated = resp.comment.updated;
560         comment.updated_by = resp.comment.updated_by;
561         comment.active = resp.comment.active;
562         if (isDelete && !resp.comment.active) {
563             comment.html = trans('entities.comment_deleted');
564         } else {
565             comment.html = resp.comment.html;
566         }
567         if (!$timeout) {
568             return;
569         }
570         comment.is_hidden = true;
571         $timeout(function() {
572             comment.is_hidden = false;
573         });
574     }
575
576     function isCommentOpSuccess(resp) {
577         if (resp && resp.data && resp.data.status === 'success') {
578             return true;
579         }
580         return false;
581     }
582 };