commentstabview.js 13 KB

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