##// END OF EJS Templates
comments: use better sweet alert confirm dialog.
marcink -
r4312:4d4359b7 default
parent child Browse files
Show More
@@ -1,932 +1,947 b''
1 // # Copyright (C) 2010-2020 RhodeCode GmbH
1 // # Copyright (C) 2010-2020 RhodeCode GmbH
2 // #
2 // #
3 // # This program is free software: you can redistribute it and/or modify
3 // # This program is free software: you can redistribute it and/or modify
4 // # it under the terms of the GNU Affero General Public License, version 3
4 // # it under the terms of the GNU Affero General Public License, version 3
5 // # (only), as published by the Free Software Foundation.
5 // # (only), as published by the Free Software Foundation.
6 // #
6 // #
7 // # This program is distributed in the hope that it will be useful,
7 // # This program is distributed in the hope that it will be useful,
8 // # but WITHOUT ANY WARRANTY; without even the implied warranty of
8 // # but WITHOUT ANY WARRANTY; without even the implied warranty of
9 // # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
9 // # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 // # GNU General Public License for more details.
10 // # GNU General Public License for more details.
11 // #
11 // #
12 // # You should have received a copy of the GNU Affero General Public License
12 // # You should have received a copy of the GNU Affero General Public License
13 // # along with this program. If not, see <http://www.gnu.org/licenses/>.
13 // # along with this program. If not, see <http://www.gnu.org/licenses/>.
14 // #
14 // #
15 // # This program is dual-licensed. If you wish to learn more about the
15 // # This program is dual-licensed. If you wish to learn more about the
16 // # RhodeCode Enterprise Edition, including its added features, Support services,
16 // # RhodeCode Enterprise Edition, including its added features, Support services,
17 // # and proprietary license terms, please see https://rhodecode.com/licenses/
17 // # and proprietary license terms, please see https://rhodecode.com/licenses/
18
18
19 var firefoxAnchorFix = function() {
19 var firefoxAnchorFix = function() {
20 // hack to make anchor links behave properly on firefox, in our inline
20 // hack to make anchor links behave properly on firefox, in our inline
21 // comments generation when comments are injected firefox is misbehaving
21 // comments generation when comments are injected firefox is misbehaving
22 // when jumping to anchor links
22 // when jumping to anchor links
23 if (location.href.indexOf('#') > -1) {
23 if (location.href.indexOf('#') > -1) {
24 location.href += '';
24 location.href += '';
25 }
25 }
26 };
26 };
27
27
28 var linkifyComments = function(comments) {
28 var linkifyComments = function(comments) {
29 var firstCommentId = null;
29 var firstCommentId = null;
30 if (comments) {
30 if (comments) {
31 firstCommentId = $(comments[0]).data('comment-id');
31 firstCommentId = $(comments[0]).data('comment-id');
32 }
32 }
33
33
34 if (firstCommentId){
34 if (firstCommentId){
35 $('#inline-comments-counter').attr('href', '#comment-' + firstCommentId);
35 $('#inline-comments-counter').attr('href', '#comment-' + firstCommentId);
36 }
36 }
37 };
37 };
38
38
39 var bindToggleButtons = function() {
39 var bindToggleButtons = function() {
40 $('.comment-toggle').on('click', function() {
40 $('.comment-toggle').on('click', function() {
41 $(this).parent().nextUntil('tr.line').toggle('inline-comments');
41 $(this).parent().nextUntil('tr.line').toggle('inline-comments');
42 });
42 });
43 };
43 };
44
44
45
45
46
46
47 var _submitAjaxPOST = function(url, postData, successHandler, failHandler) {
47 var _submitAjaxPOST = function(url, postData, successHandler, failHandler) {
48 failHandler = failHandler || function() {};
48 failHandler = failHandler || function() {};
49 postData = toQueryString(postData);
49 postData = toQueryString(postData);
50 var request = $.ajax({
50 var request = $.ajax({
51 url: url,
51 url: url,
52 type: 'POST',
52 type: 'POST',
53 data: postData,
53 data: postData,
54 headers: {'X-PARTIAL-XHR': true}
54 headers: {'X-PARTIAL-XHR': true}
55 })
55 })
56 .done(function (data) {
56 .done(function (data) {
57 successHandler(data);
57 successHandler(data);
58 })
58 })
59 .fail(function (data, textStatus, errorThrown) {
59 .fail(function (data, textStatus, errorThrown) {
60 failHandler(data, textStatus, errorThrown)
60 failHandler(data, textStatus, errorThrown)
61 });
61 });
62 return request;
62 return request;
63 };
63 };
64
64
65
65
66
66
67
67
68 /* Comment form for main and inline comments */
68 /* Comment form for main and inline comments */
69 (function(mod) {
69 (function(mod) {
70
70
71 if (typeof exports == "object" && typeof module == "object") {
71 if (typeof exports == "object" && typeof module == "object") {
72 // CommonJS
72 // CommonJS
73 module.exports = mod();
73 module.exports = mod();
74 }
74 }
75 else {
75 else {
76 // Plain browser env
76 // Plain browser env
77 (this || window).CommentForm = mod();
77 (this || window).CommentForm = mod();
78 }
78 }
79
79
80 })(function() {
80 })(function() {
81 "use strict";
81 "use strict";
82
82
83 function CommentForm(formElement, commitId, pullRequestId, lineNo, initAutocompleteActions, resolvesCommentId) {
83 function CommentForm(formElement, commitId, pullRequestId, lineNo, initAutocompleteActions, resolvesCommentId) {
84 if (!(this instanceof CommentForm)) {
84 if (!(this instanceof CommentForm)) {
85 return new CommentForm(formElement, commitId, pullRequestId, lineNo, initAutocompleteActions, resolvesCommentId);
85 return new CommentForm(formElement, commitId, pullRequestId, lineNo, initAutocompleteActions, resolvesCommentId);
86 }
86 }
87
87
88 // bind the element instance to our Form
88 // bind the element instance to our Form
89 $(formElement).get(0).CommentForm = this;
89 $(formElement).get(0).CommentForm = this;
90
90
91 this.withLineNo = function(selector) {
91 this.withLineNo = function(selector) {
92 var lineNo = this.lineNo;
92 var lineNo = this.lineNo;
93 if (lineNo === undefined) {
93 if (lineNo === undefined) {
94 return selector
94 return selector
95 } else {
95 } else {
96 return selector + '_' + lineNo;
96 return selector + '_' + lineNo;
97 }
97 }
98 };
98 };
99
99
100 this.commitId = commitId;
100 this.commitId = commitId;
101 this.pullRequestId = pullRequestId;
101 this.pullRequestId = pullRequestId;
102 this.lineNo = lineNo;
102 this.lineNo = lineNo;
103 this.initAutocompleteActions = initAutocompleteActions;
103 this.initAutocompleteActions = initAutocompleteActions;
104
104
105 this.previewButton = this.withLineNo('#preview-btn');
105 this.previewButton = this.withLineNo('#preview-btn');
106 this.previewContainer = this.withLineNo('#preview-container');
106 this.previewContainer = this.withLineNo('#preview-container');
107
107
108 this.previewBoxSelector = this.withLineNo('#preview-box');
108 this.previewBoxSelector = this.withLineNo('#preview-box');
109
109
110 this.editButton = this.withLineNo('#edit-btn');
110 this.editButton = this.withLineNo('#edit-btn');
111 this.editContainer = this.withLineNo('#edit-container');
111 this.editContainer = this.withLineNo('#edit-container');
112 this.cancelButton = this.withLineNo('#cancel-btn');
112 this.cancelButton = this.withLineNo('#cancel-btn');
113 this.commentType = this.withLineNo('#comment_type');
113 this.commentType = this.withLineNo('#comment_type');
114
114
115 this.resolvesId = null;
115 this.resolvesId = null;
116 this.resolvesActionId = null;
116 this.resolvesActionId = null;
117
117
118 this.closesPr = '#close_pull_request';
118 this.closesPr = '#close_pull_request';
119
119
120 this.cmBox = this.withLineNo('#text');
120 this.cmBox = this.withLineNo('#text');
121 this.cm = initCommentBoxCodeMirror(this, this.cmBox, this.initAutocompleteActions);
121 this.cm = initCommentBoxCodeMirror(this, this.cmBox, this.initAutocompleteActions);
122
122
123 this.statusChange = this.withLineNo('#change_status');
123 this.statusChange = this.withLineNo('#change_status');
124
124
125 this.submitForm = formElement;
125 this.submitForm = formElement;
126 this.submitButton = $(this.submitForm).find('input[type="submit"]');
126 this.submitButton = $(this.submitForm).find('input[type="submit"]');
127 this.submitButtonText = this.submitButton.val();
127 this.submitButtonText = this.submitButton.val();
128
128
129 this.previewUrl = pyroutes.url('repo_commit_comment_preview',
129 this.previewUrl = pyroutes.url('repo_commit_comment_preview',
130 {'repo_name': templateContext.repo_name,
130 {'repo_name': templateContext.repo_name,
131 'commit_id': templateContext.commit_data.commit_id});
131 'commit_id': templateContext.commit_data.commit_id});
132
132
133 if (resolvesCommentId){
133 if (resolvesCommentId){
134 this.resolvesId = '#resolve_comment_{0}'.format(resolvesCommentId);
134 this.resolvesId = '#resolve_comment_{0}'.format(resolvesCommentId);
135 this.resolvesActionId = '#resolve_comment_action_{0}'.format(resolvesCommentId);
135 this.resolvesActionId = '#resolve_comment_action_{0}'.format(resolvesCommentId);
136 $(this.commentType).prop('disabled', true);
136 $(this.commentType).prop('disabled', true);
137 $(this.commentType).addClass('disabled');
137 $(this.commentType).addClass('disabled');
138
138
139 // disable select
139 // disable select
140 setTimeout(function() {
140 setTimeout(function() {
141 $(self.statusChange).select2('readonly', true);
141 $(self.statusChange).select2('readonly', true);
142 }, 10);
142 }, 10);
143
143
144 var resolvedInfo = (
144 var resolvedInfo = (
145 '<li class="resolve-action">' +
145 '<li class="resolve-action">' +
146 '<input type="hidden" id="resolve_comment_{0}" name="resolve_comment_{0}" value="{0}">' +
146 '<input type="hidden" id="resolve_comment_{0}" name="resolve_comment_{0}" value="{0}">' +
147 '<button id="resolve_comment_action_{0}" class="resolve-text btn btn-sm" onclick="return Rhodecode.comments.submitResolution({0})">{1} #{0}</button>' +
147 '<button id="resolve_comment_action_{0}" class="resolve-text btn btn-sm" onclick="return Rhodecode.comments.submitResolution({0})">{1} #{0}</button>' +
148 '</li>'
148 '</li>'
149 ).format(resolvesCommentId, _gettext('resolve comment'));
149 ).format(resolvesCommentId, _gettext('resolve comment'));
150 $(resolvedInfo).insertAfter($(this.commentType).parent());
150 $(resolvedInfo).insertAfter($(this.commentType).parent());
151 }
151 }
152
152
153 // based on commitId, or pullRequestId decide where do we submit
153 // based on commitId, or pullRequestId decide where do we submit
154 // out data
154 // out data
155 if (this.commitId){
155 if (this.commitId){
156 this.submitUrl = pyroutes.url('repo_commit_comment_create',
156 this.submitUrl = pyroutes.url('repo_commit_comment_create',
157 {'repo_name': templateContext.repo_name,
157 {'repo_name': templateContext.repo_name,
158 'commit_id': this.commitId});
158 'commit_id': this.commitId});
159 this.selfUrl = pyroutes.url('repo_commit',
159 this.selfUrl = pyroutes.url('repo_commit',
160 {'repo_name': templateContext.repo_name,
160 {'repo_name': templateContext.repo_name,
161 'commit_id': this.commitId});
161 'commit_id': this.commitId});
162
162
163 } else if (this.pullRequestId) {
163 } else if (this.pullRequestId) {
164 this.submitUrl = pyroutes.url('pullrequest_comment_create',
164 this.submitUrl = pyroutes.url('pullrequest_comment_create',
165 {'repo_name': templateContext.repo_name,
165 {'repo_name': templateContext.repo_name,
166 'pull_request_id': this.pullRequestId});
166 'pull_request_id': this.pullRequestId});
167 this.selfUrl = pyroutes.url('pullrequest_show',
167 this.selfUrl = pyroutes.url('pullrequest_show',
168 {'repo_name': templateContext.repo_name,
168 {'repo_name': templateContext.repo_name,
169 'pull_request_id': this.pullRequestId});
169 'pull_request_id': this.pullRequestId});
170
170
171 } else {
171 } else {
172 throw new Error(
172 throw new Error(
173 'CommentForm requires pullRequestId, or commitId to be specified.')
173 'CommentForm requires pullRequestId, or commitId to be specified.')
174 }
174 }
175
175
176 // FUNCTIONS and helpers
176 // FUNCTIONS and helpers
177 var self = this;
177 var self = this;
178
178
179 this.isInline = function(){
179 this.isInline = function(){
180 return this.lineNo && this.lineNo != 'general';
180 return this.lineNo && this.lineNo != 'general';
181 };
181 };
182
182
183 this.getCmInstance = function(){
183 this.getCmInstance = function(){
184 return this.cm
184 return this.cm
185 };
185 };
186
186
187 this.setPlaceholder = function(placeholder) {
187 this.setPlaceholder = function(placeholder) {
188 var cm = this.getCmInstance();
188 var cm = this.getCmInstance();
189 if (cm){
189 if (cm){
190 cm.setOption('placeholder', placeholder);
190 cm.setOption('placeholder', placeholder);
191 }
191 }
192 };
192 };
193
193
194 this.getCommentStatus = function() {
194 this.getCommentStatus = function() {
195 return $(this.submitForm).find(this.statusChange).val();
195 return $(this.submitForm).find(this.statusChange).val();
196 };
196 };
197 this.getCommentType = function() {
197 this.getCommentType = function() {
198 return $(this.submitForm).find(this.commentType).val();
198 return $(this.submitForm).find(this.commentType).val();
199 };
199 };
200
200
201 this.getResolvesId = function() {
201 this.getResolvesId = function() {
202 return $(this.submitForm).find(this.resolvesId).val() || null;
202 return $(this.submitForm).find(this.resolvesId).val() || null;
203 };
203 };
204
204
205 this.getClosePr = function() {
205 this.getClosePr = function() {
206 return $(this.submitForm).find(this.closesPr).val() || null;
206 return $(this.submitForm).find(this.closesPr).val() || null;
207 };
207 };
208
208
209 this.markCommentResolved = function(resolvedCommentId){
209 this.markCommentResolved = function(resolvedCommentId){
210 $('#comment-label-{0}'.format(resolvedCommentId)).find('.resolved').show();
210 $('#comment-label-{0}'.format(resolvedCommentId)).find('.resolved').show();
211 $('#comment-label-{0}'.format(resolvedCommentId)).find('.resolve').hide();
211 $('#comment-label-{0}'.format(resolvedCommentId)).find('.resolve').hide();
212 };
212 };
213
213
214 this.isAllowedToSubmit = function() {
214 this.isAllowedToSubmit = function() {
215 return !$(this.submitButton).prop('disabled');
215 return !$(this.submitButton).prop('disabled');
216 };
216 };
217
217
218 this.initStatusChangeSelector = function(){
218 this.initStatusChangeSelector = function(){
219 var formatChangeStatus = function(state, escapeMarkup) {
219 var formatChangeStatus = function(state, escapeMarkup) {
220 var originalOption = state.element;
220 var originalOption = state.element;
221 var tmpl = '<i class="icon-circle review-status-{0}"></i><span>{1}</span>'.format($(originalOption).data('status'), escapeMarkup(state.text));
221 var tmpl = '<i class="icon-circle review-status-{0}"></i><span>{1}</span>'.format($(originalOption).data('status'), escapeMarkup(state.text));
222 return tmpl
222 return tmpl
223 };
223 };
224 var formatResult = function(result, container, query, escapeMarkup) {
224 var formatResult = function(result, container, query, escapeMarkup) {
225 return formatChangeStatus(result, escapeMarkup);
225 return formatChangeStatus(result, escapeMarkup);
226 };
226 };
227
227
228 var formatSelection = function(data, container, escapeMarkup) {
228 var formatSelection = function(data, container, escapeMarkup) {
229 return formatChangeStatus(data, escapeMarkup);
229 return formatChangeStatus(data, escapeMarkup);
230 };
230 };
231
231
232 $(this.submitForm).find(this.statusChange).select2({
232 $(this.submitForm).find(this.statusChange).select2({
233 placeholder: _gettext('Status Review'),
233 placeholder: _gettext('Status Review'),
234 formatResult: formatResult,
234 formatResult: formatResult,
235 formatSelection: formatSelection,
235 formatSelection: formatSelection,
236 containerCssClass: "drop-menu status_box_menu",
236 containerCssClass: "drop-menu status_box_menu",
237 dropdownCssClass: "drop-menu-dropdown",
237 dropdownCssClass: "drop-menu-dropdown",
238 dropdownAutoWidth: true,
238 dropdownAutoWidth: true,
239 minimumResultsForSearch: -1
239 minimumResultsForSearch: -1
240 });
240 });
241 $(this.submitForm).find(this.statusChange).on('change', function() {
241 $(this.submitForm).find(this.statusChange).on('change', function() {
242 var status = self.getCommentStatus();
242 var status = self.getCommentStatus();
243
243
244 if (status && !self.isInline()) {
244 if (status && !self.isInline()) {
245 $(self.submitButton).prop('disabled', false);
245 $(self.submitButton).prop('disabled', false);
246 }
246 }
247
247
248 var placeholderText = _gettext('Comment text will be set automatically based on currently selected status ({0}) ...').format(status);
248 var placeholderText = _gettext('Comment text will be set automatically based on currently selected status ({0}) ...').format(status);
249 self.setPlaceholder(placeholderText)
249 self.setPlaceholder(placeholderText)
250 })
250 })
251 };
251 };
252
252
253 // reset the comment form into it's original state
253 // reset the comment form into it's original state
254 this.resetCommentFormState = function(content) {
254 this.resetCommentFormState = function(content) {
255 content = content || '';
255 content = content || '';
256
256
257 $(this.editContainer).show();
257 $(this.editContainer).show();
258 $(this.editButton).parent().addClass('active');
258 $(this.editButton).parent().addClass('active');
259
259
260 $(this.previewContainer).hide();
260 $(this.previewContainer).hide();
261 $(this.previewButton).parent().removeClass('active');
261 $(this.previewButton).parent().removeClass('active');
262
262
263 this.setActionButtonsDisabled(true);
263 this.setActionButtonsDisabled(true);
264 self.cm.setValue(content);
264 self.cm.setValue(content);
265 self.cm.setOption("readOnly", false);
265 self.cm.setOption("readOnly", false);
266
266
267 if (this.resolvesId) {
267 if (this.resolvesId) {
268 // destroy the resolve action
268 // destroy the resolve action
269 $(this.resolvesId).parent().remove();
269 $(this.resolvesId).parent().remove();
270 }
270 }
271 // reset closingPR flag
271 // reset closingPR flag
272 $('.close-pr-input').remove();
272 $('.close-pr-input').remove();
273
273
274 $(this.statusChange).select2('readonly', false);
274 $(this.statusChange).select2('readonly', false);
275 };
275 };
276
276
277 this.globalSubmitSuccessCallback = function(){
277 this.globalSubmitSuccessCallback = function(){
278 // default behaviour is to call GLOBAL hook, if it's registered.
278 // default behaviour is to call GLOBAL hook, if it's registered.
279 if (window.commentFormGlobalSubmitSuccessCallback !== undefined){
279 if (window.commentFormGlobalSubmitSuccessCallback !== undefined){
280 commentFormGlobalSubmitSuccessCallback()
280 commentFormGlobalSubmitSuccessCallback()
281 }
281 }
282 };
282 };
283
283
284 this.submitAjaxPOST = function(url, postData, successHandler, failHandler) {
284 this.submitAjaxPOST = function(url, postData, successHandler, failHandler) {
285 return _submitAjaxPOST(url, postData, successHandler, failHandler);
285 return _submitAjaxPOST(url, postData, successHandler, failHandler);
286 };
286 };
287
287
288 // overwrite a submitHandler, we need to do it for inline comments
288 // overwrite a submitHandler, we need to do it for inline comments
289 this.setHandleFormSubmit = function(callback) {
289 this.setHandleFormSubmit = function(callback) {
290 this.handleFormSubmit = callback;
290 this.handleFormSubmit = callback;
291 };
291 };
292
292
293 // overwrite a submitSuccessHandler
293 // overwrite a submitSuccessHandler
294 this.setGlobalSubmitSuccessCallback = function(callback) {
294 this.setGlobalSubmitSuccessCallback = function(callback) {
295 this.globalSubmitSuccessCallback = callback;
295 this.globalSubmitSuccessCallback = callback;
296 };
296 };
297
297
298 // default handler for for submit for main comments
298 // default handler for for submit for main comments
299 this.handleFormSubmit = function() {
299 this.handleFormSubmit = function() {
300 var text = self.cm.getValue();
300 var text = self.cm.getValue();
301 var status = self.getCommentStatus();
301 var status = self.getCommentStatus();
302 var commentType = self.getCommentType();
302 var commentType = self.getCommentType();
303 var resolvesCommentId = self.getResolvesId();
303 var resolvesCommentId = self.getResolvesId();
304 var closePullRequest = self.getClosePr();
304 var closePullRequest = self.getClosePr();
305
305
306 if (text === "" && !status) {
306 if (text === "" && !status) {
307 return;
307 return;
308 }
308 }
309
309
310 var excludeCancelBtn = false;
310 var excludeCancelBtn = false;
311 var submitEvent = true;
311 var submitEvent = true;
312 self.setActionButtonsDisabled(true, excludeCancelBtn, submitEvent);
312 self.setActionButtonsDisabled(true, excludeCancelBtn, submitEvent);
313 self.cm.setOption("readOnly", true);
313 self.cm.setOption("readOnly", true);
314
314
315 var postData = {
315 var postData = {
316 'text': text,
316 'text': text,
317 'changeset_status': status,
317 'changeset_status': status,
318 'comment_type': commentType,
318 'comment_type': commentType,
319 'csrf_token': CSRF_TOKEN
319 'csrf_token': CSRF_TOKEN
320 };
320 };
321
321
322 if (resolvesCommentId) {
322 if (resolvesCommentId) {
323 postData['resolves_comment_id'] = resolvesCommentId;
323 postData['resolves_comment_id'] = resolvesCommentId;
324 }
324 }
325
325
326 if (closePullRequest) {
326 if (closePullRequest) {
327 postData['close_pull_request'] = true;
327 postData['close_pull_request'] = true;
328 }
328 }
329
329
330 var submitSuccessCallback = function(o) {
330 var submitSuccessCallback = function(o) {
331 // reload page if we change status for single commit.
331 // reload page if we change status for single commit.
332 if (status && self.commitId) {
332 if (status && self.commitId) {
333 location.reload(true);
333 location.reload(true);
334 } else {
334 } else {
335 $('#injected_page_comments').append(o.rendered_text);
335 $('#injected_page_comments').append(o.rendered_text);
336 self.resetCommentFormState();
336 self.resetCommentFormState();
337 timeagoActivate();
337 timeagoActivate();
338 tooltipActivate();
338 tooltipActivate();
339
339
340 // mark visually which comment was resolved
340 // mark visually which comment was resolved
341 if (resolvesCommentId) {
341 if (resolvesCommentId) {
342 self.markCommentResolved(resolvesCommentId);
342 self.markCommentResolved(resolvesCommentId);
343 }
343 }
344 }
344 }
345
345
346 // run global callback on submit
346 // run global callback on submit
347 self.globalSubmitSuccessCallback();
347 self.globalSubmitSuccessCallback();
348
348
349 };
349 };
350 var submitFailCallback = function(jqXHR, textStatus, errorThrown) {
350 var submitFailCallback = function(jqXHR, textStatus, errorThrown) {
351 var prefix = "Error while submitting comment.\n"
351 var prefix = "Error while submitting comment.\n"
352 var message = formatErrorMessage(jqXHR, textStatus, errorThrown, prefix);
352 var message = formatErrorMessage(jqXHR, textStatus, errorThrown, prefix);
353 ajaxErrorSwal(message);
353 ajaxErrorSwal(message);
354 self.resetCommentFormState(text);
354 self.resetCommentFormState(text);
355 };
355 };
356 self.submitAjaxPOST(
356 self.submitAjaxPOST(
357 self.submitUrl, postData, submitSuccessCallback, submitFailCallback);
357 self.submitUrl, postData, submitSuccessCallback, submitFailCallback);
358 };
358 };
359
359
360 this.previewSuccessCallback = function(o) {
360 this.previewSuccessCallback = function(o) {
361 $(self.previewBoxSelector).html(o);
361 $(self.previewBoxSelector).html(o);
362 $(self.previewBoxSelector).removeClass('unloaded');
362 $(self.previewBoxSelector).removeClass('unloaded');
363
363
364 // swap buttons, making preview active
364 // swap buttons, making preview active
365 $(self.previewButton).parent().addClass('active');
365 $(self.previewButton).parent().addClass('active');
366 $(self.editButton).parent().removeClass('active');
366 $(self.editButton).parent().removeClass('active');
367
367
368 // unlock buttons
368 // unlock buttons
369 self.setActionButtonsDisabled(false);
369 self.setActionButtonsDisabled(false);
370 };
370 };
371
371
372 this.setActionButtonsDisabled = function(state, excludeCancelBtn, submitEvent) {
372 this.setActionButtonsDisabled = function(state, excludeCancelBtn, submitEvent) {
373 excludeCancelBtn = excludeCancelBtn || false;
373 excludeCancelBtn = excludeCancelBtn || false;
374 submitEvent = submitEvent || false;
374 submitEvent = submitEvent || false;
375
375
376 $(this.editButton).prop('disabled', state);
376 $(this.editButton).prop('disabled', state);
377 $(this.previewButton).prop('disabled', state);
377 $(this.previewButton).prop('disabled', state);
378
378
379 if (!excludeCancelBtn) {
379 if (!excludeCancelBtn) {
380 $(this.cancelButton).prop('disabled', state);
380 $(this.cancelButton).prop('disabled', state);
381 }
381 }
382
382
383 var submitState = state;
383 var submitState = state;
384 if (!submitEvent && this.getCommentStatus() && !self.isInline()) {
384 if (!submitEvent && this.getCommentStatus() && !self.isInline()) {
385 // if the value of commit review status is set, we allow
385 // if the value of commit review status is set, we allow
386 // submit button, but only on Main form, isInline means inline
386 // submit button, but only on Main form, isInline means inline
387 submitState = false
387 submitState = false
388 }
388 }
389
389
390 $(this.submitButton).prop('disabled', submitState);
390 $(this.submitButton).prop('disabled', submitState);
391 if (submitEvent) {
391 if (submitEvent) {
392 $(this.submitButton).val(_gettext('Submitting...'));
392 $(this.submitButton).val(_gettext('Submitting...'));
393 } else {
393 } else {
394 $(this.submitButton).val(this.submitButtonText);
394 $(this.submitButton).val(this.submitButtonText);
395 }
395 }
396
396
397 };
397 };
398
398
399 // lock preview/edit/submit buttons on load, but exclude cancel button
399 // lock preview/edit/submit buttons on load, but exclude cancel button
400 var excludeCancelBtn = true;
400 var excludeCancelBtn = true;
401 this.setActionButtonsDisabled(true, excludeCancelBtn);
401 this.setActionButtonsDisabled(true, excludeCancelBtn);
402
402
403 // anonymous users don't have access to initialized CM instance
403 // anonymous users don't have access to initialized CM instance
404 if (this.cm !== undefined){
404 if (this.cm !== undefined){
405 this.cm.on('change', function(cMirror) {
405 this.cm.on('change', function(cMirror) {
406 if (cMirror.getValue() === "") {
406 if (cMirror.getValue() === "") {
407 self.setActionButtonsDisabled(true, excludeCancelBtn)
407 self.setActionButtonsDisabled(true, excludeCancelBtn)
408 } else {
408 } else {
409 self.setActionButtonsDisabled(false, excludeCancelBtn)
409 self.setActionButtonsDisabled(false, excludeCancelBtn)
410 }
410 }
411 });
411 });
412 }
412 }
413
413
414 $(this.editButton).on('click', function(e) {
414 $(this.editButton).on('click', function(e) {
415 e.preventDefault();
415 e.preventDefault();
416
416
417 $(self.previewButton).parent().removeClass('active');
417 $(self.previewButton).parent().removeClass('active');
418 $(self.previewContainer).hide();
418 $(self.previewContainer).hide();
419
419
420 $(self.editButton).parent().addClass('active');
420 $(self.editButton).parent().addClass('active');
421 $(self.editContainer).show();
421 $(self.editContainer).show();
422
422
423 });
423 });
424
424
425 $(this.previewButton).on('click', function(e) {
425 $(this.previewButton).on('click', function(e) {
426 e.preventDefault();
426 e.preventDefault();
427 var text = self.cm.getValue();
427 var text = self.cm.getValue();
428
428
429 if (text === "") {
429 if (text === "") {
430 return;
430 return;
431 }
431 }
432
432
433 var postData = {
433 var postData = {
434 'text': text,
434 'text': text,
435 'renderer': templateContext.visual.default_renderer,
435 'renderer': templateContext.visual.default_renderer,
436 'csrf_token': CSRF_TOKEN
436 'csrf_token': CSRF_TOKEN
437 };
437 };
438
438
439 // lock ALL buttons on preview
439 // lock ALL buttons on preview
440 self.setActionButtonsDisabled(true);
440 self.setActionButtonsDisabled(true);
441
441
442 $(self.previewBoxSelector).addClass('unloaded');
442 $(self.previewBoxSelector).addClass('unloaded');
443 $(self.previewBoxSelector).html(_gettext('Loading ...'));
443 $(self.previewBoxSelector).html(_gettext('Loading ...'));
444
444
445 $(self.editContainer).hide();
445 $(self.editContainer).hide();
446 $(self.previewContainer).show();
446 $(self.previewContainer).show();
447
447
448 // by default we reset state of comment preserving the text
448 // by default we reset state of comment preserving the text
449 var previewFailCallback = function(jqXHR, textStatus, errorThrown) {
449 var previewFailCallback = function(jqXHR, textStatus, errorThrown) {
450 var prefix = "Error while preview of comment.\n"
450 var prefix = "Error while preview of comment.\n"
451 var message = formatErrorMessage(jqXHR, textStatus, errorThrown, prefix);
451 var message = formatErrorMessage(jqXHR, textStatus, errorThrown, prefix);
452 ajaxErrorSwal(message);
452 ajaxErrorSwal(message);
453
453
454 self.resetCommentFormState(text)
454 self.resetCommentFormState(text)
455 };
455 };
456 self.submitAjaxPOST(
456 self.submitAjaxPOST(
457 self.previewUrl, postData, self.previewSuccessCallback,
457 self.previewUrl, postData, self.previewSuccessCallback,
458 previewFailCallback);
458 previewFailCallback);
459
459
460 $(self.previewButton).parent().addClass('active');
460 $(self.previewButton).parent().addClass('active');
461 $(self.editButton).parent().removeClass('active');
461 $(self.editButton).parent().removeClass('active');
462 });
462 });
463
463
464 $(this.submitForm).submit(function(e) {
464 $(this.submitForm).submit(function(e) {
465 e.preventDefault();
465 e.preventDefault();
466 var allowedToSubmit = self.isAllowedToSubmit();
466 var allowedToSubmit = self.isAllowedToSubmit();
467 if (!allowedToSubmit){
467 if (!allowedToSubmit){
468 return false;
468 return false;
469 }
469 }
470 self.handleFormSubmit();
470 self.handleFormSubmit();
471 });
471 });
472
472
473 }
473 }
474
474
475 return CommentForm;
475 return CommentForm;
476 });
476 });
477
477
478 /* comments controller */
478 /* comments controller */
479 var CommentsController = function() {
479 var CommentsController = function() {
480 var mainComment = '#text';
480 var mainComment = '#text';
481 var self = this;
481 var self = this;
482
482
483 this.cancelComment = function(node) {
483 this.cancelComment = function(node) {
484 var $node = $(node);
484 var $node = $(node);
485 var $td = $node.closest('td');
485 var $td = $node.closest('td');
486 $node.closest('.comment-inline-form').remove();
486 $node.closest('.comment-inline-form').remove();
487 return false;
487 return false;
488 };
488 };
489
489
490 this.getLineNumber = function(node) {
490 this.getLineNumber = function(node) {
491 var $node = $(node);
491 var $node = $(node);
492 var lineNo = $node.closest('td').attr('data-line-no');
492 var lineNo = $node.closest('td').attr('data-line-no');
493 if (lineNo === undefined && $node.data('commentInline')){
493 if (lineNo === undefined && $node.data('commentInline')){
494 lineNo = $node.data('commentLineNo')
494 lineNo = $node.data('commentLineNo')
495 }
495 }
496
496
497 return lineNo
497 return lineNo
498 };
498 };
499
499
500 this.scrollToComment = function(node, offset, outdated) {
500 this.scrollToComment = function(node, offset, outdated) {
501 if (offset === undefined) {
501 if (offset === undefined) {
502 offset = 0;
502 offset = 0;
503 }
503 }
504 var outdated = outdated || false;
504 var outdated = outdated || false;
505 var klass = outdated ? 'div.comment-outdated' : 'div.comment-current';
505 var klass = outdated ? 'div.comment-outdated' : 'div.comment-current';
506
506
507 if (!node) {
507 if (!node) {
508 node = $('.comment-selected');
508 node = $('.comment-selected');
509 if (!node.length) {
509 if (!node.length) {
510 node = $('comment-current')
510 node = $('comment-current')
511 }
511 }
512 }
512 }
513
513
514 $wrapper = $(node).closest('div.comment');
514 $wrapper = $(node).closest('div.comment');
515
515
516 // show hidden comment when referenced.
516 // show hidden comment when referenced.
517 if (!$wrapper.is(':visible')){
517 if (!$wrapper.is(':visible')){
518 $wrapper.show();
518 $wrapper.show();
519 }
519 }
520
520
521 $comment = $(node).closest(klass);
521 $comment = $(node).closest(klass);
522 $comments = $(klass);
522 $comments = $(klass);
523
523
524 $('.comment-selected').removeClass('comment-selected');
524 $('.comment-selected').removeClass('comment-selected');
525
525
526 var nextIdx = $(klass).index($comment) + offset;
526 var nextIdx = $(klass).index($comment) + offset;
527 if (nextIdx >= $comments.length) {
527 if (nextIdx >= $comments.length) {
528 nextIdx = 0;
528 nextIdx = 0;
529 }
529 }
530 var $next = $(klass).eq(nextIdx);
530 var $next = $(klass).eq(nextIdx);
531
531
532 var $cb = $next.closest('.cb');
532 var $cb = $next.closest('.cb');
533 $cb.removeClass('cb-collapsed');
533 $cb.removeClass('cb-collapsed');
534
534
535 var $filediffCollapseState = $cb.closest('.filediff').prev();
535 var $filediffCollapseState = $cb.closest('.filediff').prev();
536 $filediffCollapseState.prop('checked', false);
536 $filediffCollapseState.prop('checked', false);
537 $next.addClass('comment-selected');
537 $next.addClass('comment-selected');
538 scrollToElement($next);
538 scrollToElement($next);
539 return false;
539 return false;
540 };
540 };
541
541
542 this.nextComment = function(node) {
542 this.nextComment = function(node) {
543 return self.scrollToComment(node, 1);
543 return self.scrollToComment(node, 1);
544 };
544 };
545
545
546 this.prevComment = function(node) {
546 this.prevComment = function(node) {
547 return self.scrollToComment(node, -1);
547 return self.scrollToComment(node, -1);
548 };
548 };
549
549
550 this.nextOutdatedComment = function(node) {
550 this.nextOutdatedComment = function(node) {
551 return self.scrollToComment(node, 1, true);
551 return self.scrollToComment(node, 1, true);
552 };
552 };
553
553
554 this.prevOutdatedComment = function(node) {
554 this.prevOutdatedComment = function(node) {
555 return self.scrollToComment(node, -1, true);
555 return self.scrollToComment(node, -1, true);
556 };
556 };
557
557
558 this.deleteComment = function(node) {
558 this._deleteComment = function(node) {
559 if (!confirm(_gettext('Delete this comment?'))) {
560 return false;
561 }
562 var $node = $(node);
559 var $node = $(node);
563 var $td = $node.closest('td');
560 var $td = $node.closest('td');
564 var $comment = $node.closest('.comment');
561 var $comment = $node.closest('.comment');
565 var comment_id = $comment.attr('data-comment-id');
562 var comment_id = $comment.attr('data-comment-id');
566 var url = AJAX_COMMENT_DELETE_URL.replace('__COMMENT_ID__', comment_id);
563 var url = AJAX_COMMENT_DELETE_URL.replace('__COMMENT_ID__', comment_id);
567 var postData = {
564 var postData = {
568 'csrf_token': CSRF_TOKEN
565 'csrf_token': CSRF_TOKEN
569 };
566 };
570
567
571 $comment.addClass('comment-deleting');
568 $comment.addClass('comment-deleting');
572 $comment.hide('fast');
569 $comment.hide('fast');
573
570
574 var success = function(response) {
571 var success = function(response) {
575 $comment.remove();
572 $comment.remove();
576 return false;
573 return false;
577 };
574 };
578 var failure = function(jqXHR, textStatus, errorThrown) {
575 var failure = function(jqXHR, textStatus, errorThrown) {
579 var prefix = "Error while deleting this comment.\n"
576 var prefix = "Error while deleting this comment.\n"
580 var message = formatErrorMessage(jqXHR, textStatus, errorThrown, prefix);
577 var message = formatErrorMessage(jqXHR, textStatus, errorThrown, prefix);
581 ajaxErrorSwal(message);
578 ajaxErrorSwal(message);
582
579
583 $comment.show('fast');
580 $comment.show('fast');
584 $comment.removeClass('comment-deleting');
581 $comment.removeClass('comment-deleting');
585 return false;
582 return false;
586 };
583 };
587 ajaxPOST(url, postData, success, failure);
584 ajaxPOST(url, postData, success, failure);
585 }
586
587 this.deleteComment = function(node) {
588 var $comment = $(node).closest('.comment');
589 var comment_id = $comment.attr('data-comment-id');
590
591 Swal.fire({
592 title: 'Delete this comment?',
593 icon: 'warning',
594 showCancelButton: true,
595 confirmButtonColor: '#84a5d2',
596 cancelButtonColor: '#e85e4d',
597 confirmButtonText: _gettext('Yes, delete comment #{0}!').format(comment_id)
598 }).then(function(result) {
599 if (result.value) {
600 self._deleteComment(node);
601 }
602 })
588 };
603 };
589
604
590 this.toggleWideMode = function (node) {
605 this.toggleWideMode = function (node) {
591 if ($('#content').hasClass('wrapper')) {
606 if ($('#content').hasClass('wrapper')) {
592 $('#content').removeClass("wrapper");
607 $('#content').removeClass("wrapper");
593 $('#content').addClass("wide-mode-wrapper");
608 $('#content').addClass("wide-mode-wrapper");
594 $(node).addClass('btn-success');
609 $(node).addClass('btn-success');
595 return true
610 return true
596 } else {
611 } else {
597 $('#content').removeClass("wide-mode-wrapper");
612 $('#content').removeClass("wide-mode-wrapper");
598 $('#content').addClass("wrapper");
613 $('#content').addClass("wrapper");
599 $(node).removeClass('btn-success');
614 $(node).removeClass('btn-success');
600 return false
615 return false
601 }
616 }
602
617
603 };
618 };
604
619
605 this.toggleComments = function(node, show) {
620 this.toggleComments = function(node, show) {
606 var $filediff = $(node).closest('.filediff');
621 var $filediff = $(node).closest('.filediff');
607 if (show === true) {
622 if (show === true) {
608 $filediff.removeClass('hide-comments');
623 $filediff.removeClass('hide-comments');
609 } else if (show === false) {
624 } else if (show === false) {
610 $filediff.find('.hide-line-comments').removeClass('hide-line-comments');
625 $filediff.find('.hide-line-comments').removeClass('hide-line-comments');
611 $filediff.addClass('hide-comments');
626 $filediff.addClass('hide-comments');
612 } else {
627 } else {
613 $filediff.find('.hide-line-comments').removeClass('hide-line-comments');
628 $filediff.find('.hide-line-comments').removeClass('hide-line-comments');
614 $filediff.toggleClass('hide-comments');
629 $filediff.toggleClass('hide-comments');
615 }
630 }
616 return false;
631 return false;
617 };
632 };
618
633
619 this.toggleLineComments = function(node) {
634 this.toggleLineComments = function(node) {
620 self.toggleComments(node, true);
635 self.toggleComments(node, true);
621 var $node = $(node);
636 var $node = $(node);
622 // mark outdated comments as visible before the toggle;
637 // mark outdated comments as visible before the toggle;
623 $(node.closest('tr')).find('.comment-outdated').show();
638 $(node.closest('tr')).find('.comment-outdated').show();
624 $node.closest('tr').toggleClass('hide-line-comments');
639 $node.closest('tr').toggleClass('hide-line-comments');
625 };
640 };
626
641
627 this.createCommentForm = function(formElement, lineno, placeholderText, initAutocompleteActions, resolvesCommentId){
642 this.createCommentForm = function(formElement, lineno, placeholderText, initAutocompleteActions, resolvesCommentId){
628 var pullRequestId = templateContext.pull_request_data.pull_request_id;
643 var pullRequestId = templateContext.pull_request_data.pull_request_id;
629 var commitId = templateContext.commit_data.commit_id;
644 var commitId = templateContext.commit_data.commit_id;
630
645
631 var commentForm = new CommentForm(
646 var commentForm = new CommentForm(
632 formElement, commitId, pullRequestId, lineno, initAutocompleteActions, resolvesCommentId);
647 formElement, commitId, pullRequestId, lineno, initAutocompleteActions, resolvesCommentId);
633 var cm = commentForm.getCmInstance();
648 var cm = commentForm.getCmInstance();
634
649
635 if (resolvesCommentId){
650 if (resolvesCommentId){
636 var placeholderText = _gettext('Leave a resolution comment, or click resolve button to resolve TODO comment #{0}').format(resolvesCommentId);
651 var placeholderText = _gettext('Leave a resolution comment, or click resolve button to resolve TODO comment #{0}').format(resolvesCommentId);
637 }
652 }
638
653
639 setTimeout(function() {
654 setTimeout(function() {
640 // callbacks
655 // callbacks
641 if (cm !== undefined) {
656 if (cm !== undefined) {
642 commentForm.setPlaceholder(placeholderText);
657 commentForm.setPlaceholder(placeholderText);
643 if (commentForm.isInline()) {
658 if (commentForm.isInline()) {
644 cm.focus();
659 cm.focus();
645 cm.refresh();
660 cm.refresh();
646 }
661 }
647 }
662 }
648 }, 10);
663 }, 10);
649
664
650 // trigger scrolldown to the resolve comment, since it might be away
665 // trigger scrolldown to the resolve comment, since it might be away
651 // from the clicked
666 // from the clicked
652 if (resolvesCommentId){
667 if (resolvesCommentId){
653 var actionNode = $(commentForm.resolvesActionId).offset();
668 var actionNode = $(commentForm.resolvesActionId).offset();
654
669
655 setTimeout(function() {
670 setTimeout(function() {
656 if (actionNode) {
671 if (actionNode) {
657 $('body, html').animate({scrollTop: actionNode.top}, 10);
672 $('body, html').animate({scrollTop: actionNode.top}, 10);
658 }
673 }
659 }, 100);
674 }, 100);
660 }
675 }
661
676
662 // add dropzone support
677 // add dropzone support
663 var insertAttachmentText = function (cm, attachmentName, attachmentStoreUrl, isRendered) {
678 var insertAttachmentText = function (cm, attachmentName, attachmentStoreUrl, isRendered) {
664 var renderer = templateContext.visual.default_renderer;
679 var renderer = templateContext.visual.default_renderer;
665 if (renderer == 'rst') {
680 if (renderer == 'rst') {
666 var attachmentUrl = '`#{0} <{1}>`_'.format(attachmentName, attachmentStoreUrl);
681 var attachmentUrl = '`#{0} <{1}>`_'.format(attachmentName, attachmentStoreUrl);
667 if (isRendered){
682 if (isRendered){
668 attachmentUrl = '\n.. image:: {0}'.format(attachmentStoreUrl);
683 attachmentUrl = '\n.. image:: {0}'.format(attachmentStoreUrl);
669 }
684 }
670 } else if (renderer == 'markdown') {
685 } else if (renderer == 'markdown') {
671 var attachmentUrl = '[{0}]({1})'.format(attachmentName, attachmentStoreUrl);
686 var attachmentUrl = '[{0}]({1})'.format(attachmentName, attachmentStoreUrl);
672 if (isRendered){
687 if (isRendered){
673 attachmentUrl = '!' + attachmentUrl;
688 attachmentUrl = '!' + attachmentUrl;
674 }
689 }
675 } else {
690 } else {
676 var attachmentUrl = '{}'.format(attachmentStoreUrl);
691 var attachmentUrl = '{}'.format(attachmentStoreUrl);
677 }
692 }
678 cm.replaceRange(attachmentUrl+'\n', CodeMirror.Pos(cm.lastLine()));
693 cm.replaceRange(attachmentUrl+'\n', CodeMirror.Pos(cm.lastLine()));
679
694
680 return false;
695 return false;
681 };
696 };
682
697
683 //see: https://www.dropzonejs.com/#configuration
698 //see: https://www.dropzonejs.com/#configuration
684 var storeUrl = pyroutes.url('repo_commit_comment_attachment_upload',
699 var storeUrl = pyroutes.url('repo_commit_comment_attachment_upload',
685 {'repo_name': templateContext.repo_name,
700 {'repo_name': templateContext.repo_name,
686 'commit_id': templateContext.commit_data.commit_id})
701 'commit_id': templateContext.commit_data.commit_id})
687
702
688 var previewTmpl = $(formElement).find('.comment-attachment-uploader-template').get(0);
703 var previewTmpl = $(formElement).find('.comment-attachment-uploader-template').get(0);
689 if (previewTmpl !== undefined){
704 if (previewTmpl !== undefined){
690 var selectLink = $(formElement).find('.pick-attachment').get(0);
705 var selectLink = $(formElement).find('.pick-attachment').get(0);
691 $(formElement).find('.comment-attachment-uploader').dropzone({
706 $(formElement).find('.comment-attachment-uploader').dropzone({
692 url: storeUrl,
707 url: storeUrl,
693 headers: {"X-CSRF-Token": CSRF_TOKEN},
708 headers: {"X-CSRF-Token": CSRF_TOKEN},
694 paramName: function () {
709 paramName: function () {
695 return "attachment"
710 return "attachment"
696 }, // The name that will be used to transfer the file
711 }, // The name that will be used to transfer the file
697 clickable: selectLink,
712 clickable: selectLink,
698 parallelUploads: 1,
713 parallelUploads: 1,
699 maxFiles: 10,
714 maxFiles: 10,
700 maxFilesize: templateContext.attachment_store.max_file_size_mb,
715 maxFilesize: templateContext.attachment_store.max_file_size_mb,
701 uploadMultiple: false,
716 uploadMultiple: false,
702 autoProcessQueue: true, // if false queue will not be processed automatically.
717 autoProcessQueue: true, // if false queue will not be processed automatically.
703 createImageThumbnails: false,
718 createImageThumbnails: false,
704 previewTemplate: previewTmpl.innerHTML,
719 previewTemplate: previewTmpl.innerHTML,
705
720
706 accept: function (file, done) {
721 accept: function (file, done) {
707 done();
722 done();
708 },
723 },
709 init: function () {
724 init: function () {
710
725
711 this.on("sending", function (file, xhr, formData) {
726 this.on("sending", function (file, xhr, formData) {
712 $(formElement).find('.comment-attachment-uploader').find('.dropzone-text').hide();
727 $(formElement).find('.comment-attachment-uploader').find('.dropzone-text').hide();
713 $(formElement).find('.comment-attachment-uploader').find('.dropzone-upload').show();
728 $(formElement).find('.comment-attachment-uploader').find('.dropzone-upload').show();
714 });
729 });
715
730
716 this.on("success", function (file, response) {
731 this.on("success", function (file, response) {
717 $(formElement).find('.comment-attachment-uploader').find('.dropzone-text').show();
732 $(formElement).find('.comment-attachment-uploader').find('.dropzone-text').show();
718 $(formElement).find('.comment-attachment-uploader').find('.dropzone-upload').hide();
733 $(formElement).find('.comment-attachment-uploader').find('.dropzone-upload').hide();
719
734
720 var isRendered = false;
735 var isRendered = false;
721 var ext = file.name.split('.').pop();
736 var ext = file.name.split('.').pop();
722 var imageExts = templateContext.attachment_store.image_ext;
737 var imageExts = templateContext.attachment_store.image_ext;
723 if (imageExts.indexOf(ext) !== -1){
738 if (imageExts.indexOf(ext) !== -1){
724 isRendered = true;
739 isRendered = true;
725 }
740 }
726
741
727 insertAttachmentText(cm, file.name, response.repo_fqn_access_path, isRendered)
742 insertAttachmentText(cm, file.name, response.repo_fqn_access_path, isRendered)
728 });
743 });
729
744
730 this.on("error", function (file, errorMessage, xhr) {
745 this.on("error", function (file, errorMessage, xhr) {
731 $(formElement).find('.comment-attachment-uploader').find('.dropzone-upload').hide();
746 $(formElement).find('.comment-attachment-uploader').find('.dropzone-upload').hide();
732
747
733 var error = null;
748 var error = null;
734
749
735 if (xhr !== undefined){
750 if (xhr !== undefined){
736 var httpStatus = xhr.status + " " + xhr.statusText;
751 var httpStatus = xhr.status + " " + xhr.statusText;
737 if (xhr !== undefined && xhr.status >= 500) {
752 if (xhr !== undefined && xhr.status >= 500) {
738 error = httpStatus;
753 error = httpStatus;
739 }
754 }
740 }
755 }
741
756
742 if (error === null) {
757 if (error === null) {
743 error = errorMessage.error || errorMessage || httpStatus;
758 error = errorMessage.error || errorMessage || httpStatus;
744 }
759 }
745 $(file.previewElement).find('.dz-error-message').html('ERROR: {0}'.format(error));
760 $(file.previewElement).find('.dz-error-message').html('ERROR: {0}'.format(error));
746
761
747 });
762 });
748 }
763 }
749 });
764 });
750 }
765 }
751 return commentForm;
766 return commentForm;
752 };
767 };
753
768
754 this.createGeneralComment = function (lineNo, placeholderText, resolvesCommentId) {
769 this.createGeneralComment = function (lineNo, placeholderText, resolvesCommentId) {
755
770
756 var tmpl = $('#cb-comment-general-form-template').html();
771 var tmpl = $('#cb-comment-general-form-template').html();
757 tmpl = tmpl.format(null, 'general');
772 tmpl = tmpl.format(null, 'general');
758 var $form = $(tmpl);
773 var $form = $(tmpl);
759
774
760 var $formPlaceholder = $('#cb-comment-general-form-placeholder');
775 var $formPlaceholder = $('#cb-comment-general-form-placeholder');
761 var curForm = $formPlaceholder.find('form');
776 var curForm = $formPlaceholder.find('form');
762 if (curForm){
777 if (curForm){
763 curForm.remove();
778 curForm.remove();
764 }
779 }
765 $formPlaceholder.append($form);
780 $formPlaceholder.append($form);
766
781
767 var _form = $($form[0]);
782 var _form = $($form[0]);
768 var autocompleteActions = ['approve', 'reject', 'as_note', 'as_todo'];
783 var autocompleteActions = ['approve', 'reject', 'as_note', 'as_todo'];
769 var commentForm = this.createCommentForm(
784 var commentForm = this.createCommentForm(
770 _form, lineNo, placeholderText, autocompleteActions, resolvesCommentId);
785 _form, lineNo, placeholderText, autocompleteActions, resolvesCommentId);
771 commentForm.initStatusChangeSelector();
786 commentForm.initStatusChangeSelector();
772
787
773 return commentForm;
788 return commentForm;
774 };
789 };
775
790
776 this.createComment = function(node, resolutionComment) {
791 this.createComment = function(node, resolutionComment) {
777 var resolvesCommentId = resolutionComment || null;
792 var resolvesCommentId = resolutionComment || null;
778 var $node = $(node);
793 var $node = $(node);
779 var $td = $node.closest('td');
794 var $td = $node.closest('td');
780 var $form = $td.find('.comment-inline-form');
795 var $form = $td.find('.comment-inline-form');
781
796
782 if (!$form.length) {
797 if (!$form.length) {
783
798
784 var $filediff = $node.closest('.filediff');
799 var $filediff = $node.closest('.filediff');
785 $filediff.removeClass('hide-comments');
800 $filediff.removeClass('hide-comments');
786 var f_path = $filediff.attr('data-f-path');
801 var f_path = $filediff.attr('data-f-path');
787 var lineno = self.getLineNumber(node);
802 var lineno = self.getLineNumber(node);
788 // create a new HTML from template
803 // create a new HTML from template
789 var tmpl = $('#cb-comment-inline-form-template').html();
804 var tmpl = $('#cb-comment-inline-form-template').html();
790 tmpl = tmpl.format(escapeHtml(f_path), lineno);
805 tmpl = tmpl.format(escapeHtml(f_path), lineno);
791 $form = $(tmpl);
806 $form = $(tmpl);
792
807
793 var $comments = $td.find('.inline-comments');
808 var $comments = $td.find('.inline-comments');
794 if (!$comments.length) {
809 if (!$comments.length) {
795 $comments = $(
810 $comments = $(
796 $('#cb-comments-inline-container-template').html());
811 $('#cb-comments-inline-container-template').html());
797 $td.append($comments);
812 $td.append($comments);
798 }
813 }
799
814
800 $td.find('.cb-comment-add-button').before($form);
815 $td.find('.cb-comment-add-button').before($form);
801
816
802 var placeholderText = _gettext('Leave a comment on line {0}.').format(lineno);
817 var placeholderText = _gettext('Leave a comment on line {0}.').format(lineno);
803 var _form = $($form[0]).find('form');
818 var _form = $($form[0]).find('form');
804 var autocompleteActions = ['as_note', 'as_todo'];
819 var autocompleteActions = ['as_note', 'as_todo'];
805 var commentForm = this.createCommentForm(
820 var commentForm = this.createCommentForm(
806 _form, lineno, placeholderText, autocompleteActions, resolvesCommentId);
821 _form, lineno, placeholderText, autocompleteActions, resolvesCommentId);
807
822
808 $.Topic('/ui/plugins/code/comment_form_built').prepareOrPublish({
823 $.Topic('/ui/plugins/code/comment_form_built').prepareOrPublish({
809 form: _form,
824 form: _form,
810 parent: $td[0],
825 parent: $td[0],
811 lineno: lineno,
826 lineno: lineno,
812 f_path: f_path}
827 f_path: f_path}
813 );
828 );
814
829
815 // set a CUSTOM submit handler for inline comments.
830 // set a CUSTOM submit handler for inline comments.
816 commentForm.setHandleFormSubmit(function(o) {
831 commentForm.setHandleFormSubmit(function(o) {
817 var text = commentForm.cm.getValue();
832 var text = commentForm.cm.getValue();
818 var commentType = commentForm.getCommentType();
833 var commentType = commentForm.getCommentType();
819 var resolvesCommentId = commentForm.getResolvesId();
834 var resolvesCommentId = commentForm.getResolvesId();
820
835
821 if (text === "") {
836 if (text === "") {
822 return;
837 return;
823 }
838 }
824
839
825 if (lineno === undefined) {
840 if (lineno === undefined) {
826 alert('missing line !');
841 alert('missing line !');
827 return;
842 return;
828 }
843 }
829 if (f_path === undefined) {
844 if (f_path === undefined) {
830 alert('missing file path !');
845 alert('missing file path !');
831 return;
846 return;
832 }
847 }
833
848
834 var excludeCancelBtn = false;
849 var excludeCancelBtn = false;
835 var submitEvent = true;
850 var submitEvent = true;
836 commentForm.setActionButtonsDisabled(true, excludeCancelBtn, submitEvent);
851 commentForm.setActionButtonsDisabled(true, excludeCancelBtn, submitEvent);
837 commentForm.cm.setOption("readOnly", true);
852 commentForm.cm.setOption("readOnly", true);
838 var postData = {
853 var postData = {
839 'text': text,
854 'text': text,
840 'f_path': f_path,
855 'f_path': f_path,
841 'line': lineno,
856 'line': lineno,
842 'comment_type': commentType,
857 'comment_type': commentType,
843 'csrf_token': CSRF_TOKEN
858 'csrf_token': CSRF_TOKEN
844 };
859 };
845 if (resolvesCommentId){
860 if (resolvesCommentId){
846 postData['resolves_comment_id'] = resolvesCommentId;
861 postData['resolves_comment_id'] = resolvesCommentId;
847 }
862 }
848
863
849 var submitSuccessCallback = function(json_data) {
864 var submitSuccessCallback = function(json_data) {
850 $form.remove();
865 $form.remove();
851 try {
866 try {
852 var html = json_data.rendered_text;
867 var html = json_data.rendered_text;
853 var lineno = json_data.line_no;
868 var lineno = json_data.line_no;
854 var target_id = json_data.target_id;
869 var target_id = json_data.target_id;
855
870
856 $comments.find('.cb-comment-add-button').before(html);
871 $comments.find('.cb-comment-add-button').before(html);
857
872
858 //mark visually which comment was resolved
873 //mark visually which comment was resolved
859 if (resolvesCommentId) {
874 if (resolvesCommentId) {
860 commentForm.markCommentResolved(resolvesCommentId);
875 commentForm.markCommentResolved(resolvesCommentId);
861 }
876 }
862
877
863 // run global callback on submit
878 // run global callback on submit
864 commentForm.globalSubmitSuccessCallback();
879 commentForm.globalSubmitSuccessCallback();
865
880
866 } catch (e) {
881 } catch (e) {
867 console.error(e);
882 console.error(e);
868 }
883 }
869
884
870 // re trigger the linkification of next/prev navigation
885 // re trigger the linkification of next/prev navigation
871 linkifyComments($('.inline-comment-injected'));
886 linkifyComments($('.inline-comment-injected'));
872 timeagoActivate();
887 timeagoActivate();
873 tooltipActivate();
888 tooltipActivate();
874
889
875 if (window.updateSticky !== undefined) {
890 if (window.updateSticky !== undefined) {
876 // potentially our comments change the active window size, so we
891 // potentially our comments change the active window size, so we
877 // notify sticky elements
892 // notify sticky elements
878 updateSticky()
893 updateSticky()
879 }
894 }
880
895
881 commentForm.setActionButtonsDisabled(false);
896 commentForm.setActionButtonsDisabled(false);
882
897
883 };
898 };
884 var submitFailCallback = function(jqXHR, textStatus, errorThrown) {
899 var submitFailCallback = function(jqXHR, textStatus, errorThrown) {
885 var prefix = "Error while submitting comment.\n"
900 var prefix = "Error while submitting comment.\n"
886 var message = formatErrorMessage(jqXHR, textStatus, errorThrown, prefix);
901 var message = formatErrorMessage(jqXHR, textStatus, errorThrown, prefix);
887 ajaxErrorSwal(message);
902 ajaxErrorSwal(message);
888 commentForm.resetCommentFormState(text)
903 commentForm.resetCommentFormState(text)
889 };
904 };
890 commentForm.submitAjaxPOST(
905 commentForm.submitAjaxPOST(
891 commentForm.submitUrl, postData, submitSuccessCallback, submitFailCallback);
906 commentForm.submitUrl, postData, submitSuccessCallback, submitFailCallback);
892 });
907 });
893 }
908 }
894
909
895 $form.addClass('comment-inline-form-open');
910 $form.addClass('comment-inline-form-open');
896 };
911 };
897
912
898 this.createResolutionComment = function(commentId){
913 this.createResolutionComment = function(commentId){
899 // hide the trigger text
914 // hide the trigger text
900 $('#resolve-comment-{0}'.format(commentId)).hide();
915 $('#resolve-comment-{0}'.format(commentId)).hide();
901
916
902 var comment = $('#comment-'+commentId);
917 var comment = $('#comment-'+commentId);
903 var commentData = comment.data();
918 var commentData = comment.data();
904 if (commentData.commentInline) {
919 if (commentData.commentInline) {
905 this.createComment(comment, commentId)
920 this.createComment(comment, commentId)
906 } else {
921 } else {
907 Rhodecode.comments.createGeneralComment('general', "$placeholder", commentId)
922 Rhodecode.comments.createGeneralComment('general', "$placeholder", commentId)
908 }
923 }
909
924
910 return false;
925 return false;
911 };
926 };
912
927
913 this.submitResolution = function(commentId){
928 this.submitResolution = function(commentId){
914 var form = $('#resolve_comment_{0}'.format(commentId)).closest('form');
929 var form = $('#resolve_comment_{0}'.format(commentId)).closest('form');
915 var commentForm = form.get(0).CommentForm;
930 var commentForm = form.get(0).CommentForm;
916
931
917 var cm = commentForm.getCmInstance();
932 var cm = commentForm.getCmInstance();
918 var renderer = templateContext.visual.default_renderer;
933 var renderer = templateContext.visual.default_renderer;
919 if (renderer == 'rst'){
934 if (renderer == 'rst'){
920 var commentUrl = '`#{0} <{1}#comment-{0}>`_'.format(commentId, commentForm.selfUrl);
935 var commentUrl = '`#{0} <{1}#comment-{0}>`_'.format(commentId, commentForm.selfUrl);
921 } else if (renderer == 'markdown') {
936 } else if (renderer == 'markdown') {
922 var commentUrl = '[#{0}]({1}#comment-{0})'.format(commentId, commentForm.selfUrl);
937 var commentUrl = '[#{0}]({1}#comment-{0})'.format(commentId, commentForm.selfUrl);
923 } else {
938 } else {
924 var commentUrl = '{1}#comment-{0}'.format(commentId, commentForm.selfUrl);
939 var commentUrl = '{1}#comment-{0}'.format(commentId, commentForm.selfUrl);
925 }
940 }
926
941
927 cm.setValue(_gettext('TODO from comment {0} was fixed.').format(commentUrl));
942 cm.setValue(_gettext('TODO from comment {0} was fixed.').format(commentUrl));
928 form.submit();
943 form.submit();
929 return false;
944 return false;
930 };
945 };
931
946
932 };
947 };
General Comments 0
You need to be logged in to leave comments. Login now