commentstabview.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. /*
  2. * Copyright (c) 2016
  3. *
  4. * This file is licensed under the Affero General Public License version 3
  5. * or later.
  6. *
  7. * See the COPYING-README file.
  8. *
  9. */
  10. /* global Handlebars, escapeHTML */
  11. (function(OC, OCA) {
  12. var TEMPLATE =
  13. '<ul class="comments">' +
  14. '</ul>' +
  15. '<div class="empty hidden">{{emptyResultLabel}}</div>' +
  16. '<input type="button" class="showMore hidden" value="{{moreLabel}}"' +
  17. ' name="show-more" id="show-more" />' +
  18. '<div class="loading hidden" style="height: 50px"></div>';
  19. var EDIT_COMMENT_TEMPLATE =
  20. '<div class="newCommentRow comment" data-id="{{id}}">' +
  21. ' <div class="authorRow">' +
  22. ' {{#if avatarEnabled}}' +
  23. ' <div class="avatar" data-username="{{actorId}}"></div>' +
  24. ' {{/if}}' +
  25. ' <div class="author">{{actorDisplayName}}</div>' +
  26. '{{#if isEditMode}}' +
  27. ' <a href="#" class="action delete icon icon-delete has-tooltip" title="{{deleteTooltip}}"></a>' +
  28. '{{/if}}' +
  29. ' </div>' +
  30. ' <form class="newCommentForm">' +
  31. ' <textarea class="message" placeholder="{{newMessagePlaceholder}}">{{{message}}}</textarea>' +
  32. ' <input class="submit" type="submit" value="{{submitText}}" />' +
  33. '{{#if isEditMode}}' +
  34. ' <input class="cancel" type="button" value="{{cancelText}}" />' +
  35. '{{/if}}' +
  36. ' <div class="submitLoading icon-loading-small hidden"></div>'+
  37. ' </form>' +
  38. '</div>';
  39. var COMMENT_TEMPLATE =
  40. '<li class="comment{{#if isUnread}} unread{{/if}}{{#if isLong}} collapsed{{/if}}" data-id="{{id}}">' +
  41. ' <div class="authorRow">' +
  42. ' {{#if avatarEnabled}}' +
  43. ' <div class="avatar" {{#if actorId}}data-username="{{actorId}}"{{/if}}> </div>' +
  44. ' {{/if}}' +
  45. ' <div class="author">{{actorDisplayName}}</div>' +
  46. '{{#if isUserAuthor}}' +
  47. ' <a href="#" class="action edit icon icon-rename has-tooltip" title="{{editTooltip}}"></a>' +
  48. '{{/if}}' +
  49. ' <div class="date has-tooltip" title="{{altDate}}">{{date}}</div>' +
  50. ' </div>' +
  51. ' <div class="message">{{{formattedMessage}}}</div>' +
  52. '{{#if isLong}}' +
  53. ' <div class="message-overlay"></div>' +
  54. '{{/if}}' +
  55. '</li>';
  56. /**
  57. * @memberof OCA.Comments
  58. */
  59. var CommentsTabView = OCA.Files.DetailTabView.extend(
  60. /** @lends OCA.Comments.CommentsTabView.prototype */ {
  61. id: 'commentsTabView',
  62. className: 'tab commentsTabView',
  63. events: {
  64. 'submit .newCommentForm': '_onSubmitComment',
  65. 'click .showMore': '_onClickShowMore',
  66. 'click .action.edit': '_onClickEditComment',
  67. 'click .action.delete': '_onClickDeleteComment',
  68. 'click .cancel': '_onClickCloseComment',
  69. 'click .comment': '_onClickComment'
  70. },
  71. _commentMaxLength: 1000,
  72. initialize: function() {
  73. OCA.Files.DetailTabView.prototype.initialize.apply(this, arguments);
  74. this.collection = new OCA.Comments.CommentCollection();
  75. this.collection.on('request', this._onRequest, this);
  76. this.collection.on('sync', this._onEndRequest, this);
  77. this.collection.on('add', this._onAddModel, this);
  78. this._avatarsEnabled = !!OC.config.enable_avatars;
  79. this._commentMaxThreshold = this._commentMaxLength * 0.9;
  80. // TODO: error handling
  81. _.bindAll(this, '_onTypeComment');
  82. },
  83. template: function(params) {
  84. if (!this._template) {
  85. this._template = Handlebars.compile(TEMPLATE);
  86. }
  87. var currentUser = OC.getCurrentUser();
  88. return this._template(_.extend({
  89. avatarEnabled: this._avatarsEnabled,
  90. actorId: currentUser.uid,
  91. actorDisplayName: currentUser.displayName
  92. }, params));
  93. },
  94. editCommentTemplate: function(params) {
  95. if (!this._editCommentTemplate) {
  96. this._editCommentTemplate = Handlebars.compile(EDIT_COMMENT_TEMPLATE);
  97. }
  98. var currentUser = OC.getCurrentUser();
  99. return this._editCommentTemplate(_.extend({
  100. avatarEnabled: this._avatarsEnabled,
  101. actorId: currentUser.uid,
  102. actorDisplayName: currentUser.displayName,
  103. newMessagePlaceholder: t('comments', 'Type in a new comment...'),
  104. deleteTooltip: t('comments', 'Delete comment'),
  105. submitText: t('comments', 'Post'),
  106. cancelText: t('comments', 'Cancel')
  107. }, params));
  108. },
  109. commentTemplate: function(params) {
  110. if (!this._commentTemplate) {
  111. this._commentTemplate = Handlebars.compile(COMMENT_TEMPLATE);
  112. }
  113. params = _.extend({
  114. avatarEnabled: this._avatarsEnabled,
  115. editTooltip: t('comments', 'Edit comment'),
  116. isUserAuthor: OC.getCurrentUser().uid === params.actorId,
  117. isLong: this._isLong(params.message)
  118. }, params);
  119. if (params.actorType === 'deleted_users') {
  120. // makes the avatar a X
  121. params.actorId = null;
  122. params.actorDisplayName = t('comments', '[Deleted user]');
  123. }
  124. return this._commentTemplate(params);
  125. },
  126. getLabel: function() {
  127. return t('comments', 'Comments');
  128. },
  129. setFileInfo: function(fileInfo) {
  130. if (fileInfo) {
  131. this.model = fileInfo;
  132. this.render();
  133. this.collection.setObjectId(fileInfo.id);
  134. // reset to first page
  135. this.collection.reset([], {silent: true});
  136. this.nextPage();
  137. } else {
  138. this.model = null;
  139. this.render();
  140. this.collection.reset();
  141. }
  142. },
  143. render: function() {
  144. this.$el.html(this.template({
  145. emptyResultLabel: t('comments', 'No other comments available'),
  146. moreLabel: t('comments', 'More comments...')
  147. }));
  148. this.$el.find('.comments').before(this.editCommentTemplate({}));
  149. this.$el.find('.has-tooltip').tooltip();
  150. this.$container = this.$el.find('ul.comments');
  151. if (this._avatarsEnabled) {
  152. this.$el.find('.avatar').avatar(OC.getCurrentUser().uid, 28);
  153. }
  154. this.delegateEvents();
  155. this.$el.find('textarea').on('keydown input change', this._onTypeComment);
  156. },
  157. _formatItem: function(commentModel) {
  158. var timestamp = new Date(commentModel.get('creationDateTime')).getTime();
  159. var data = _.extend({
  160. date: OC.Util.relativeModifiedDate(timestamp),
  161. altDate: OC.Util.formatDate(timestamp),
  162. formattedMessage: this._formatMessage(commentModel.get('message'))
  163. }, commentModel.attributes);
  164. return data;
  165. },
  166. _toggleLoading: function(state) {
  167. this._loading = state;
  168. this.$el.find('.loading').toggleClass('hidden', !state);
  169. },
  170. _onRequest: function(type) {
  171. if (type === 'REPORT') {
  172. this._toggleLoading(true);
  173. this.$el.find('.showMore').addClass('hidden');
  174. }
  175. },
  176. _onEndRequest: function(type) {
  177. var fileInfoModel = this.model;
  178. this._toggleLoading(false);
  179. this.$el.find('.empty').toggleClass('hidden', !!this.collection.length);
  180. this.$el.find('.showMore').toggleClass('hidden', !this.collection.hasMoreResults());
  181. if (type !== 'REPORT') {
  182. return;
  183. }
  184. // find first unread comment
  185. var firstUnreadComment = this.collection.findWhere({isUnread: true});
  186. if (firstUnreadComment) {
  187. // update read marker
  188. this.collection.updateReadMarker(
  189. null,
  190. {
  191. success: function() {
  192. fileInfoModel.set('commentsUnread', 0);
  193. }
  194. }
  195. );
  196. }
  197. },
  198. _onAddModel: function(model, collection, options) {
  199. var $el = $(this.commentTemplate(this._formatItem(model)));
  200. if (!_.isUndefined(options.at) && collection.length > 1) {
  201. this.$container.find('li').eq(options.at).before($el);
  202. } else {
  203. this.$container.append($el);
  204. }
  205. this._postRenderItem($el);
  206. },
  207. _postRenderItem: function($el) {
  208. $el.find('.has-tooltip').tooltip();
  209. if(this._avatarsEnabled) {
  210. $el.find('.avatar').each(function() {
  211. var $this = $(this);
  212. $this.avatar($this.attr('data-username'), 28);
  213. });
  214. }
  215. },
  216. /**
  217. * Convert a message to be displayed in HTML,
  218. * converts newlines to <br> tags.
  219. */
  220. _formatMessage: function(message) {
  221. return escapeHTML(message).replace(/\n/g, '<br/>');
  222. },
  223. nextPage: function() {
  224. if (this._loading || !this.collection.hasMoreResults()) {
  225. return;
  226. }
  227. this.collection.fetchNext();
  228. },
  229. _onClickEditComment: function(ev) {
  230. ev.preventDefault();
  231. var $comment = $(ev.target).closest('.comment');
  232. var commentId = $comment.data('id');
  233. var commentToEdit = this.collection.get(commentId);
  234. var $formRow = $(this.editCommentTemplate(_.extend({
  235. isEditMode: true,
  236. submitText: t('comments', 'Save')
  237. }, commentToEdit.attributes)));
  238. $comment.addClass('hidden').removeClass('collapsed');
  239. // spawn form
  240. $comment.after($formRow);
  241. $formRow.data('commentEl', $comment);
  242. $formRow.find('textarea').on('keydown input change', this._onTypeComment);
  243. // copy avatar element from original to avoid flickering
  244. $formRow.find('.avatar').replaceWith($comment.find('.avatar').clone());
  245. $formRow.find('.has-tooltip').tooltip();
  246. return false;
  247. },
  248. _onTypeComment: function(ev) {
  249. var $field = $(ev.target);
  250. var len = $field.val().length;
  251. var $submitButton = $field.data('submitButtonEl');
  252. if (!$submitButton) {
  253. $submitButton = $field.closest('form').find('.submit');
  254. $field.data('submitButtonEl', $submitButton);
  255. }
  256. $field.tooltip('hide');
  257. if (len > this._commentMaxThreshold) {
  258. $field.attr('data-original-title', t('comments', 'Allowed characters {count} of {max}', {count: len, max: this._commentMaxLength}));
  259. $field.tooltip({trigger: 'manual'});
  260. $field.tooltip('show');
  261. $field.addClass('error');
  262. }
  263. var limitExceeded = (len > this._commentMaxLength);
  264. $field.toggleClass('error', limitExceeded);
  265. $submitButton.prop('disabled', limitExceeded);
  266. //submits form on ctrl+Enter or cmd+Enter
  267. if (ev.keyCode === 13 && (ev.ctrlKey || ev.metaKey)) {
  268. $submitButton.click();
  269. }
  270. },
  271. _onClickComment: function(ev) {
  272. var $row = $(ev.target);
  273. if (!$row.is('.comment')) {
  274. $row = $row.closest('.comment');
  275. }
  276. $row.removeClass('collapsed');
  277. },
  278. _onClickCloseComment: function(ev) {
  279. ev.preventDefault();
  280. var $row = $(ev.target).closest('.comment');
  281. $row.data('commentEl').removeClass('hidden');
  282. $row.remove();
  283. return false;
  284. },
  285. _onClickDeleteComment: function(ev) {
  286. ev.preventDefault();
  287. var $comment = $(ev.target).closest('.comment');
  288. var commentId = $comment.data('id');
  289. var $loading = $comment.find('.submitLoading');
  290. $comment.addClass('disabled');
  291. $loading.removeClass('hidden');
  292. this.collection.get(commentId).destroy({
  293. success: function() {
  294. $comment.data('commentEl').remove();
  295. $comment.remove();
  296. },
  297. error: function() {
  298. $loading.addClass('hidden');
  299. $comment.removeClass('disabled');
  300. OC.Notification.showTemporary(t('comments', 'Error occurred while retrieving comment with id {id}', {id: commentId}));
  301. }
  302. });
  303. return false;
  304. },
  305. _onClickShowMore: function(ev) {
  306. ev.preventDefault();
  307. this.nextPage();
  308. },
  309. _onSubmitComment: function(e) {
  310. var self = this;
  311. var $form = $(e.target);
  312. var commentId = $form.closest('.comment').data('id');
  313. var currentUser = OC.getCurrentUser();
  314. var $submit = $form.find('.submit');
  315. var $loading = $form.find('.submitLoading');
  316. var $textArea = $form.find('textarea');
  317. var message = $textArea.val().trim();
  318. e.preventDefault();
  319. if (!message.length || message.length > this._commentMaxLength) {
  320. return;
  321. }
  322. $textArea.prop('disabled', true);
  323. $submit.addClass('hidden');
  324. $loading.removeClass('hidden');
  325. if (commentId) {
  326. // edit mode
  327. var comment = this.collection.get(commentId);
  328. comment.save({
  329. message: $textArea.val()
  330. }, {
  331. success: function(model) {
  332. var $row = $form.closest('.comment');
  333. $submit.removeClass('hidden');
  334. $loading.addClass('hidden');
  335. $row.data('commentEl')
  336. .removeClass('hidden')
  337. .find('.message')
  338. .html(self._formatMessage(model.get('message')));
  339. $row.remove();
  340. },
  341. error: function() {
  342. $submit.removeClass('hidden');
  343. $loading.addClass('hidden');
  344. $textArea.prop('disabled', false);
  345. OC.Notification.showTemporary(t('comments', 'Error occurred while updating comment with id {id}', {id: commentId}));
  346. }
  347. });
  348. } else {
  349. this.collection.create({
  350. actorId: currentUser.uid,
  351. actorDisplayName: currentUser.displayName,
  352. actorType: 'users',
  353. verb: 'comment',
  354. message: $textArea.val(),
  355. creationDateTime: (new Date()).toUTCString()
  356. }, {
  357. at: 0,
  358. // wait for real creation before adding
  359. wait: true,
  360. success: function() {
  361. $submit.removeClass('hidden');
  362. $loading.addClass('hidden');
  363. $textArea.val('').prop('disabled', false);
  364. },
  365. error: function() {
  366. $submit.removeClass('hidden');
  367. $loading.addClass('hidden');
  368. $textArea.prop('disabled', false);
  369. OC.Notification.showTemporary(t('comments', 'Error occurred while posting comment'));
  370. }
  371. });
  372. }
  373. return false;
  374. },
  375. /**
  376. * Returns whether the given message is long and needs
  377. * collapsing
  378. */
  379. _isLong: function(message) {
  380. return message.length > 250 || (message.match(/\n/g) || []).length > 1;
  381. }
  382. });
  383. OCA.Comments.CommentsTabView = CommentsTabView;
  384. })(OC, OCA);