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