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) {
918 var current_line = -1;
919 var last_context_line = context[context.length - 1];
920 if (patched_file[prev_line] == last_context_line)
921 current_line = prev_line + 1;
923 console.log('Hunk #' + hunk_num + ' FAILED.');
927 // For paranoia sake, confirm the rest of the context matches;
928 for (var i = 0; i < context.length - 1; i++) {
929 if (patched_file[current_line - context.length + i] != context[i]) {
930 console.log('Hunk #' + hunk_num + ' FAILED. Did not match preceding context.');
938 function fromLineNumber(line) {
939 var node = line.querySelector('.from');
940 return node ? Number(node.textContent) : 0;
943 function toLineNumber(line) {
944 var node = line.querySelector('.to');
945 return node ? Number(node.textContent) : 0;
948 function textContentsFor(line) {
949 // Just get the first match since a side-by-side diff has two lines with text inside them for
950 // unmodified lines in the diff.
951 return $('.text', line).first().text();
954 function lineNumberForFirstNonContextLine(patched_file, line, prev_line, context, hunk_num) {
955 if (context.length) {
956 var prev_line_num = fromLineNumber(prev_line) - 1;
957 return hunkStartingLine(patched_file, context, prev_line_num, hunk_num);
960 if (toLineNumber(line) == 1 || fromLineNumber(line) == 1)
963 console.log('Failed to apply patch. Adds or removes lines before any context lines.');
967 function applyDiff(original_file, file_name) {
968 var diff_sections = files[file_name].getElementsByClassName('DiffSection');
969 var patched_file = original_file.concat([]);
971 // Apply diffs in reverse order to avoid needing to keep track of changing line numbers.
972 for (var i = diff_sections.length - 1; i >= 0; i--) {
973 var section = diff_sections[i];
974 var lines = $('.Line:not(.context)', section);
975 var current_line = -1;
977 var hunk_num = i + 1;
979 for (var j = 0, lines_len = lines.length; j < lines_len; j++) {
981 var line_contents = textContentsFor(line);
982 if ($(line).hasClass('add')) {
983 if (current_line == -1) {
984 current_line = lineNumberForFirstNonContextLine(patched_file, line, lines[j-1], context, hunk_num);
985 if (current_line == -1)
989 patched_file.splice(current_line, 0, line_contents);
991 } else if ($(line).hasClass('remove')) {
992 if (current_line == -1) {
993 current_line = lineNumberForFirstNonContextLine(patched_file, line, lines[j-1], context, hunk_num);
994 if (current_line == -1)
998 if (patched_file[current_line] != line_contents) {
999 console.log('Hunk #' + hunk_num + ' FAILED.');
1003 patched_file.splice(current_line, 1);
1004 } else if (current_line == -1) {
1005 context.push(line_contents);
1006 } else if (line_contents != patched_file[current_line]) {
1007 console.log('Hunk #' + hunk_num + ' FAILED. Context at end did not match');
1015 return patched_file;
1018 function openOverallComments(e) {
1019 $('.overallComments textarea').addClass('open');
1020 $('#statusBubbleContainer').addClass('wrap');
1023 var g_overallCommentsInputTimer;
1025 function handleOverallCommentsInput() {
1026 setAutoSaveStateIndicator('saving');
1027 // Save draft comments after we haven't received an input event in 1 second.
1028 if (g_overallCommentsInputTimer)
1029 clearTimeout(g_overallCommentsInputTimer);
1030 g_overallCommentsInputTimer = setTimeout(saveDraftComments, 1000);
1033 function onBodyResize() {
1034 updateToolbarAnchorState();
1037 function updateToolbarAnchorState() {
1038 var toolbar = $('#toolbar');
1039 // Unanchor the toolbar and then see if it's bottom is below the body's bottom.
1040 toolbar.toggleClass('anchored', false);
1041 var toolbar_bottom = toolbar.offset().top + toolbar.outerHeight();
1042 var should_anchor = toolbar_bottom >= document.body.clientHeight;
1043 toolbar.toggleClass('anchored', should_anchor);
1046 function diffLinksHtml() {
1047 return '<a href="javascript:" class="unify-link">unified</a>' +
1048 '<a href="javascript:" class="side-by-side-link">side-by-side</a>';
1051 $(document).ready(function() {
1054 $(document.body).prepend('<div id="message">' +
1055 '<div class="help">Select line numbers to add a comment. Scroll though diffs with the "j" and "k" keys.' +
1056 '<div class="DiffLinks LinkContainer">' + diffLinksHtml() + '</div>' +
1057 '<a href="javascript:" class="more">[more]</a>' +
1058 '<div class="more-help inactive">' +
1059 '<div class="winter"></div>' +
1060 '<div class="lightbox"><table>' +
1061 '<tr><td>enter</td><td>add/edit comment for focused item</td></tr>' +
1062 '<tr><td>escape</td><td>accept current comment / close preview and help popups</td></tr>' +
1063 '<tr><td>j</td><td>focus next diff</td></tr>' +
1064 '<tr><td>k</td><td>focus previous diff</td></tr>' +
1065 '<tr><td>shift + j</td><td>focus next line</td></tr>' +
1066 '<tr><td>shift + k</td><td>focus previous line</td></tr>' +
1067 '<tr><td>n</td><td>focus next comment</td></tr>' +
1068 '<tr><td>p</td><td>focus previous comment</td></tr>' +
1069 '<tr><td>r</td><td>focus review select element</td></tr>' +
1070 '<tr><td>ctrl + shift + up</td><td>extend context of the focused comment</td></tr>' +
1071 '<tr><td>ctrl + shift + down</td><td>shrink context of the focused comment</td></tr>' +
1076 $(document.body).append('<div id="toolbar">' +
1077 '<div class="overallComments">' +
1078 '<textarea placeholder="Overall comments"></textarea>' +
1081 '<span id="statusBubbleContainer"></span>' +
1082 '<span class="actions">' +
1083 '<span class="links"><span class="bugLink"></span></span>' +
1084 '<span id="flagContainer"></span>' +
1085 '<button id="preview_comments">Preview</button>' +
1086 '<button id="post_comments">Publish</button> ' +
1089 '<div class="autosave-state"></div>' +
1092 $('.overallComments textarea').bind('click', openOverallComments);
1093 $('.overallComments textarea').bind('input', handleOverallCommentsInput);
1095 $(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>');
1096 $('#reviewform').bind('load', handleReviewFormLoad);
1098 // Create a dummy iframe and monitor resizes in it's contentWindow to detect when the top document's body changes size.
1099 // FIXME: Should we setTimeout throttle these?
1100 var resize_iframe = $('<iframe class="pseudo_resize_event_iframe"></iframe>');
1101 $(document.body).append(resize_iframe);
1102 // Handle the event on a timeout to avoid crashing Firefox.
1103 $(resize_iframe[0].contentWindow).bind('resize', function() { setTimeout(onBodyResize, 0)});
1105 updateToolbarAnchorState();
1109 function handleReviewFormLoad() {
1110 var review_form_contents = $('#reviewform').contents();
1111 if (review_form_contents[0].querySelector('#form-controls #flags')) {
1112 review_form_contents.bind('keydown', function(e) {
1113 if (e.keyCode == KEY_CODE.escape)
1117 // This is the intial load of the review form iframe.
1118 var form = review_form_contents.find('form')[0];
1119 form.addEventListener('submit', eraseDraftComments);
1124 // Review form iframe have the publish button has been pressed.
1125 var email_sent_to = review_form_contents[0].querySelector('#bugzilla-body dl');
1126 // If the email_send_to DL is not in the tree that means the publish failed for some reason,
1127 // e.g., you're not logged in. Show the comment form to allow you to login.
1128 if (!email_sent_to) {
1133 eraseDraftComments();
1134 // FIXME: Once WebKit supports seamless iframes, we can just make the review-form
1135 // iframe fill the page instead of redirecting back to the bug.
1136 window.location.replace($('#toolbar .bugLink a').attr('href'));
1139 function eraseDraftComments() {
1140 g_draftCommentSaver.erase();
1143 function loadDiffState() {
1144 var diffstate = localStorage.getItem('code-review-diffstate');
1145 if (diffstate != 'sidebyside' && diffstate != 'unified')
1148 convertAllFileDiffs(diffstate, $('.FileDiff'));
1151 function isDiffSideBySide(file_diff) {
1152 return diffState(file_diff) == 'sidebyside';
1155 function diffState(file_diff) {
1156 var diff_state = $(file_diff).attr('data-diffstate');
1157 return diff_state || 'unified';
1160 function unifyLine(line, from, to, contents, classNames, attributes, id) {
1161 var new_line = unifiedLine(from, to, contents, false, classNames, attributes);
1162 var old_line = $(line);
1163 if (!old_line.hasClass('LineContainer'))
1164 old_line = old_line.parents('.LineContainer');
1166 var comments = commentsToTransferFor($(document.getElementById(id)));
1167 old_line.after(comments);
1168 old_line.replaceWith(new_line);
1171 function updateDiffLinkVisibility(file_diff) {
1172 if (diffState(file_diff) == 'unified') {
1173 $('.side-by-side-link', file_diff).show();
1174 $('.unify-link', file_diff).hide();
1176 $('.side-by-side-link', file_diff).hide();
1177 $('.unify-link', file_diff).show();
1181 function convertAllFileDiffs(diff_type, file_diffs) {
1182 file_diffs.each(function() {
1183 convertFileDiff(diff_type, this);
1187 function convertFileDiff(diff_type, file_diff) {
1188 if (diffState(file_diff) == diff_type)
1191 $(file_diff).removeClass('sidebyside unified');
1192 $(file_diff).addClass(diff_type);
1194 $(file_diff).attr('data-diffstate', diff_type);
1195 updateDiffLinkVisibility(file_diff);
1197 $('.context', file_diff).each(function() {
1198 convertLine(diff_type, this);
1201 $('.shared .Line', file_diff).each(function() {
1202 convertLine(diff_type, this);
1205 $('.ExpansionLine', file_diff).each(function() {
1206 convertExpansionLine(diff_type, this);
1210 function convertLine(diff_type, line) {
1211 var convert_function = diff_type == 'sidebyside' ? sideBySideifyLine : unifyLine;
1212 var from = fromLineNumber(line);
1213 var to = toLineNumber(line);
1214 var contents = $('.text', line).first();
1215 var classNames = classNamesForMovingLine(line);
1216 var attributes = attributesForMovingLine(line);
1218 convert_function(line, from, to, contents, classNames, attributes, id)
1221 function classNamesForMovingLine(line) {
1222 var classParts = line.className.split(' ');
1223 var classBuffer = [];
1224 for (var i = 0; i < classParts.length; i++) {
1225 var part = classParts[i];
1226 if (part != 'LineContainer' && part != 'Line')
1227 classBuffer.push(part);
1229 return classBuffer.join(' ');
1232 function attributesForMovingLine(line) {
1233 var attributesBuffer = ['id=' + line.id];
1234 // Make sure to keep all data- attributes.
1235 $(line.attributes).each(function() {
1236 if (this.name.indexOf('data-') == 0)
1237 attributesBuffer.push(this.name + '=' + this.value);
1239 return attributesBuffer.join(' ');
1242 function sideBySideifyLine(line, from, to, contents, classNames, attributes, id) {
1243 var from_class = '';
1245 var from_attributes = '';
1246 var to_attributes = '';
1247 // Clone the contents so we have two copies we can put back in the DOM.
1248 var from_contents = contents.clone(true);
1249 var to_contents = contents;
1251 var container_class = 'LineContainer';
1252 var container_attributes = '';
1254 if (from && !to) { // This is a remove line.
1255 from_class = classNames;
1256 from_attributes = attributes;
1258 } else if (to && !from) { // This is an add line.
1259 to_class = classNames;
1260 to_attributes = attributes;
1263 container_attributes = attributes;
1264 container_class += ' Line ' + classNames;
1267 var new_line = $('<div ' + container_attributes + ' class="' + container_class + '"></div>');
1268 new_line.append(lineSide('from', from_contents, false, from, from_attributes, from_class));
1269 new_line.append(lineSide('to', to_contents, false, to, to_attributes, to_class));
1271 $(line).replaceWith(new_line);
1273 var line = $(document.getElementById(id));
1274 line.after(commentsToTransferFor(line));
1277 function convertExpansionLine(diff_type, line) {
1278 var convert_function = diff_type == 'sidebyside' ? sideBySideExpansionLine : unifiedExpansionLine;
1279 var contents = $('.text', line).first();
1280 var from = fromLineNumber(line);
1281 var to = toLineNumber(line);
1282 var new_line = convert_function(from, to, contents);
1283 $(line).replaceWith(new_line);
1286 function commentsToTransferFor(line) {
1287 var fragment = document.createDocumentFragment();
1289 previousCommentsFor(line).each(function() {
1290 fragment.appendChild(this);
1293 var active_comments = activeCommentFor(line);
1294 var num_active_comments = active_comments.size();
1295 if (num_active_comments > 0) {
1296 if (num_active_comments > 1)
1297 console.log('ERROR: There is more than one active comment for ' + line.attr('id') + '.');
1299 var parent = active_comments[0].parentNode;
1300 var frozenComment = parent.nextSibling;
1301 fragment.appendChild(parent);
1302 fragment.appendChild(frozenComment);
1308 function discardComment(comment_block) {
1309 var line_id = comment_block.find('textarea').attr('data-comment-for');
1310 var line = $('#' + line_id)
1311 findCommentBlockFor(line).slideUp('fast', function() {
1313 line.removeAttr('data-has-comment');
1314 trimCommentContextToBefore(line, line.attr('data-comment-base-line'));
1315 saveDraftComments();
1319 function handleUnfreezeComment() {
1320 unfreezeComment(this);
1323 function unfreezeComment(comment) {
1324 var unfrozen_comment = $(comment).prev();
1325 unfrozen_comment.show();
1326 $(comment).remove();
1327 unfrozen_comment.find('textarea')[0].focus();
1330 function showFileDiffLinks() {
1331 $('.LinkContainer', this).each(function() { this.style.opacity = 1; });
1334 function hideFileDiffLinks() {
1335 $('.LinkContainer', this).each(function() { this.style.opacity = 0; });
1338 function handleDiscardComment() {
1339 discardComment($(this).parents('.comment'));
1342 function handleAcceptComment() {
1343 acceptComment($(this).parents('.comment'));
1346 function acceptComment(comment) {
1347 var frozen_comment = freezeComment(comment);
1348 focusOn(frozen_comment);
1349 saveDraftComments();
1352 $('.FileDiff').live('mouseenter', showFileDiffLinks);
1353 $('.FileDiff').live('mouseleave', hideFileDiffLinks);
1354 $('.side-by-side-link').live('click', handleSideBySideLinkClick);
1355 $('.unify-link').live('click', handleUnifyLinkClick);
1356 $('.ExpandLink').live('click', handleExpandLinkClick);
1357 $('.frozenComment').live('click', handleUnfreezeComment);
1358 $('.comment .discard').live('click', handleDiscardComment);
1359 $('.comment .ok').live('click', handleAcceptComment);
1360 $('.more').live('click', showMoreHelp);
1361 $('.more-help .winter').live('click', hideMoreHelp);
1363 function freezeComment(comment_block) {
1364 var comment_textarea = comment_block.find('textarea');
1365 if (comment_textarea.val().trim() == '') {
1366 discardComment(comment_block);
1369 var line_id = comment_textarea.attr('data-comment-for');
1370 var line = $('#' + line_id)
1371 var frozen_comment = $('<div class="frozenComment"></div>').text(comment_textarea.val());
1372 findCommentBlockFor(line).hide().after(frozen_comment);
1373 return frozen_comment;
1376 function focusOn(node) {
1377 if (node.length == 0)
1380 // Give a tabindex so the element can receive actual browser focus.
1381 // -1 makes the element focusable without actually putting in in the tab order.
1382 node.attr('tabindex', -1);
1384 // Remove the tabindex on blur to avoid having the node be mouse-focusable.
1385 node.bind('blur', function() { node.removeAttr('tabindex'); });
1386 $(document).scrollTop(node.position().top - window.innerHeight / 2);
1389 function focusNext(filter, direction) {
1390 var focusable_nodes = $('a,.Line,.frozenComment,.previousComment,.DiffBlock,.overallComments').filter(function() {
1391 return !$(this).hasClass('DiffBlock') || $('.add,.remove', this).size();
1394 var is_backward = direction == DIRECTION.BACKWARD;
1395 var index = focusable_nodes.index($(document.activeElement));
1396 if (index == -1 && is_backward)
1397 index = focusable_nodes.length;
1399 var offset = is_backward ? -1 : 1;
1400 var end = is_backward ? -1 : focusable_nodes.size();
1401 for (var i = index + offset; i != end; i = i + offset) {
1402 var node = $(focusable_nodes[i]);
1411 var DIRECTION = {FORWARD: 1, BACKWARD: 2};
1413 function isComment(node) {
1414 return node.hasClass('frozenComment') || node.hasClass('previousComment') || node.hasClass('overallComments');
1417 function isDiffBlock(node) {
1418 return node.hasClass('DiffBlock');
1421 function isLine(node) {
1422 return node.hasClass('Line');
1425 function commentTextareaForKeyTarget(key_target) {
1426 if (key_target.nodeName == 'TEXTAREA')
1427 return $(key_target);
1429 var comment_textarea = $(document.activeElement).prev().find('textarea');
1430 if (!comment_textarea.size())
1432 return comment_textarea;
1435 function extendCommentContextUp(key_target) {
1436 var comment_textarea = commentTextareaForKeyTarget(key_target);
1437 if (!comment_textarea)
1440 var comment_base_line = comment_textarea.attr('data-comment-for');
1441 var diff_section = diffSectionFor(comment_textarea);
1442 var lines = $('.Line', diff_section);
1443 for (var i = 0; i < lines.length - 1; i++) {
1444 if (hasDataCommentBaseLine(lines[i + 1], comment_base_line)) {
1445 addDataCommentBaseLine(lines[i], comment_base_line);
1451 function shrinkCommentContextDown(key_target) {
1452 var comment_textarea = commentTextareaForKeyTarget(key_target);
1453 if (!comment_textarea)
1456 var comment_base_line = comment_textarea.attr('data-comment-for');
1457 var diff_section = diffSectionFor(comment_textarea);
1458 var lines = contextLinesFor(comment_base_line, diff_section);
1459 if (lines.size() > 1)
1460 removeDataCommentBaseLine(lines[0], comment_base_line);
1463 function handleModifyContextKey(e) {
1464 var handled = false;
1466 if (e.shiftKey && e.ctrlKey) {
1467 switch (e.keyCode) {
1469 extendCommentContextUp(e.target);
1474 shrinkCommentContextDown(e.target);
1486 $('textarea').live('keydown', function(e) {
1487 if (handleModifyContextKey(e))
1490 if (e.keyCode == KEY_CODE.escape)
1491 handleEscapeKeyInTextarea(this);
1494 $('body').live('keydown', function(e) {
1495 // FIXME: There's got to be a better way to avoid seeing these keypress
1497 if (e.target.nodeName == 'TEXTAREA')
1500 // Don't want to override browser shortcuts like ctrl+r.
1501 if (e.metaKey || e.ctrlKey)
1504 if (handleModifyContextKey(e))
1507 var handled = false;
1508 switch (e.keyCode) {
1510 $('.review select').focus();
1515 handled = focusNext(isComment, DIRECTION.FORWARD);
1519 handled = focusNext(isComment, DIRECTION.BACKWARD);
1524 handled = focusNext(isLine, DIRECTION.FORWARD);
1526 handled = focusNext(isDiffBlock, DIRECTION.FORWARD);
1531 handled = focusNext(isLine, DIRECTION.BACKWARD);
1533 handled = focusNext(isDiffBlock, DIRECTION.BACKWARD);
1536 case KEY_CODE.enter:
1537 handled = handleEnterKey();
1540 case KEY_CODE.escape:
1550 function handleEscapeKeyInTextarea(textarea) {
1551 var comment = $(textarea).parents('.comment');
1553 acceptComment(comment);
1556 document.body.focus();
1559 function handleEnterKey() {
1560 if (document.activeElement.nodeName == 'BODY')
1563 var focused = $(document.activeElement);
1565 if (focused.hasClass('frozenComment')) {
1566 unfreezeComment(focused);
1570 if (focused.hasClass('overallComments')) {
1571 openOverallComments();
1572 focused.find('textarea')[0].focus();
1576 if (focused.hasClass('previousComment')) {
1577 addCommentField(focused);
1581 var lines = focused.hasClass('Line') ? focused : $('.Line', focused);
1582 var last = lines.last();
1583 if (last.attr('data-has-comment')) {
1584 unfreezeCommentFor(last);
1588 addCommentForLines(lines);
1592 function contextLinesFor(comment_base_lines, file_diff) {
1593 var base_lines = comment_base_lines.split(' ');
1594 return $('div[data-comment-base-line]', file_diff).filter(function() {
1595 return $(this).attr('data-comment-base-line').split(' ').some(function(item) {
1596 return base_lines.indexOf(item) != -1;
1601 function numberFrom(line_id) {
1602 return Number(line_id.replace('line', ''));
1605 function trimCommentContextToBefore(line, comment_base_line) {
1606 var line_to_trim_to = numberFrom(line.attr('id'));
1607 contextLinesFor(comment_base_line, fileDiffFor(line)).each(function() {
1608 var id = $(this).attr('id');
1609 if (numberFrom(id) > line_to_trim_to)
1612 removeDataCommentBaseLine(this, comment_base_line);
1616 var drag_select_start_index = -1;
1618 function lineOffsetFrom(line, offset) {
1619 var file_diff = line.parents('.FileDiff');
1620 var all_lines = $('.Line', file_diff);
1621 var index = all_lines.index(line);
1622 return $(all_lines[index + offset]);
1625 function previousLineFor(line) {
1626 return lineOffsetFrom(line, -1);
1629 function nextLineFor(line) {
1630 return lineOffsetFrom(line, 1);
1633 $(document.body).bind('mouseup', processSelectedLines);
1635 $('.lineNumber').live('click', function(e) {
1636 var line = lineFromLineDescendant($(this));
1637 if (line.hasClass('commentContext'))
1638 trimCommentContextToBefore(previousLineFor(line), line.attr('data-comment-base-line'));
1639 else if (e.shiftKey)
1640 extendCommentContextTo(line);
1641 }).live('mousedown', function(e) {
1642 // preventDefault to avoid selecting text when dragging to select comment context lines.
1643 // FIXME: should we use user-modify CSS instead?
1648 var line = lineFromLineDescendant($(this));
1649 drag_select_start_index = numberFrom(line.attr('id'));
1650 line.addClass('selected');
1653 $('.LineContainer').live('mouseenter', function(e) {
1654 if (drag_select_start_index == -1 || e.shiftKey)
1656 selectToLineContainer(this);
1657 }).live('mouseup', function(e) {
1658 if (drag_select_start_index == -1 || e.shiftKey)
1661 selectToLineContainer(this);
1662 processSelectedLines();
1665 function extendCommentContextTo(line) {
1666 var diff_section = diffSectionFor(line);
1667 var lines = $('.Line', diff_section);
1668 var lines_to_modify = [];
1669 var have_seen_start_line = false;
1670 var data_comment_base_line = null;
1671 lines.each(function() {
1672 if (data_comment_base_line)
1675 have_seen_start_line = have_seen_start_line || this == line[0];
1677 if (have_seen_start_line) {
1678 if ($(this).hasClass('commentContext'))
1679 data_comment_base_line = $(this).attr('data-comment-base-line');
1681 lines_to_modify.push(this);
1685 // There is no comment context to extend.
1686 if (!data_comment_base_line)
1689 $(lines_to_modify).each(function() {
1690 $(this).addClass('commentContext');
1691 $(this).attr('data-comment-base-line', data_comment_base_line);
1695 function selectTo(focus_index) {
1696 var selected = $('.selected').removeClass('selected');
1697 var is_backward = drag_select_start_index > focus_index;
1698 var current_index = is_backward ? focus_index : drag_select_start_index;
1699 var last_index = is_backward ? drag_select_start_index : focus_index;
1700 while (current_index <= last_index) {
1701 $('#line' + current_index).addClass('selected')
1706 function selectToLineContainer(line_container) {
1707 var line = lineFromLineContainer(line_container);
1709 // Ensure that the selected lines are all contained in the same DiffSection.
1710 var selected_lines = $('.selected');
1711 var selected_diff_section = diffSectionFor(selected_lines.first());
1712 var new_diff_section = diffSectionFor(line);
1713 if (new_diff_section[0] != selected_diff_section[0]) {
1714 var lines = $('.Line', selected_diff_section);
1715 if (numberFrom(selected_lines.first().attr('id')) == drag_select_start_index)
1716 line = lines.last();
1718 line = lines.first();
1721 selectTo(numberFrom(line.attr('id')));
1724 function processSelectedLines() {
1725 drag_select_start_index = -1;
1726 addCommentForLines($('.selected'));
1729 function addCommentForLines(lines) {
1733 var already_has_comment = lines.last().hasClass('commentContext');
1735 var comment_base_line;
1736 if (already_has_comment)
1737 comment_base_line = lines.last().attr('data-comment-base-line');
1739 var last = lineFromLineDescendant(lines.last());
1740 addCommentFor($(last));
1741 comment_base_line = last.attr('id');
1744 lines.each(function() {
1745 addDataCommentBaseLine(this, comment_base_line);
1746 $(this).removeClass('selected');
1749 saveDraftComments();
1752 function hasDataCommentBaseLine(line, id) {
1753 var val = $(line).attr('data-comment-base-line');
1757 var parts = val.split(' ');
1758 for (var i = 0; i < parts.length; i++) {
1765 function addDataCommentBaseLine(line, id) {
1766 $(line).addClass('commentContext');
1767 if (hasDataCommentBaseLine(line, id))
1770 var val = $(line).attr('data-comment-base-line');
1771 var parts = val ? val.split(' ') : [];
1773 $(line).attr('data-comment-base-line', parts.join(' '));
1776 function removeDataCommentBaseLine(line, comment_base_lines) {
1777 var val = $(line).attr('data-comment-base-line');
1781 var base_lines = comment_base_lines.split(' ');
1782 var parts = val.split(' ');
1784 for (var i = 0; i < parts.length; i++) {
1785 if (base_lines.indexOf(parts[i]) == -1)
1786 new_parts.push(parts[i]);
1789 var new_comment_base_line = new_parts.join(' ');
1790 if (new_comment_base_line)
1791 $(line).attr('data-comment-base-line', new_comment_base_line);
1793 $(line).removeAttr('data-comment-base-line');
1794 $(line).removeClass('commentContext');
1798 function lineFromLineDescendant(descendant) {
1799 return descendant.hasClass('Line') ? descendant : descendant.parents('.Line');
1802 function lineFromLineContainer(lineContainer) {
1803 var line = $(lineContainer);
1804 if (!line.hasClass('Line'))
1805 line = $('.Line', line);
1809 function contextSnippetFor(line, indent) {
1811 contextLinesFor(line.attr('id'), fileDiffFor(line)).each(function() {
1813 if ($(this).hasClass('add'))
1815 else if ($(this).hasClass('remove'))
1817 snippets.push(indent + action + textContentsFor(this));
1819 return snippets.join('\n');
1822 function fileNameFor(line) {
1823 return fileDiffFor(line).find('h1').text();
1826 function indentFor(depth) {
1827 return (new Array(depth + 1)).join('>') + ' ';
1830 function snippetFor(line, indent) {
1831 var file_name = fileNameFor(line);
1832 var line_number = line.hasClass('remove') ? '-' + fromLineNumber(line[0]) : toLineNumber(line[0]);
1833 return indent + file_name + ':' + line_number + '\n' + contextSnippetFor(line, indent);
1836 function quotePreviousComments(comments) {
1837 var quoted_comments = [];
1838 var depth = comments.size();
1839 comments.each(function() {
1840 var indent = indentFor(depth--);
1841 var text = $(this).children('.content').text();
1842 quoted_comments.push(indent + '\n' + indent + text.split('\n').join('\n' + indent));
1844 return quoted_comments.join('\n');
1847 $('#comment_form .winter').live('click', hideCommentForm);
1849 function fillInReviewForm() {
1850 var comments_in_context = []
1851 forEachLine(function(line) {
1852 if (line.attr('data-has-comment') != 'true')
1854 var comment = findCommentBlockFor(line).children('textarea').val().trim();
1857 var previous_comments = previousCommentsFor(line);
1858 var snippet = snippetFor(line, indentFor(previous_comments.size() + 1));
1859 var quoted_comments = quotePreviousComments(previous_comments);
1860 var comment_with_context = [];
1861 comment_with_context.push(snippet);
1862 if (quoted_comments != '')
1863 comment_with_context.push(quoted_comments);
1864 comment_with_context.push('\n' + comment);
1865 comments_in_context.push(comment_with_context.join('\n'));
1867 var comment = $('.overallComments textarea').val().trim();
1870 comment += comments_in_context.join('\n\n');
1871 if (comments_in_context.length > 0)
1872 comment = 'View in context: ' + window.location + '\n\n' + comment;
1873 var review_form = $('#reviewform').contents();
1874 review_form.find('#comment').val(comment);
1875 review_form.find('#flags select').each(function() {
1876 var control = findControlForFlag(this);
1877 if (!control.size())
1879 $(this).attr('selectedIndex', control.attr('selectedIndex'));
1883 function showCommentForm() {
1884 $('#comment_form').removeClass('inactive');
1885 $('#reviewform').contents().find('#submitBtn').focus();
1888 function hideCommentForm() {
1889 $('#comment_form').addClass('inactive');
1891 // Make sure the top document has focus so key events don't keep going to the review form.
1892 document.body.tabIndex = -1;
1893 document.body.focus();
1896 $('#preview_comments').live('click', function() {
1901 $('#post_comments').live('click', function() {
1903 $('#reviewform').contents().find('form').submit();