commentstabview.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  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 live-relative-timestamp" data-timestamp="{{timestamp}}" 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. timestamp: timestamp,
  162. date: OC.Util.relativeModifiedDate(timestamp),
  163. altDate: OC.Util.formatDate(timestamp),
  164. formattedMessage: this._formatMessage(commentModel.get('message'))
  165. }, commentModel.attributes);
  166. return data;
  167. },
  168. _toggleLoading: function(state) {
  169. this._loading = state;
  170. this.$el.find('.loading').toggleClass('hidden', !state);
  171. },
  172. _onRequest: function(type) {
  173. if (type === 'REPORT') {
  174. this._toggleLoading(true);
  175. this.$el.find('.showMore').addClass('hidden');
  176. }
  177. },
  178. _onEndRequest: function(type) {
  179. var fileInfoModel = this.model;
  180. this._toggleLoading(false);
  181. this.$el.find('.emptycontent').toggleClass('hidden', !!this.collection.length);
  182. this.$el.find('.showMore').toggleClass('hidden', !this.collection.hasMoreResults());
  183. if (type !== 'REPORT') {
  184. return;
  185. }
  186. // find first unread comment
  187. var firstUnreadComment = this.collection.findWhere({isUnread: true});
  188. if (firstUnreadComment) {
  189. // update read marker
  190. this.collection.updateReadMarker(
  191. null,
  192. {
  193. success: function() {
  194. fileInfoModel.set('commentsUnread', 0);
  195. }
  196. }
  197. );
  198. }
  199. },
  200. _onAddModel: function(model, collection, options) {
  201. var $el = $(this.commentTemplate(this._formatItem(model)));
  202. if (!_.isUndefined(options.at) && collection.length > 1) {
  203. this.$container.find('li').eq(options.at).before($el);
  204. } else {
  205. this.$container.append($el);
  206. }
  207. this._postRenderItem($el);
  208. },
  209. _postRenderItem: function($el) {
  210. $el.find('.has-tooltip').tooltip();
  211. if(this._avatarsEnabled) {
  212. $el.find('.avatar').each(function() {
  213. var $this = $(this);
  214. $this.avatar($this.attr('data-username'), 32);
  215. });
  216. }
  217. },
  218. /**
  219. * Convert a message to be displayed in HTML,
  220. * converts newlines to <br> tags.
  221. */
  222. _formatMessage: function(message) {
  223. return escapeHTML(message).replace(/\n/g, '<br/>');
  224. },
  225. nextPage: function() {
  226. if (this._loading || !this.collection.hasMoreResults()) {
  227. return;
  228. }
  229. this.collection.fetchNext();
  230. },
  231. _onClickEditComment: function(ev) {
  232. ev.preventDefault();
  233. var $comment = $(ev.target).closest('.comment');
  234. var commentId = $comment.data('id');
  235. var commentToEdit = this.collection.get(commentId);
  236. var $formRow = $(this.editCommentTemplate(_.extend({
  237. isEditMode: true,
  238. submitText: t('comments', 'Save')
  239. }, commentToEdit.attributes)));
  240. $comment.addClass('hidden').removeClass('collapsed');
  241. // spawn form
  242. $comment.after($formRow);
  243. $formRow.data('commentEl', $comment);
  244. $formRow.find('textarea').on('keydown input change', this._onTypeComment);
  245. // copy avatar element from original to avoid flickering
  246. $formRow.find('.avatar').replaceWith($comment.find('.avatar').clone());
  247. $formRow.find('.has-tooltip').tooltip();
  248. return false;
  249. },
  250. _onTypeComment: function(ev) {
  251. var $field = $(ev.target);
  252. var len = $field.val().length;
  253. var $submitButton = $field.data('submitButtonEl');
  254. if (!$submitButton) {
  255. $submitButton = $field.closest('form').find('.submit');
  256. $field.data('submitButtonEl', $submitButton);
  257. }
  258. $field.tooltip('hide');
  259. if (len > this._commentMaxThreshold) {
  260. $field.attr('data-original-title', t('comments', 'Allowed characters {count} of {max}', {count: len, max: this._commentMaxLength}));
  261. $field.tooltip({trigger: 'manual'});
  262. $field.tooltip('show');
  263. $field.addClass('error');
  264. }
  265. var limitExceeded = (len > this._commentMaxLength);
  266. $field.toggleClass('error', limitExceeded);
  267. $submitButton.prop('disabled', limitExceeded);
  268. //submits form on ctrl+Enter or cmd+Enter
  269. if (ev.keyCode === 13 && (ev.ctrlKey || ev.metaKey)) {
  270. $submitButton.click();
  271. }
  272. },
  273. _onClickComment: function(ev) {
  274. var $row = $(ev.target);
  275. if (!$row.is('.comment')) {
  276. $row = $row.closest('.comment');
  277. }
  278. $row.removeClass('collapsed');
  279. },
  280. _onClickCloseComment: function(ev) {
  281. ev.preventDefault();
  282. var $row = $(ev.target).closest('.comment');
  283. $row.data('commentEl').removeClass('hidden');
  284. $row.remove();
  285. return false;
  286. },
  287. _onClickDeleteComment: function(ev) {
  288. ev.preventDefault();
  289. var $comment = $(ev.target).closest('.comment');
  290. var commentId = $comment.data('id');
  291. var $loading = $comment.find('.submitLoading');
  292. $comment.addClass('disabled');
  293. $loading.removeClass('hidden');
  294. this.collection.get(commentId).destroy({
  295. success: function() {
  296. $comment.data('commentEl').remove();
  297. $comment.remove();
  298. },
  299. error: function() {
  300. $loading.addClass('hidden');
  301. $comment.removeClass('disabled');
  302. OC.Notification.showTemporary(t('comments', 'Error occurred while retrieving comment with id {id}', {id: commentId}));
  303. }
  304. });
  305. return false;
  306. },
  307. _onClickShowMore: function(ev) {
  308. ev.preventDefault();
  309. this.nextPage();
  310. },
  311. _onSubmitComment: function(e) {
  312. var self = this;
  313. var $form = $(e.target);
  314. var commentId = $form.closest('.comment').data('id');
  315. var currentUser = OC.getCurrentUser();
  316. var $submit = $form.find('.submit');
  317. var $loading = $form.find('.submitLoading');
  318. var $textArea = $form.find('.message');
  319. var message = $textArea.val().trim();
  320. e.preventDefault();
  321. if (!message.length || message.length > this._commentMaxLength) {
  322. return;
  323. }
  324. $textArea.prop('disabled', true);
  325. $submit.addClass('hidden');
  326. $loading.removeClass('hidden');
  327. if (commentId) {
  328. // edit mode
  329. var comment = this.collection.get(commentId);
  330. comment.save({
  331. message: $textArea.val()
  332. }, {
  333. success: function(model) {
  334. var $row = $form.closest('.comment');
  335. $submit.removeClass('hidden');
  336. $loading.addClass('hidden');
  337. $row.data('commentEl')
  338. .removeClass('hidden')
  339. .find('.message')
  340. .html(self._formatMessage(model.get('message')));
  341. $row.remove();
  342. },
  343. error: function() {
  344. $submit.removeClass('hidden');
  345. $loading.addClass('hidden');
  346. $textArea.prop('disabled', false);
  347. OC.Notification.showTemporary(t('comments', 'Error occurred while updating comment with id {id}', {id: commentId}));
  348. }
  349. });
  350. } else {
  351. this.collection.create({
  352. actorId: currentUser.uid,
  353. actorDisplayName: currentUser.displayName,
  354. actorType: 'users',
  355. verb: 'comment',
  356. message: $textArea.val(),
  357. creationDateTime: (new Date()).toUTCString()
  358. }, {
  359. at: 0,
  360. // wait for real creation before adding
  361. wait: true,
  362. success: function() {
  363. $submit.removeClass('hidden');
  364. $loading.addClass('hidden');
  365. $textArea.val('').prop('disabled', false);
  366. },
  367. error: function() {
  368. $submit.removeClass('hidden');
  369. $loading.addClass('hidden');
  370. $textArea.prop('disabled', false);
  371. OC.Notification.showTemporary(t('comments', 'Error occurred while posting comment'));
  372. }
  373. });
  374. }
  375. return false;
  376. },
  377. /**
  378. * Returns whether the given message is long and needs
  379. * collapsing
  380. */
  381. _isLong: function(message) {
  382. return message.length > 250 || (message.match(/\n/g) || []).length > 1;
  383. }
  384. });
  385. OCA.Comments.CommentsTabView = CommentsTabView;
  386. })(OC, OCA);