1 // Copyright (C) 2010 Adam Barth. All rights reserved.
3 // Redistribution and use in source and binary forms, with or without
4 // modification, are permitted provided that the following conditions are met:
6 // 1. Redistributions of source code must retain the above copyright notice,
7 // this list of conditions and the following disclaimer.
9 // 2. Redistributions in binary form must reproduce the above copyright notice,
10 // this list of conditions and the following disclaimer in the documentation
11 // and/or other materials provided with the distribution.
13 // THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS "AS IS" AND ANY
14 // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
15 // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
16 // DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR
17 // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18 // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
19 // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
20 // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
21 // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
22 // OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
24 var CODE_REVIEW_UNITTEST;
28 * Create a new function with some of its arguements
30 * Taken from goog.partial in the Closure library.
31 * @param {Function} fn A function to partially apply.
32 * @param {...*} var_args Additional arguments that are partially
34 * @return {!Function} A partially-applied form of the function.
36 function partial(fn, var_args) {
37 var args = Array.prototype.slice.call(arguments, 1);
39 // Prepend the bound arguments to the current arguments.
40 var newArgs = Array.prototype.slice.call(arguments);
41 newArgs.unshift.apply(newArgs, args);
42 return fn.apply(this, newArgs);
46 function determineAttachmentID() {
48 return /id=(\d+)/.exec(window.location.search)[1]
54 // Attempt to activate only in the "Review Patch" context.
55 if (window.top != window)
58 if (!CODE_REVIEW_UNITTEST && !window.location.search.match(/action=review/)
59 && !window.location.toString().match(/bugs\.webkit\.org\/PrettyPatch/))
62 var attachment_id = determineAttachmentID();
64 console.log('No attachment ID');
68 var original_file_contents = {};
69 var patched_file_contents = {};
70 var WEBKIT_BASE_DIR = "http://svn.webkit.org/repository/webkit/trunk/";
71 var SIDE_BY_SIDE_DIFFS_KEY = 'sidebysidediffs';
72 var g_displayed_draft_comments = false;
85 function idForLine(number) {
86 return 'line' + number;
89 function nextLineID() {
90 return idForLine(next_line_id++);
93 function forEachLine(callback) {
94 for (var i = 0; i < next_line_id; ++i) {
95 callback($('#' + idForLine(i)));
100 this.id = nextLineID();
103 function hoverify() {
104 $(this).hover(function() {
105 $(this).addClass('hot');
108 $(this).removeClass('hot');
112 function fileDiffFor(line) {
113 return $(line).parents('.FileDiff');
116 function diffSectionFor(line) {
117 return $(line).parents('.DiffSection');
120 function activeCommentFor(line) {
121 // Scope to the diffSection as a performance improvement.
122 return $('textarea[data-comment-for~="' + line[0].id + '"]', fileDiffFor(line));
125 function previousCommentsFor(line) {
126 // Scope to the diffSection as a performance improvement.
127 return $('div[data-comment-for~="' + line[0].id + '"].previousComment', fileDiffFor(line));
130 function findCommentPositionFor(line) {
131 var previous_comments = previousCommentsFor(line);
132 var num_previous_comments = previous_comments.size();
133 if (num_previous_comments)
134 return $(previous_comments[num_previous_comments - 1])
138 function findCommentBlockFor(line) {
139 var comment_block = findCommentPositionFor(line).next();
140 if (!comment_block.hasClass('comment'))
142 return comment_block;
145 function insertCommentFor(line, block) {
146 findCommentPositionFor(line).after(block);
149 function addDraftComment(start_line_id, end_line_id, contents) {
150 var line = $('#' + end_line_id);
151 var start = numberFrom(start_line_id);
152 var end = numberFrom(end_line_id);
153 for (var i = start; i <= end; i++) {
154 addDataCommentBaseLine($('#line' + i), end_line_id);
157 var comment_block = createCommentFor(line);
158 $(comment_block).children('textarea').val(contents);
159 freezeComment(comment_block);
162 function ensureDraftCommentsDisplayed() {
163 if (g_displayed_draft_comments)
165 g_displayed_draft_comments = true;
167 var comments = g_draftCommentSaver.saved_comments();
168 $(comments.comments).each(function() {
169 addDraftComment(this.start_line_id, this.end_line_id, this.contents);
172 var overall_comments = comments['overall-comments'];
173 if (overall_comments) {
174 openOverallComments();
175 $('.overallComments textarea').val(overall_comments);
179 function DraftCommentSaver(opt_attachment_id, opt_localStorage) {
180 this._attachment_id = opt_attachment_id || attachment_id;
181 this._localStorage = opt_localStorage || localStorage;
182 this._save_comments = true;
185 if (CODE_REVIEW_UNITTEST)
186 window['DraftCommentSaver'] = DraftCommentSaver;
188 DraftCommentSaver.prototype._json = function() {
189 var comments = $('.comment');
190 var comment_store = [];
191 comments.each(function () {
192 var file_diff = fileDiffFor(this);
193 var textarea = $('textarea', this);
195 var contents = textarea.val().trim();
199 var comment_base_line = textarea.attr('data-comment-for');
200 var lines = contextLinesFor(comment_base_line, file_diff);
203 start_line_id: lines.first().attr('id'),
204 end_line_id: comment_base_line,
209 var overall_comments = $('.overallComments textarea').val().trim();
210 return JSON.stringify({'born-on': Date.now(), 'comments': comment_store, 'overall-comments': overall_comments});
213 DraftCommentSaver.prototype.saved_comments = function() {
214 var serialized_comments = this._localStorage.getItem(DraftCommentSaver._keyPrefix + this._attachment_id);
215 if (!serialized_comments)
220 comments = JSON.parse(serialized_comments);
222 this._erase_corrupt_comments();
226 var individual_comments = comments.comments;
227 if (comments && !individual_comments.length)
230 // Sanity check comments are as expected.
231 if (!comments || !individual_comments[0].contents) {
232 this._erase_corrupt_comments();
239 DraftCommentSaver.prototype._erase_corrupt_comments = function() {
240 // FIXME: Show an error to the user instead of logging.
241 console.log('Draft comments were corrupted. Erasing comments.');
245 DraftCommentSaver.prototype.save = function() {
246 if (!this._save_comments)
249 var key = DraftCommentSaver._keyPrefix + this._attachment_id;
250 var value = this._json();
252 if (this._attemptToWrite(key, value))
255 this._eraseOldCommentsForAllReviews();
256 if (this._attemptToWrite(key, value))
259 var remove_comments = this._should_remove_comments();
260 if (!remove_comments) {
261 this._save_comments = false;
265 this._eraseCommentsForAllReviews();
266 if (this._attemptToWrite(key, value))
269 this._save_comments = false;
270 // FIXME: Show an error to the user.
273 DraftCommentSaver.prototype._should_remove_comments = function(message) {
274 return prompt('Local storage quota is full. Remove draft comments from all previous reviews to make room?');
277 DraftCommentSaver.prototype._attemptToWrite = function(key, value) {
279 this._localStorage.setItem(key, value);
286 DraftCommentSaver._keyPrefix = 'draft-comments-for-attachment-';
288 DraftCommentSaver.prototype.erase = function() {
289 this._localStorage.removeItem(DraftCommentSaver._keyPrefix + this._attachment_id);
292 DraftCommentSaver.prototype._eraseOldCommentsForAllReviews = function() {
293 this._eraseComments(true);
295 DraftCommentSaver.prototype._eraseCommentsForAllReviews = function() {
296 this._eraseComments(false);
299 var MONTH_IN_MS = 1000 * 60 * 60 * 24 * 30;
301 DraftCommentSaver.prototype._eraseComments = function(only_old_reviews) {
302 var length = this._localStorage.length;
303 var keys_to_delete = [];
304 for (var i = 0; i < length; i++) {
305 var key = this._localStorage.key(i);
306 if (key.indexOf(DraftCommentSaver._keyPrefix) != 0)
309 if (only_old_reviews) {
311 var born_on = JSON.parse(this._localStorage.getItem(key))['born-on'];
312 if (Date.now() - born_on < MONTH_IN_MS)
315 console.log('Deleting JSON. JSON for code review is corrupt: ' + key);
318 keys_to_delete.push(key);
321 for (var i = 0; i < keys_to_delete.length; i++) {
322 this._localStorage.removeItem(keys_to_delete[i]);
326 var g_draftCommentSaver = new DraftCommentSaver();
328 function saveDraftComments() {
329 ensureDraftCommentsDisplayed();
330 g_draftCommentSaver.save();
331 setAutoSaveStateIndicator('saved');
334 function setAutoSaveStateIndicator(state) {
335 var container = $('.autosave-state');
336 container.text(state);
338 if (state == 'saving')
339 container.addClass(state);
341 container.removeClass('saving');
344 function unfreezeCommentFor(line) {
345 // FIXME: This query is overly complex because we place comment blocks
346 // after Lines. Instead, comment blocks should be children of Lines.
347 findCommentPositionFor(line).next().next().filter('.frozenComment').each(handleUnfreezeComment);
350 function createCommentFor(line) {
351 if (line.attr('data-has-comment')) {
352 unfreezeCommentFor(line);
355 line.attr('data-has-comment', 'true');
356 line.addClass('commentContext');
358 var comment_block = $('<div class="comment"><textarea data-comment-for="' + line.attr('id') + '"></textarea><div class="actions"><button class="ok">OK</button><button class="discard">Discard</button></div></div>');
359 $('textarea', comment_block).bind('input', handleOverallCommentsInput);
360 insertCommentFor(line, comment_block);
361 return comment_block;
364 function addCommentFor(line) {
365 var comment_block = createCommentFor(line);
369 comment_block.hide().slideDown('fast', function() {
370 $(this).children('textarea').focus();
374 function addCommentField(comment_block) {
375 var id = $(comment_block).attr('data-comment-for');
377 id = comment_block.id;
378 addCommentFor($('#' + id));
381 function handleAddCommentField() {
382 addCommentField(this);
385 function addPreviousComment(line, author, comment_text) {
386 var line_id = line.attr('id');
387 var comment_block = $('<div data-comment-for="' + line_id + '" class="previousComment"></div>');
388 var author_block = $('<div class="author"></div>').text(author + ':');
389 var text_block = $('<div class="content"></div>').text(comment_text);
390 comment_block.append(author_block).append(text_block).each(hoverify).click(handleAddCommentField);
391 addDataCommentBaseLine(line, line_id);
392 insertCommentFor(line, comment_block);
395 function displayPreviousComments(comments) {
396 for (var i = 0; i < comments.length; ++i) {
397 var author = comments[i].author;
398 var file_name = comments[i].file_name;
399 var line_number = comments[i].line_number;
400 var comment_text = comments[i].comment_text;
402 var file = files[file_name];
404 var query = '.Line .to';
405 if (line_number[0] == '-') {
406 // The line_number represent a removal. We need to adjust the query to
407 // look at the "from" lines.
408 query = '.Line .from';
409 // Trim off the '-' control character.
410 line_number = line_number.substr(1);
413 $(file).find(query).each(function() {
414 if ($(this).text() != line_number)
416 var line = $(this).parent();
417 addPreviousComment(line, author, comment_text);
421 if (comments.length == 0) {
425 descriptor = comments.length + ' comment';
426 if (comments.length > 1)
428 $('.help .more').before(' This patch has ' + descriptor + '. Scroll through them with the "n" and "p" keys. ');
431 function showMoreHelp() {
432 $('.more-help').removeClass('inactive');
435 function hideMoreHelp() {
436 $('.more-help').addClass('inactive');
439 function scanForStyleQueueComments(text) {
441 var lines = text.split('\n');
442 for (var i = 0; i < lines.length; ++i) {
443 var parts = lines[i].match(/^([^:]+):(-?\d+):(.*)$/);
447 var file_name = parts[1];
448 var line_number = parts[2];
449 var comment_text = parts[3].trim();
451 if (!file_name in files) {
452 console.log('Filename in style queue output is not in the patch: ' + file_name);
457 'author': 'StyleQueue',
458 'file_name': file_name,
459 'line_number': line_number,
460 'comment_text': comment_text
466 function scanForComments(author, text) {
468 var lines = text.split('\n');
469 for (var i = 0; i < lines.length; ++i) {
470 var parts = lines[i].match(/^([> ]+)([^:]+):(-?\d+)$/);
473 var quote_markers = parts[1];
474 var file_name = parts[2];
475 // FIXME: Store multiple lines for multiline comments and correctly import them here.
476 var line_number = parts[3];
477 if (!file_name in files)
479 while (i < lines.length && lines[i].length > 0 && lines[i][0] == '>')
481 var comment_lines = [];
482 while (i < lines.length && (lines[i].length == 0 || lines[i][0] != '>')) {
483 comment_lines.push(lines[i]);
486 --i; // Decrement i because the for loop will increment it again in a second.
487 var comment_text = comment_lines.join('\n').trim();
490 'file_name': file_name,
491 'line_number': line_number,
492 'comment_text': comment_text
498 function isReviewFlag(select) {
499 return $(select).attr('title') == 'Request for patch review.';
502 function isCommitQueueFlag(select) {
503 return $(select).attr('title').match(/commit-queue/);
506 function findControlForFlag(select) {
507 if (isReviewFlag(select))
508 return $('#toolbar .review select');
509 else if (isCommitQueueFlag(select))
510 return $('#toolbar .commitQueue select');
514 function addFlagsForAttachment(details) {
515 var flag_control = "<select><option></option><option>?</option><option>+</option><option>-</option></select>";
516 $('#flagContainer').append(
517 $('<span class="review"> r: ' + flag_control + '</span>')).append(
518 $('<span class="commitQueue"> cq: ' + flag_control + '</span>'));
520 details.find('#flags select').each(function() {
521 var requestee = $(this).parent().siblings('td:first-child').text().trim();
522 if (requestee.length) {
523 // Remove trailing ':'.
524 requestee = requestee.substr(0, requestee.length - 1);
525 requestee = ' (' + requestee + ')';
527 var control = findControlForFlag(this)
528 control.attr('selectedIndex', $(this).attr('selectedIndex'));
529 control.parent().prepend(requestee);
533 window.addEventListener('message', function(e) {
534 if (e.origin != 'https://webkit-commit-queue.appspot.com')
538 $('.statusBubble')[0].style.height = e.data.height;
539 $('.statusBubble')[0].style.width = e.data.width;
543 function handleStatusBubbleLoad(e) {
544 e.target.contentWindow.postMessage('containerMetrics', 'https://webkit-commit-queue.appspot.com');
547 function fetchHistory() {
548 $.get('attachment.cgi?id=' + attachment_id + '&action=edit', function(data) {
549 var bug_id = /Attachment \d+ Details for Bug (\d+)/.exec(data)[1];
550 $.get('show_bug.cgi?id=' + bug_id, function(data) {
552 $(data).find('.bz_comment').each(function() {
553 var author = $(this).find('.email').text();
554 var text = $(this).find('.bz_comment_text').text();
556 var comment_marker = '(From update of attachment ' + attachment_id + ' .details.)';
557 if (text.match(comment_marker))
558 $.merge(comments, scanForComments(author, text));
560 var style_queue_comment_marker = 'Attachment ' + attachment_id + ' .details. did not pass style-queue.'
561 if (text.match(style_queue_comment_marker))
562 $.merge(comments, scanForStyleQueueComments(text));
564 displayPreviousComments(comments);
565 ensureDraftCommentsDisplayed();
568 var details = $(data);
569 addFlagsForAttachment(details);
571 var statusBubble = document.createElement('iframe');
572 statusBubble.className = 'statusBubble';
573 statusBubble.src = 'https://webkit-commit-queue.appspot.com/status-bubble/' + attachment_id;
574 statusBubble.scrolling = 'no';
575 // Can't append the HTML because we need to set the onload handler before appending the iframe to the DOM.
576 statusBubble.onload = handleStatusBubbleLoad;
577 $('#statusBubbleContainer').append(statusBubble);
579 $('#toolbar .bugLink').html('<a href="/show_bug.cgi?id=' + bug_id + '" target="_blank">Bug ' + bug_id + '</a>');
583 function firstLine(file_diff) {
584 var container = $('.LineContainer:not(.context)', file_diff)[0];
588 var from = fromLineNumber(container);
589 var to = toLineNumber(container);
593 function crawlDiff() {
594 $('.Line').each(idify).each(hoverify);
595 $('.FileDiff').each(function() {
596 var header = $(this).children('h1');
597 var url_hash = '#L' + firstLine(this);
599 var file_name = header.text();
600 files[file_name] = this;
602 addExpandLinks(file_name);
604 var diff_links = $('<div class="FileDiffLinkContainer LinkContainer">' +
608 var file_link = $('a', header)[0];
609 // If the base directory in the file path does not match a WebKit top level directory,
610 // then PrettyPatch.rb doesn't linkify the header.
612 file_link.target = "_blank";
613 file_link.href += url_hash;
614 diff_links.append(tracLinks(file_name, url_hash));
617 $('h1', this).after(diff_links);
618 updateDiffLinkVisibility(this);
622 function tracLinks(file_name, url_hash) {
623 var trac_links = $('<a target="_blank">annotate</a><a target="_blank">revision log</a>');
624 trac_links[0].href = 'http://trac.webkit.org/browser/trunk/' + file_name + '?annotate=blame' + url_hash;
625 trac_links[1].href = 'http://trac.webkit.org/log/trunk/' + file_name;
629 function addExpandLinks(file_name) {
630 if (file_name.indexOf('ChangeLog') != -1)
633 var file_diff = files[file_name];
635 // Don't show the links to expand upwards/downwards if the patch starts/ends without context
636 // lines, i.e. starts/ends with add/remove lines.
637 var first_line = file_diff.querySelector('.LineContainer:not(.context)');
639 // If there is no element with a "Line" class, then this is an image diff.
643 var expand_bar_index = 0;
644 if (!$(first_line).hasClass('add') && !$(first_line).hasClass('remove'))
645 $('h1', file_diff).after(expandBarHtml(BELOW))
647 $('br', file_diff).replaceWith(expandBarHtml());
649 var last_line = file_diff.querySelector('.LineContainer:last-of-type');
650 // Some patches for new files somehow end up with an empty context line at the end
651 // with a from line number of 0. Don't show expand links in that case either.
652 if (!$(last_line).hasClass('add') && !$(last_line).hasClass('remove') && fromLineNumber(last_line) != 0)
653 $('.revision', file_diff).before(expandBarHtml(ABOVE));
656 function expandBarHtml(opt_direction) {
657 var html = '<div class="ExpandBar">' +
658 '<div class="ExpandArea Expand' + ABOVE + '"></div>' +
659 '<div class="ExpandLinkContainer LinkContainer"><span class="ExpandText">expand: </span>';
661 // FIXME: If there are <100 line to expand, don't show the expand-100 link.
662 // If there are <20 lines to expand, don't show the expand-20 link.
663 if (!opt_direction || opt_direction == ABOVE) {
664 html += expandLinkHtml(ABOVE, 100) +
665 expandLinkHtml(ABOVE, 20);
668 html += expandLinkHtml(ALL);
670 if (!opt_direction || opt_direction == BELOW) {
671 html += expandLinkHtml(BELOW, 20) +
672 expandLinkHtml(BELOW, 100);
675 html += '</div><div class="ExpandArea Expand' + BELOW + '"></div></div>';
679 function expandLinkHtml(direction, amount) {
680 return "<a class='ExpandLink' href='javascript:' data-direction='" + direction + "' data-amount='" + amount + "'>" +
681 (amount ? amount + " " : "") + direction + "</a>";
684 function handleExpandLinkClick() {
685 var expand_bar = $(this).parents('.ExpandBar');
686 var file_name = expand_bar.parents('.FileDiff').children('h1')[0].textContent;
687 var expand_function = partial(expand, expand_bar[0], file_name, this.getAttribute('data-direction'), Number(this.getAttribute('data-amount')));
688 if (file_name in original_file_contents)
691 getWebKitSourceFile(file_name, expand_function, expand_bar);
694 function handleSideBySideLinkClick() {
695 convertDiff('sidebyside', this);
698 function handleUnifyLinkClick() {
699 convertDiff('unified', this);
702 function convertDiff(difftype, convert_link) {
703 var file_diffs = $(convert_link).parents('.FileDiff');
704 if (!file_diffs.size()) {
705 localStorage.setItem('code-review-diffstate', difftype);
706 file_diffs = $('.FileDiff');
709 convertAllFileDiffs(difftype, file_diffs);
712 function patchRevision() {
713 var revision = $('.revision');
714 return revision[0] ? revision.first().text() : null;
717 function getWebKitSourceFile(file_name, onLoad, expand_bar) {
718 function handleLoad(contents) {
719 original_file_contents[file_name] = contents.split('\n');
720 patched_file_contents[file_name] = applyDiff(original_file_contents[file_name], file_name);
724 var revision = patchRevision();
725 var queryParameters = revision ? '?p=' + revision : '';
728 url: WEBKIT_BASE_DIR + file_name + queryParameters,
729 context: document.body,
730 complete: function(xhr, data) {
732 handleLoadError(expand_bar);
734 handleLoad(xhr.responseText);
739 function replaceExpandLinkContainers(expand_bar, text) {
740 $('.ExpandLinkContainer', $(expand_bar).parents('.FileDiff')).replaceWith('<span class="ExpandText">' + text + '</span>');
743 function handleLoadError(expand_bar) {
744 replaceExpandLinkContainers(expand_bar, "Can't expand. Is this a new or deleted file?");
751 function lineNumbersFromSet(set, is_last) {
755 var size = set.size();
756 var start = is_last ? (size - 1) : 0;
757 var end = is_last ? -1 : size;
758 var offset = is_last ? -1 : 1;
760 for (var i = start; i != end; i += offset) {
761 if (to != -1 && from != -1)
762 return {to: to, from: from};
764 var line_number = set[i];
765 if ($(line_number).hasClass('to')) {
767 to = Number(line_number.textContent);
770 from = Number(line_number.textContent);
775 function expand(expand_bar, file_name, direction, amount) {
776 if (file_name in original_file_contents && !patched_file_contents[file_name]) {
777 // FIXME: In this case, try fetching the source file at the revision the patch was created at.
778 // Might need to modify webkit-patch to include that data in the diff.
779 replaceExpandLinkContainers(expand_bar, "Can't expand. Unable to apply patch to tip of tree.");
783 var above_expansion = expand_bar.querySelector('.Expand' + ABOVE)
784 var below_expansion = expand_bar.querySelector('.Expand' + BELOW)
786 var above_line_numbers = $('.expansionLineNumber', above_expansion);
787 if (!above_line_numbers[0]) {
788 var diff_section = expand_bar.previousElementSibling;
789 above_line_numbers = $('.Line:not(.context) .lineNumber', diff_section);
792 var above_last_line_num, above_last_from_line_num;
793 if (above_line_numbers[0]) {
794 var above_numbers = lineNumbersFromSet(above_line_numbers, true);
795 above_last_line_num = above_numbers.to;
796 above_last_from_line_num = above_numbers.from;
798 above_last_from_line_num = above_last_line_num = 0;
800 var below_line_numbers = $('.expansionLineNumber', below_expansion);
801 if (!below_line_numbers[0]) {
802 var diff_section = expand_bar.nextElementSibling;
804 below_line_numbers = $('.Line:not(.context) .lineNumber', diff_section);
807 var below_first_line_num, below_first_from_line_num;
808 if (below_line_numbers[0]) {
809 var below_numbers = lineNumbersFromSet(below_line_numbers, false);
810 below_first_line_num = below_numbers.to - 1;
811 below_first_from_line_num = below_numbers.from - 1;
813 below_first_from_line_num = below_first_line_num = patched_file_contents[file_name].length - 1;
815 var start_line_num, start_from_line_num;
818 if (direction == ABOVE) {
819 start_from_line_num = above_last_from_line_num;
820 start_line_num = above_last_line_num;
821 end_line_num = Math.min(start_line_num + amount, below_first_line_num);
822 } else if (direction == BELOW) {
823 end_line_num = below_first_line_num;
824 start_line_num = Math.max(end_line_num - amount, above_last_line_num)
825 start_from_line_num = Math.max(below_first_from_line_num - amount, above_last_from_line_num)
826 } else { // direction == ALL
827 start_line_num = above_last_line_num;
828 start_from_line_num = above_last_from_line_num;
829 end_line_num = below_first_line_num;
832 var lines = expansionLines(file_name, expansion_area, direction, start_line_num, end_line_num, start_from_line_num);
835 // Filling in all the remaining lines. Overwrite the expand links.
836 if (start_line_num == above_last_line_num && end_line_num == below_first_line_num) {
837 $('.ExpandLinkContainer', expand_bar).detach();
838 below_expansion.insertBefore(lines, below_expansion.firstChild);
839 // Now that we're filling in all the lines, the context line following this expand bar is no longer needed.
840 $('.context', expand_bar.nextElementSibling).detach();
841 } else if (direction == ABOVE) {
842 above_expansion.appendChild(lines);
844 below_expansion.insertBefore(lines, below_expansion.firstChild);
848 function unifiedLine(from, to, contents, is_expansion_line, opt_className, opt_attributes) {
849 var className = is_expansion_line ? 'ExpansionLine' : 'LineContainer Line';
851 className += ' ' + opt_className;
853 var lineNumberClassName = is_expansion_line ? 'expansionLineNumber' : 'lineNumber';
855 var line = $('<div class="' + className + '" ' + (opt_attributes || '') + '>' +
856 '<span class="from ' + lineNumberClassName + '">' + (from || ' ') +
857 '</span><span class="to ' + lineNumberClassName + '">' + (to || ' ') +
858 '</span><span class="text"></span>' +
861 $('.text', line).replaceWith(contents);
865 function unifiedExpansionLine(from, to, contents) {
866 return unifiedLine(from, to, contents, true);
869 function sideBySideExpansionLine(from, to, contents) {
870 var line = $('<div class="ExpansionLine"></div>');
871 // Clone the contents so we have two copies we can put back in the DOM.
872 line.append(lineSide('from', contents.clone(true), true, from));
873 line.append(lineSide('to', contents, true, to));
877 function lineSide(side, contents, is_expansion_line, opt_line_number, opt_attributes, opt_class) {
879 if (opt_attributes || opt_class) {
880 class_name = 'class="';
882 class_name += is_expansion_line ? 'ExpansionLine' : 'Line';
883 class_name += ' ' + (opt_class || '') + '"';
886 var attributes = opt_attributes || '';
888 var line_side = $('<div class="LineSide">' +
889 '<div ' + attributes + ' ' + class_name + '>' +
890 '<span class="' + side + ' ' + (is_expansion_line ? 'expansionLineNumber' : 'lineNumber') + '">' +
891 (opt_line_number || ' ') +
893 '<span class="text"></span>' +
897 $('.text', line_side).replaceWith(contents);
901 function expansionLines(file_name, expansion_area, direction, start_line_num, end_line_num, start_from_line_num) {
902 var fragment = document.createDocumentFragment();
903 var is_side_by_side = isDiffSideBySide(files[file_name]);
905 for (var i = 0; i < end_line_num - start_line_num; i++) {
906 var from = start_from_line_num + i + 1;
907 var to = start_line_num + i + 1;
908 var contents = $('<span class="text"></span>');
909 contents.text(patched_file_contents[file_name][start_line_num + i]);
910 var line = is_side_by_side ? sideBySideExpansionLine(from, to, contents) : unifiedExpansionLine(from, to, contents);
911 fragment.appendChild(line[0]);
917 function hunkStartingLine(patched_file, context, prev_line, hunk_num) {
919 var current_line = -1;
920 var last_context_line = context[context.length - 1];
921 if (patched_file[prev_line] == last_context_line)
922 current_line = prev_line + 1;
924 for (var i = prev_line - PATCH_FUZZ; i < prev_line + PATCH_FUZZ; i++) {
925 if (patched_file[i] == last_context_line)
926 current_line = i + 1;
929 if (current_line == -1) {
930 console.log('Hunk #' + hunk_num + ' FAILED.');
935 // For paranoia sake, confirm the rest of the context matches;
936 for (var i = 0; i < context.length - 1; i++) {
937 if (patched_file[current_line - context.length + i] != context[i]) {
938 console.log('Hunk #' + hunk_num + ' FAILED. Did not match preceding context.');
946 function fromLineNumber(line) {
947 var node = line.querySelector('.from');
948 return node ? Number(node.textContent) : 0;
951 function toLineNumber(line) {
952 var node = line.querySelector('.to');
953 return node ? Number(node.textContent) : 0;
956 function textContentsFor(line) {
957 // Just get the first match since a side-by-side diff has two lines with text inside them for
958 // unmodified lines in the diff.
959 return $('.text', line).first().text();
962 function lineNumberForFirstNonContextLine(patched_file, line, prev_line, context, hunk_num) {
963 if (context.length) {
964 var prev_line_num = fromLineNumber(prev_line) - 1;
965 return hunkStartingLine(patched_file, context, prev_line_num, hunk_num);
968 if (toLineNumber(line) == 1 || fromLineNumber(line) == 1)
971 console.log('Failed to apply patch. Adds or removes lines before any context lines.');
975 function applyDiff(original_file, file_name) {
976 var diff_sections = files[file_name].getElementsByClassName('DiffSection');
977 var patched_file = original_file.concat([]);
979 // Apply diffs in reverse order to avoid needing to keep track of changing line numbers.
980 for (var i = diff_sections.length - 1; i >= 0; i--) {
981 var section = diff_sections[i];
982 var lines = $('.Line:not(.context)', section);
983 var current_line = -1;
985 var hunk_num = i + 1;
987 for (var j = 0, lines_len = lines.length; j < lines_len; j++) {
989 var line_contents = textContentsFor(line);
990 if ($(line).hasClass('add')) {
991 if (current_line == -1) {
992 current_line = lineNumberForFirstNonContextLine(patched_file, line, lines[j-1], context, hunk_num);
993 if (current_line == -1)
997 patched_file.splice(current_line, 0, line_contents);
999 } else if ($(line).hasClass('remove')) {
1000 if (current_line == -1) {
1001 current_line = lineNumberForFirstNonContextLine(patched_file, line, lines[j-1], context, hunk_num);
1002 if (current_line == -1)
1006 if (patched_file[current_line] != line_contents) {
1007 console.log('Hunk #' + hunk_num + ' FAILED.');
1011 patched_file.splice(current_line, 1);
1012 } else if (current_line == -1) {
1013 context.push(line_contents);
1014 } else if (line_contents != patched_file[current_line]) {
1015 console.log('Hunk #' + hunk_num + ' FAILED. Context at end did not match');
1023 return patched_file;
1026 function openOverallComments(e) {
1027 $('.overallComments textarea').addClass('open');
1028 $('#statusBubbleContainer').addClass('wrap');
1031 var g_overallCommentsInputTimer;
1033 function handleOverallCommentsInput() {
1034 setAutoSaveStateIndicator('saving');
1035 // Save draft comments after we haven't received an input event in 1 second.
1036 if (g_overallCommentsInputTimer)
1037 clearTimeout(g_overallCommentsInputTimer);
1038 g_overallCommentsInputTimer = setTimeout(saveDraftComments, 1000);
1041 function onBodyResize() {
1042 updateToolbarAnchorState();
1045 function updateToolbarAnchorState() {
1046 var toolbar = $('#toolbar');
1047 // Unanchor the toolbar and then see if it's bottom is below the body's bottom.
1048 toolbar.toggleClass('anchored', false);
1049 var toolbar_bottom = toolbar.offset().top + toolbar.outerHeight();
1050 var should_anchor = toolbar_bottom >= document.body.clientHeight;
1051 toolbar.toggleClass('anchored', should_anchor);
1054 function diffLinksHtml() {
1055 return '<a href="javascript:" class="unify-link">unified</a>' +
1056 '<a href="javascript:" class="side-by-side-link">side-by-side</a>';
1059 $(document).ready(function() {
1062 $(document.body).prepend('<div id="message">' +
1063 '<div class="help">Select line numbers to add a comment. Scroll though diffs with the "j" and "k" keys.' +
1064 '<div class="DiffLinks LinkContainer">' + diffLinksHtml() + '</div>' +
1065 '<a href="javascript:" class="more">[more]</a>' +
1066 '<div class="more-help inactive">' +
1067 '<div class="winter"></div>' +
1068 '<div class="lightbox"><table>' +
1069 '<tr><td>enter</td><td>add/edit comment for focused item</td></tr>' +
1070 '<tr><td>escape</td><td>accept current comment / close preview and help popups</td></tr>' +
1071 '<tr><td>j</td><td>focus next diff</td></tr>' +
1072 '<tr><td>k</td><td>focus previous diff</td></tr>' +
1073 '<tr><td>shift + j</td><td>focus next line</td></tr>' +
1074 '<tr><td>shift + k</td><td>focus previous line</td></tr>' +
1075 '<tr><td>n</td><td>focus next comment</td></tr>' +
1076 '<tr><td>p</td><td>focus previous comment</td></tr>' +
1077 '<tr><td>r</td><td>focus review select element</td></tr>' +
1078 '<tr><td>ctrl + shift + up</td><td>extend context of the focused comment</td></tr>' +
1079 '<tr><td>ctrl + shift + down</td><td>shrink context of the focused comment</td></tr>' +
1084 $(document.body).append('<div id="toolbar">' +
1085 '<div class="overallComments">' +
1086 '<textarea placeholder="Overall comments"></textarea>' +
1089 '<span id="statusBubbleContainer"></span>' +
1090 '<span class="actions">' +
1091 '<span class="links"><span class="bugLink"></span></span>' +
1092 '<span id="flagContainer"></span>' +
1093 '<button id="preview_comments">Preview</button>' +
1094 '<button id="post_comments">Publish</button> ' +
1097 '<div class="autosave-state"></div>' +
1100 $('.overallComments textarea').bind('click', openOverallComments);
1101 $('.overallComments textarea').bind('input', handleOverallCommentsInput);
1103 $(document.body).prepend('<div id="comment_form" class="inactive"><div class="winter"></div><div class="lightbox"><iframe id="reviewform" src="attachment.cgi?id=' + attachment_id + '&action=reviewform"></iframe></div></div>');
1104 $('#reviewform').bind('load', handleReviewFormLoad);
1106 // Create a dummy iframe and monitor resizes in it's contentWindow to detect when the top document's body changes size.
1107 // FIXME: Should we setTimeout throttle these?
1108 var resize_iframe = $('<iframe class="pseudo_resize_event_iframe"></iframe>');
1109 $(document.body).append(resize_iframe);
1110 // Handle the event on a timeout to avoid crashing Firefox.
1111 $(resize_iframe[0].contentWindow).bind('resize', function() { setTimeout(onBodyResize, 0)});
1113 updateToolbarAnchorState();
1117 function handleReviewFormLoad() {
1118 var review_form_contents = $('#reviewform').contents();
1119 if (review_form_contents[0].querySelector('#form-controls #flags')) {
1120 review_form_contents.bind('keydown', function(e) {
1121 if (e.keyCode == KEY_CODE.escape)
1125 // This is the intial load of the review form iframe.
1126 var form = review_form_contents.find('form')[0];
1127 form.addEventListener('submit', eraseDraftComments);
1132 // Review form iframe have the publish button has been pressed.
1133 var email_sent_to = review_form_contents[0].querySelector('#bugzilla-body dl');
1134 // If the email_send_to DL is not in the tree that means the publish failed for some reason,
1135 // e.g., you're not logged in. Show the comment form to allow you to login.
1136 if (!email_sent_to) {
1141 eraseDraftComments();
1142 // FIXME: Once WebKit supports seamless iframes, we can just make the review-form
1143 // iframe fill the page instead of redirecting back to the bug.
1144 window.location.replace($('#toolbar .bugLink a').attr('href'));
1147 function eraseDraftComments() {
1148 g_draftCommentSaver.erase();
1151 function loadDiffState() {
1152 var diffstate = localStorage.getItem('code-review-diffstate');
1153 if (diffstate != 'sidebyside' && diffstate != 'unified')
1156 convertAllFileDiffs(diffstate, $('.FileDiff'));
1159 function isDiffSideBySide(file_diff) {
1160 return diffState(file_diff) == 'sidebyside';
1163 function diffState(file_diff) {
1164 var diff_state = $(file_diff).attr('data-diffstate');
1165 return diff_state || 'unified';
1168 function unifyLine(line, from, to, contents, classNames, attributes, id) {
1169 var new_line = unifiedLine(from, to, contents, false, classNames, attributes);
1170 var old_line = $(line);
1171 if (!old_line.hasClass('LineContainer'))
1172 old_line = old_line.parents('.LineContainer');
1174 var comments = commentsToTransferFor($(document.getElementById(id)));
1175 old_line.after(comments);
1176 old_line.replaceWith(new_line);
1179 function updateDiffLinkVisibility(file_diff) {
1180 if (diffState(file_diff) == 'unified') {
1181 $('.side-by-side-link', file_diff).show();
1182 $('.unify-link', file_diff).hide();
1184 $('.side-by-side-link', file_diff).hide();
1185 $('.unify-link', file_diff).show();
1189 function convertAllFileDiffs(diff_type, file_diffs) {
1190 file_diffs.each(function() {
1191 convertFileDiff(diff_type, this);
1195 function convertFileDiff(diff_type, file_diff) {
1196 if (diffState(file_diff) == diff_type)
1199 $(file_diff).removeClass('sidebyside unified');
1200 $(file_diff).addClass(diff_type);
1202 $(file_diff).attr('data-diffstate', diff_type);
1203 updateDiffLinkVisibility(file_diff);
1205 $('.context', file_diff).each(function() {
1206 convertLine(diff_type, this);
1209 $('.shared .Line', file_diff).each(function() {
1210 convertLine(diff_type, this);
1213 $('.ExpansionLine', file_diff).each(function() {
1214 convertExpansionLine(diff_type, this);
1218 function convertLine(diff_type, line) {
1219 var convert_function = diff_type == 'sidebyside' ? sideBySideifyLine : unifyLine;
1220 var from = fromLineNumber(line);
1221 var to = toLineNumber(line);
1222 var contents = $('.text', line).first();
1223 var classNames = classNamesForMovingLine(line);
1224 var attributes = attributesForMovingLine(line);
1226 convert_function(line, from, to, contents, classNames, attributes, id)
1229 function classNamesForMovingLine(line) {
1230 var classParts = line.className.split(' ');
1231 var classBuffer = [];
1232 for (var i = 0; i < classParts.length; i++) {
1233 var part = classParts[i];
1234 if (part != 'LineContainer' && part != 'Line')
1235 classBuffer.push(part);
1237 return classBuffer.join(' ');
1240 function attributesForMovingLine(line) {
1241 var attributesBuffer = ['id=' + line.id];
1242 // Make sure to keep all data- attributes.
1243 $(line.attributes).each(function() {
1244 if (this.name.indexOf('data-') == 0)
1245 attributesBuffer.push(this.name + '=' + this.value);
1247 return attributesBuffer.join(' ');
1250 function sideBySideifyLine(line, from, to, contents, classNames, attributes, id) {
1251 var from_class = '';
1253 var from_attributes = '';
1254 var to_attributes = '';
1255 // Clone the contents so we have two copies we can put back in the DOM.
1256 var from_contents = contents.clone(true);
1257 var to_contents = contents;
1259 var container_class = 'LineContainer';
1260 var container_attributes = '';
1262 if (from && !to) { // This is a remove line.
1263 from_class = classNames;
1264 from_attributes = attributes;
1266 } else if (to && !from) { // This is an add line.
1267 to_class = classNames;
1268 to_attributes = attributes;
1271 container_attributes = attributes;
1272 container_class += ' Line ' + classNames;
1275 var new_line = $('<div ' + container_attributes + ' class="' + container_class + '"></div>');
1276 new_line.append(lineSide('from', from_contents, false, from, from_attributes, from_class));
1277 new_line.append(lineSide('to', to_contents, false, to, to_attributes, to_class));
1279 $(line).replaceWith(new_line);
1281 var line = $(document.getElementById(id));
1282 line.after(commentsToTransferFor(line));
1285 function convertExpansionLine(diff_type, line) {
1286 var convert_function = diff_type == 'sidebyside' ? sideBySideExpansionLine : unifiedExpansionLine;
1287 var contents = $('.text', line).first();
1288 var from = fromLineNumber(line);
1289 var to = toLineNumber(line);
1290 var new_line = convert_function(from, to, contents);
1291 $(line).replaceWith(new_line);
1294 function commentsToTransferFor(line) {
1295 var fragment = document.createDocumentFragment();
1297 previousCommentsFor(line).each(function() {
1298 fragment.appendChild(this);
1301 var active_comments = activeCommentFor(line);
1302 var num_active_comments = active_comments.size();
1303 if (num_active_comments > 0) {
1304 if (num_active_comments > 1)
1305 console.log('ERROR: There is more than one active comment for ' + line.attr('id') + '.');
1307 var parent = active_comments[0].parentNode;
1308 var frozenComment = parent.nextSibling;
1309 fragment.appendChild(parent);
1310 fragment.appendChild(frozenComment);
1316 function discardComment(comment_block) {
1317 var line_id = comment_block.find('textarea').attr('data-comment-for');
1318 var line = $('#' + line_id)
1319 findCommentBlockFor(line).slideUp('fast', function() {
1321 line.removeAttr('data-has-comment');
1322 trimCommentContextToBefore(line, line.attr('data-comment-base-line'));
1323 saveDraftComments();
1327 function handleUnfreezeComment() {
1328 unfreezeComment(this);
1331 function unfreezeComment(comment) {
1332 var unfrozen_comment = $(comment).prev();
1333 unfrozen_comment.show();
1334 $(comment).remove();
1335 unfrozen_comment.find('textarea')[0].focus();
1338 function showFileDiffLinks() {
1339 $('.LinkContainer', this).each(function() { this.style.opacity = 1; });
1342 function hideFileDiffLinks() {
1343 $('.LinkContainer', this).each(function() { this.style.opacity = 0; });
1346 function handleDiscardComment() {
1347 discardComment($(this).parents('.comment'));
1350 function handleAcceptComment() {
1351 acceptComment($(this).parents('.comment'));
1354 function acceptComment(comment) {
1355 freezeComment(comment);
1356 saveDraftComments();
1359 $('.FileDiff').live('mouseenter', showFileDiffLinks);
1360 $('.FileDiff').live('mouseleave', hideFileDiffLinks);
1361 $('.side-by-side-link').live('click', handleSideBySideLinkClick);
1362 $('.unify-link').live('click', handleUnifyLinkClick);
1363 $('.ExpandLink').live('click', handleExpandLinkClick);
1364 $('.frozenComment').live('click', handleUnfreezeComment);
1365 $('.comment .discard').live('click', handleDiscardComment);
1366 $('.comment .ok').live('click', handleAcceptComment);
1367 $('.more').live('click', showMoreHelp);
1368 $('.more-help .winter').live('click', hideMoreHelp);
1370 function freezeComment(comment_block) {
1371 var comment_textarea = comment_block.find('textarea');
1372 if (comment_textarea.val().trim() == '') {
1373 discardComment(comment_block);
1376 var line_id = comment_textarea.attr('data-comment-for');
1377 var line = $('#' + line_id)
1378 findCommentBlockFor(line).hide().after($('<div class="frozenComment"></div>').text(comment_textarea.val()));
1381 function focusOn(node) {
1382 if (node.length == 0)
1385 // Give a tabindex so the element can receive actual browser focus.
1386 // -1 makes the element focusable without actually putting in in the tab order.
1387 node.attr('tabindex', -1);
1389 // Remove the tabindex on blur to avoid having the node be mouse-focusable.
1390 node.bind('blur', function() { node.removeAttr('tabindex'); });
1391 $(document).scrollTop(node.position().top - window.innerHeight / 2);
1394 function focusNext(filter, direction) {
1395 var focusable_nodes = $('a,.Line,.frozenComment,.previousComment,.DiffBlock,.overallComments').filter(function() {
1396 return !$(this).hasClass('DiffBlock') || $('.add,.remove', this).size();
1399 var is_backward = direction == DIRECTION.BACKWARD;
1400 var index = focusable_nodes.index($(document.activeElement));
1401 if (index == -1 && is_backward)
1402 index = focusable_nodes.length;
1404 var offset = is_backward ? -1 : 1;
1405 var end = is_backward ? -1 : focusable_nodes.size();
1406 for (var i = index + offset; i != end; i = i + offset) {
1407 var node = $(focusable_nodes[i]);
1416 var DIRECTION = {FORWARD: 1, BACKWARD: 2};
1418 function isComment(node) {
1419 return node.hasClass('frozenComment') || node.hasClass('previousComment') || node.hasClass('overallComments');
1422 function isDiffBlock(node) {
1423 return node.hasClass('DiffBlock');
1426 function isLine(node) {
1427 return node.hasClass('Line');
1430 function commentTextareaForKeyTarget(key_target) {
1431 if (key_target.nodeName == 'TEXTAREA')
1432 return $(key_target);
1434 var comment_textarea = $(document.activeElement).prev().find('textarea');
1435 if (!comment_textarea.size())
1437 return comment_textarea;
1440 function extendCommentContextUp(key_target) {
1441 var comment_textarea = commentTextareaForKeyTarget(key_target);
1442 if (!comment_textarea)
1445 var comment_base_line = comment_textarea.attr('data-comment-for');
1446 var diff_section = diffSectionFor(comment_textarea);
1447 var lines = $('.Line', diff_section);
1448 for (var i = 0; i < lines.length - 1; i++) {
1449 if (hasDataCommentBaseLine(lines[i + 1], comment_base_line)) {
1450 addDataCommentBaseLine(lines[i], comment_base_line);
1456 function shrinkCommentContextDown(key_target) {
1457 var comment_textarea = commentTextareaForKeyTarget(key_target);
1458 if (!comment_textarea)
1461 var comment_base_line = comment_textarea.attr('data-comment-for');
1462 var diff_section = diffSectionFor(comment_textarea);
1463 var lines = contextLinesFor(comment_base_line, diff_section);
1464 if (lines.size() > 1)
1465 removeDataCommentBaseLine(lines[0], comment_base_line);
1468 function handleModifyContextKey(e) {
1469 var handled = false;
1471 if (e.shiftKey && e.ctrlKey) {
1472 switch (e.keyCode) {
1474 extendCommentContextUp(e.target);
1479 shrinkCommentContextDown(e.target);
1491 $('textarea').live('keydown', function(e) {
1492 if (handleModifyContextKey(e))
1495 if (e.keyCode == KEY_CODE.escape)
1496 handleEscapeKeyInTextarea(this);
1499 $('body').live('keydown', function(e) {
1500 // FIXME: There's got to be a better way to avoid seeing these keypress
1502 if (e.target.nodeName == 'TEXTAREA')
1505 // Don't want to override browser shortcuts like ctrl+r.
1506 if (e.metaKey || e.ctrlKey)
1509 if (handleModifyContextKey(e))
1512 var handled = false;
1513 switch (e.keyCode) {
1515 $('.review select').focus();
1520 handled = focusNext(isComment, DIRECTION.FORWARD);
1524 handled = focusNext(isComment, DIRECTION.BACKWARD);
1529 handled = focusNext(isLine, DIRECTION.FORWARD);
1531 handled = focusNext(isDiffBlock, DIRECTION.FORWARD);
1536 handled = focusNext(isLine, DIRECTION.BACKWARD);
1538 handled = focusNext(isDiffBlock, DIRECTION.BACKWARD);
1541 case KEY_CODE.enter:
1542 handled = handleEnterKey();
1545 case KEY_CODE.escape:
1555 function handleEscapeKeyInTextarea(textarea) {
1556 var comment = $(textarea).parents('.comment');
1558 acceptComment(comment);
1561 document.body.focus();
1564 function handleEnterKey() {
1565 if (document.activeElement.nodeName == 'BODY')
1568 var focused = $(document.activeElement);
1570 if (focused.hasClass('frozenComment')) {
1571 unfreezeComment(focused);
1575 if (focused.hasClass('overallComments')) {
1576 openOverallComments();
1577 focused.find('textarea')[0].focus();
1581 if (focused.hasClass('previousComment')) {
1582 addCommentField(focused);
1586 var lines = focused.hasClass('Line') ? focused : $('.Line', focused);
1587 var last = lines.last();
1588 if (last.attr('data-has-comment')) {
1589 unfreezeCommentFor(last);
1593 addCommentForLines(lines);
1597 function contextLinesFor(comment_base_lines, file_diff) {
1598 var base_lines = comment_base_lines.split(' ');
1599 return $('div[data-comment-base-line]', file_diff).filter(function() {
1600 return $(this).attr('data-comment-base-line').split(' ').some(function(item) {
1601 return base_lines.indexOf(item) != -1;
1606 function numberFrom(line_id) {
1607 return Number(line_id.replace('line', ''));
1610 function trimCommentContextToBefore(line, comment_base_line) {
1611 var line_to_trim_to = numberFrom(line.attr('id'));
1612 contextLinesFor(comment_base_line, fileDiffFor(line)).each(function() {
1613 var id = $(this).attr('id');
1614 if (numberFrom(id) > line_to_trim_to)
1617 removeDataCommentBaseLine(this, comment_base_line);
1621 var drag_select_start_index = -1;
1623 function lineOffsetFrom(line, offset) {
1624 var file_diff = line.parents('.FileDiff');
1625 var all_lines = $('.Line', file_diff);
1626 var index = all_lines.index(line);
1627 return $(all_lines[index + offset]);
1630 function previousLineFor(line) {
1631 return lineOffsetFrom(line, -1);
1634 function nextLineFor(line) {
1635 return lineOffsetFrom(line, 1);
1638 $(document.body).bind('mouseup', processSelectedLines);
1640 $('.lineNumber').live('click', function(e) {
1641 var line = lineFromLineDescendant($(this));
1642 if (line.hasClass('commentContext'))
1643 trimCommentContextToBefore(previousLineFor(line), line.attr('data-comment-base-line'));
1644 else if (e.shiftKey)
1645 extendCommentContextTo(line);
1646 }).live('mousedown', function(e) {
1647 // preventDefault to avoid selecting text when dragging to select comment context lines.
1648 // FIXME: should we use user-modify CSS instead?
1653 var line = lineFromLineDescendant($(this));
1654 drag_select_start_index = numberFrom(line.attr('id'));
1655 line.addClass('selected');
1658 $('.LineContainer').live('mouseenter', function(e) {
1659 if (drag_select_start_index == -1 || e.shiftKey)
1661 selectToLineContainer(this);
1662 }).live('mouseup', function(e) {
1663 if (drag_select_start_index == -1 || e.shiftKey)
1666 selectToLineContainer(this);
1667 processSelectedLines();
1670 function extendCommentContextTo(line) {
1671 var diff_section = diffSectionFor(line);
1672 var lines = $('.Line', diff_section);
1673 var lines_to_modify = [];
1674 var have_seen_start_line = false;
1675 var data_comment_base_line = null;
1676 lines.each(function() {
1677 if (data_comment_base_line)
1680 have_seen_start_line = have_seen_start_line || this == line[0];
1682 if (have_seen_start_line) {
1683 if ($(this).hasClass('commentContext'))
1684 data_comment_base_line = $(this).attr('data-comment-base-line');
1686 lines_to_modify.push(this);
1690 // There is no comment context to extend.
1691 if (!data_comment_base_line)
1694 $(lines_to_modify).each(function() {
1695 $(this).addClass('commentContext');
1696 $(this).attr('data-comment-base-line', data_comment_base_line);
1700 function selectTo(focus_index) {
1701 var selected = $('.selected').removeClass('selected');
1702 var is_backward = drag_select_start_index > focus_index;
1703 var current_index = is_backward ? focus_index : drag_select_start_index;
1704 var last_index = is_backward ? drag_select_start_index : focus_index;
1705 while (current_index <= last_index) {
1706 $('#line' + current_index).addClass('selected')
1711 function selectToLineContainer(line_container) {
1712 var line = lineFromLineContainer(line_container);
1714 // Ensure that the selected lines are all contained in the same DiffSection.
1715 var selected_lines = $('.selected');
1716 var selected_diff_section = diffSectionFor(selected_lines.first());
1717 var new_diff_section = diffSectionFor(line);
1718 if (new_diff_section[0] != selected_diff_section[0]) {
1719 var lines = $('.Line', selected_diff_section);
1720 if (numberFrom(selected_lines.first().attr('id')) == drag_select_start_index)
1721 line = lines.last();
1723 line = lines.first();
1726 selectTo(numberFrom(line.attr('id')));
1729 function processSelectedLines() {
1730 drag_select_start_index = -1;
1731 addCommentForLines($('.selected'));
1734 function addCommentForLines(lines) {
1738 var already_has_comment = lines.last().hasClass('commentContext');
1740 var comment_base_line;
1741 if (already_has_comment)
1742 comment_base_line = lines.last().attr('data-comment-base-line');
1744 var last = lineFromLineDescendant(lines.last());
1745 addCommentFor($(last));
1746 comment_base_line = last.attr('id');
1749 lines.each(function() {
1750 addDataCommentBaseLine(this, comment_base_line);
1751 $(this).removeClass('selected');
1754 saveDraftComments();
1757 function hasDataCommentBaseLine(line, id) {
1758 var val = $(line).attr('data-comment-base-line');
1762 var parts = val.split(' ');
1763 for (var i = 0; i < parts.length; i++) {
1770 function addDataCommentBaseLine(line, id) {
1771 $(line).addClass('commentContext');
1772 if (hasDataCommentBaseLine(line, id))
1775 var val = $(line).attr('data-comment-base-line');
1776 var parts = val ? val.split(' ') : [];
1778 $(line).attr('data-comment-base-line', parts.join(' '));
1781 function removeDataCommentBaseLine(line, comment_base_lines) {
1782 var val = $(line).attr('data-comment-base-line');
1786 var base_lines = comment_base_lines.split(' ');
1787 var parts = val.split(' ');
1789 for (var i = 0; i < parts.length; i++) {
1790 if (base_lines.indexOf(parts[i]) == -1)
1791 new_parts.push(parts[i]);
1794 var new_comment_base_line = new_parts.join(' ');
1795 if (new_comment_base_line)
1796 $(line).attr('data-comment-base-line', new_comment_base_line);
1798 $(line).removeAttr('data-comment-base-line');
1799 $(line).removeClass('commentContext');
1803 function lineFromLineDescendant(descendant) {
1804 return descendant.hasClass('Line') ? descendant : descendant.parents('.Line');
1807 function lineFromLineContainer(lineContainer) {
1808 var line = $(lineContainer);
1809 if (!line.hasClass('Line'))
1810 line = $('.Line', line);
1814 function contextSnippetFor(line, indent) {
1816 contextLinesFor(line.attr('id'), fileDiffFor(line)).each(function() {
1818 if ($(this).hasClass('add'))
1820 else if ($(this).hasClass('remove'))
1822 snippets.push(indent + action + textContentsFor(this));
1824 return snippets.join('\n');
1827 function fileNameFor(line) {
1828 return fileDiffFor(line).find('h1').text();
1831 function indentFor(depth) {
1832 return (new Array(depth + 1)).join('>') + ' ';
1835 function snippetFor(line, indent) {
1836 var file_name = fileNameFor(line);
1837 var line_number = line.hasClass('remove') ? '-' + fromLineNumber(line[0]) : toLineNumber(line[0]);
1838 return indent + file_name + ':' + line_number + '\n' + contextSnippetFor(line, indent);
1841 function quotePreviousComments(comments) {
1842 var quoted_comments = [];
1843 var depth = comments.size();
1844 comments.each(function() {
1845 var indent = indentFor(depth--);
1846 var text = $(this).children('.content').text();
1847 quoted_comments.push(indent + '\n' + indent + text.split('\n').join('\n' + indent));
1849 return quoted_comments.join('\n');
1852 $('#comment_form .winter').live('click', hideCommentForm);
1854 function fillInReviewForm() {
1855 var comments_in_context = []
1856 forEachLine(function(line) {
1857 if (line.attr('data-has-comment') != 'true')
1859 var comment = findCommentBlockFor(line).children('textarea').val().trim();
1862 var previous_comments = previousCommentsFor(line);
1863 var snippet = snippetFor(line, indentFor(previous_comments.size() + 1));
1864 var quoted_comments = quotePreviousComments(previous_comments);
1865 var comment_with_context = [];
1866 comment_with_context.push(snippet);
1867 if (quoted_comments != '')
1868 comment_with_context.push(quoted_comments);
1869 comment_with_context.push('\n' + comment);
1870 comments_in_context.push(comment_with_context.join('\n'));
1872 var comment = $('.overallComments textarea').val().trim();
1875 comment += comments_in_context.join('\n\n');
1876 if (comments_in_context.length > 0)
1877 comment = 'View in context: ' + window.location + '\n\n' + comment;
1878 var review_form = $('#reviewform').contents();
1879 review_form.find('#comment').val(comment);
1880 review_form.find('#flags select').each(function() {
1881 var control = findControlForFlag(this);
1882 if (!control.size())
1884 $(this).attr('selectedIndex', control.attr('selectedIndex'));
1888 function showCommentForm() {
1889 $('#comment_form').removeClass('inactive');
1890 $('#reviewform').contents().find('#submitBtn').focus();
1893 function hideCommentForm() {
1894 $('#comment_form').addClass('inactive');
1896 // Make sure the top document has focus so key events don't keep going to the review form.
1897 document.body.tabIndex = -1;
1898 document.body.focus();
1901 $('#preview_comments').live('click', function() {
1906 $('#post_comments').live('click', function() {
1908 $('#reviewform').contents().find('form').submit();