1
0

commentstabview.js 15 KB

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