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
27 * Create a new function with some of its arguements
29 * Taken from goog.partial in the Closure library.
30 * @param {Function} fn A function to partially apply.
31 * @param {...*} var_args Additional arguments that are partially
33 * @return {!Function} A partially-applied form of the function.
35 function partial(fn, var_args) {
36 var args = Array.prototype.slice.call(arguments, 1);
38 // Prepend the bound arguments to the current arguments.
39 var newArgs = Array.prototype.slice.call(arguments);
40 newArgs.unshift.apply(newArgs, args);
41 return fn.apply(this, newArgs);
45 function determineAttachmentID() {
47 return /id=(\d+)/.exec(window.location.search)[1]
53 // Attempt to activate only in the "Review Patch" context.
54 if (window.top != window)
56 if (!window.location.search.match(/action=review/))
58 var attachment_id = determineAttachmentID();
64 var original_file_contents = {};
65 var patched_file_contents = {};
66 var WEBKIT_BASE_DIR = "http://svn.webkit.org/repository/webkit/trunk/";
68 function idForLine(number) {
69 return 'line' + number;
72 function nextLineID() {
73 return idForLine(next_line_id++);
76 function forEachLine(callback) {
77 for (var i = 0; i < next_line_id; ++i) {
78 callback($('#' + idForLine(i)));
83 this.id = nextLineID();
87 $(this).hover(function() {
88 $(this).addClass('hot');
91 $(this).removeClass('hot');
95 function diffSectionFrom(line) {
96 return line.parents('.FileDiff');
99 function previousCommentsFor(line) {
100 // Scope to the diffSection as a performance improvement.
101 return $('div[data-comment-for~="' + line[0].id + '"].previousComment', diffSectionFrom(line));
104 function findCommentPositionFor(line) {
105 var previous_comments = previousCommentsFor(line);
106 var num_previous_comments = previous_comments.size();
107 if (num_previous_comments)
108 return $(previous_comments[num_previous_comments - 1])
112 function findCommentBlockFor(line) {
113 var comment_block = findCommentPositionFor(line).next();
114 if (!comment_block.hasClass('comment'))
116 return comment_block;
119 function insertCommentFor(line, block) {
120 findCommentPositionFor(line).after(block);
123 function addCommentFor(line) {
124 if (line.attr('data-has-comment')) {
125 // FIXME: This query is overly complex because we place comment blocks
126 // after Lines. Instead, comment blocks should be children of Lines.
127 findCommentPositionFor(line).next().next().filter('.frozenComment').each(unfreezeComment);
130 line.attr('data-has-comment', 'true');
131 line.addClass('commentContext');
133 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>');
134 insertCommentFor(line, comment_block);
135 comment_block.hide().slideDown('fast', function() {
136 $(this).children('textarea').focus();
140 function addCommentField() {
141 var id = $(this).attr('data-comment-for');
144 addCommentFor($('#' + id));
147 function addPreviousComment(line, author, comment_text) {
148 var comment_block = $('<div data-comment-for="' + line.attr('id') + '" class="previousComment"></div>');
149 var author_block = $('<div class="author"></div>').text(author + ':');
150 var text_block = $('<div class="content"></div>').text(comment_text);
151 comment_block.append(author_block).append(text_block).each(hoverify).click(addCommentField);
152 insertCommentFor(line, comment_block);
155 function displayPreviousComments(comments) {
156 for (var i = 0; i < comments.length; ++i) {
157 var author = comments[i].author;
158 var file_name = comments[i].file_name;
159 var line_number = comments[i].line_number;
160 var comment_text = comments[i].comment_text;
162 var file = files[file_name];
164 var query = '.Line .to';
165 if (line_number[0] == '-') {
166 // The line_number represent a removal. We need to adjust the query to
167 // look at the "from" lines.
168 query = '.Line .from';
169 // Trim off the '-' control character.
170 line_number = line_number.substr(1);
173 $(file).find(query).each(function() {
174 if ($(this).text() != line_number)
176 var line = $(this).parent();
177 addPreviousComment(line, author, comment_text);
180 if (comments.length == 0)
182 descriptor = comments.length + ' comment';
183 if (comments.length > 1)
185 $('#message .commentStatus').text('This patch has ' + descriptor + '. Scroll through them with the "n" and "p" keys.');
188 function scanForComments(author, text) {
190 var lines = text.split('\n');
191 for (var i = 0; i < lines.length; ++i) {
192 var parts = lines[i].match(/^([> ]+)([^:]+):(-?\d+)$/);
195 var quote_markers = parts[1];
196 var file_name = parts[2];
197 // FIXME: Store multiple lines for multiline comments and correctly import them here.
198 var line_number = parts[3];
199 if (!file_name in files)
201 while (i < lines.length && lines[i].length > 0 && lines[i][0] == '>')
203 var comment_lines = [];
204 while (i < lines.length && (lines[i].length == 0 || lines[i][0] != '>')) {
205 comment_lines.push(lines[i]);
208 --i; // Decrement i because the for loop will increment it again in a second.
209 var comment_text = comment_lines.join('\n').trim();
212 'file_name': file_name,
213 'line_number': line_number,
214 'comment_text': comment_text
220 function isReviewFlag(select) {
221 return $(select).attr('title') == 'Request for patch review.';
224 function isCommitQueueFlag(select) {
225 return $(select).attr('title').match(/commit-queue/);
228 function findControlForFlag(select) {
229 if (isReviewFlag(select))
230 return $('#toolbar .review select');
231 else if (isCommitQueueFlag(select))
232 return $('#toolbar .commitQueue select');
236 function addFlagsForAttachment(details) {
237 var flag_control = "<select><option></option><option>?</option><option>+</option><option>-</option></select>";
238 $('#flagContainer').append(
239 $('<span class="review"> r: ' + flag_control + '</span>')).append(
240 $('<span class="commitQueue"> cq: ' + flag_control + '</span>'));
242 details.find('#flags select').each(function() {
243 var requestee = $(this).parent().siblings('td:first-child').text().trim();
244 if (requestee.length) {
245 // Remove trailing ':'.
246 requestee = requestee.substr(0, requestee.length - 1);
247 requestee = ' (' + requestee + ')';
249 var control = findControlForFlag(this)
250 control.attr('selectedIndex', $(this).attr('selectedIndex'));
251 control.parent().prepend(requestee);
255 window.addEventListener('message', function(e) {
256 if (e.origin != 'https://webkit-commit-queue.appspot.com')
260 $('.statusBubble')[0].style.height = e.data.height;
261 $('.statusBubble')[0].style.width = e.data.width;
265 function handleStatusBubbleLoad(e) {
266 e.target.contentWindow.postMessage('containerMetrics', 'https://webkit-commit-queue.appspot.com');
269 function fetchHistory() {
270 $.get('attachment.cgi?id=' + attachment_id + '&action=edit', function(data) {
271 var bug_id = /Attachment \d+ Details for Bug (\d+)/.exec(data)[1];
272 $.get('show_bug.cgi?id=' + bug_id, function(data) {
274 $(data).find('.bz_comment').each(function() {
275 var author = $(this).find('.email').text();
276 var text = $(this).find('.bz_comment_text').text();
277 var comment_marker = '(From update of attachment ' + attachment_id + ' .details.)';
278 if (text.match(comment_marker))
279 $.merge(comments, scanForComments(author, text));
281 displayPreviousComments(comments);
284 var details = $(data);
285 addFlagsForAttachment(details);
287 var statusBubble = document.createElement('iframe');
288 statusBubble.className = 'statusBubble';
289 statusBubble.src = 'https://webkit-commit-queue.appspot.com/status-bubble/' + attachment_id;
290 statusBubble.scrolling = 'no';
291 // Can't append the HTML because we need to set the onload handler before appending the iframe to the DOM.
292 statusBubble.onload = handleStatusBubbleLoad;
293 $('#statusBubbleContainer').append(statusBubble);
295 $('#toolbar .bugLink').html('<a href="/show_bug.cgi?id=' + bug_id + '" target="_blank">Bug ' + bug_id + '</a>');
299 function crawlDiff() {
300 $('.Line').each(idify).each(hoverify);
301 $('.FileDiff').each(function() {
302 var file_name = $(this).children('h1').text();
303 files[file_name] = this;
304 addExpandLinks(file_name);
308 function addExpandLinks(file_name) {
309 if (file_name.indexOf('ChangeLog') != -1)
312 var file_diff = files[file_name];
314 // Don't show the links to expand upwards/downwards if the patch starts/ends without context
315 // lines, i.e. starts/ends with add/remove lines.
316 var first_line = file_diff.querySelector('.Line');
318 // If there is no element with a "Line" class, then this is an image diff.
322 $('.context', file_diff).detach();
324 var expand_bar_index = 0;
325 if (!$(first_line).hasClass('add') && !$(first_line).hasClass('remove'))
326 $('h1', file_diff).after(expandBarHtml(file_name, BELOW))
328 $('br').replaceWith(expandBarHtml(file_name));
330 var last_line = file_diff.querySelector('.Line:last-of-type');
331 // Some patches for new files somehow end up with an empty context line at the end
332 // with a from line number of 0. Don't show expand links in that case either.
333 if (!$(last_line).hasClass('add') && !$(last_line).hasClass('remove') && fromLineNumber(last_line) != 0)
334 $(file_diff).append(expandBarHtml(file_name, ABOVE));
337 function expandBarHtml(file_name, opt_direction) {
338 var html = '<div class="ExpandBar">' +
339 '<pre class="ExpandArea Expand' + ABOVE + '"></pre>' +
340 '<div class="ExpandLinkContainer"><span class="ExpandText">expand: </span>';
342 // FIXME: If there are <100 line to expand, don't show the expand-100 link.
343 // If there are <20 lines to expand, don't show the expand-20 link.
344 if (!opt_direction || opt_direction == ABOVE) {
345 html += expandLinkHtml(ABOVE, 100) +
346 expandLinkHtml(ABOVE, 20);
349 html += expandLinkHtml(ALL);
351 if (!opt_direction || opt_direction == BELOW) {
352 html += expandLinkHtml(BELOW, 20) +
353 expandLinkHtml(BELOW, 100);
356 html += '</div><pre class="ExpandArea Expand' + BELOW + '"></pre></div>';
360 function expandLinkHtml(direction, amount) {
361 return "<a class='ExpandLink' href='javascript:' data-direction='" + direction + "' data-amount='" + amount + "'>" +
362 (amount ? amount + " " : "") + direction + "</a>";
365 function handleExpandLinkClick(target) {
366 var expand_bar = $(target).parents('.ExpandBar');
367 var file_name = expand_bar.parents('.FileDiff').children('h1')[0].textContent;
368 var expand_function = partial(expand, expand_bar[0], file_name, target.getAttribute('data-direction'), Number(target.getAttribute('data-amount')));
369 if (file_name in original_file_contents)
372 getWebKitSourceFile(file_name, expand_function, expand_bar);
375 $(window).bind('click', function (e) {
376 var target = e.target;
378 switch(target.className) {
380 handleExpandLinkClick(target);
385 function getWebKitSourceFile(file_name, onLoad, expand_bar) {
386 function handleLoad(contents) {
387 original_file_contents[file_name] = contents.split('\n');
388 patched_file_contents[file_name] = applyDiff(original_file_contents[file_name], file_name);
393 url: WEBKIT_BASE_DIR + file_name,
394 context: document.body,
395 complete: function(xhr, data) {
397 handleLoadError(expand_bar);
399 handleLoad(xhr.responseText);
404 function replaceExpandLinkContainers(expand_bar, text) {
405 $('.ExpandLinkContainer', $(expand_bar).parents('.FileDiff')).replaceWith('<span class="ExpandText">' + text + '</span>');
408 function handleLoadError(expand_bar) {
409 // FIXME: In this case, try fetching the source file at the revision the patch was created at,
410 // in case the file has bee deleted.
411 // Might need to modify webkit-patch to include that data in the diff.
412 replaceExpandLinkContainers(expand_bar, "Can't expand. Is this a new or deleted file?");
419 function expand(expand_bar, file_name, direction, amount) {
420 if (file_name in original_file_contents && !patched_file_contents[file_name]) {
421 // FIXME: In this case, try fetching the source file at the revision the patch was created at.
422 // Might need to modify webkit-patch to include that data in the diff.
423 replaceExpandLinkContainers(expand_bar, "Can't expand. Unable to apply patch to tip of tree.");
427 var above_expansion = expand_bar.querySelector('.Expand' + ABOVE)
428 var below_expansion = expand_bar.querySelector('.Expand' + BELOW)
430 var above_last_line = above_expansion.querySelector('.ExpansionLine:last-of-type');
431 if (!above_last_line) {
432 var diff_section = expand_bar.previousElementSibling;
433 above_last_line = diff_section.querySelector('.Line:last-of-type');
436 var above_last_line_num, above_last_from_line_num;
437 if (above_last_line) {
438 above_last_line_num = toLineNumber(above_last_line);
439 above_last_from_line_num = fromLineNumber(above_last_line);
441 above_last_from_line_num = above_last_line_num = 0;
443 var below_first_line = below_expansion.querySelector('.ExpansionLine');
444 if (!below_first_line) {
445 var diff_section = expand_bar.nextElementSibling;
447 below_first_line = diff_section.querySelector('.Line');
450 var below_first_line_num, below_first_from_line_num;
451 if (below_first_line) {
452 below_first_line_num = toLineNumber(below_first_line) - 1;
453 below_first_from_line_num = fromLineNumber(below_first_line) - 1;
455 below_first_from_line_num = below_first_line_num = patched_file_contents[file_name].length - 1;
457 var start_line_num, start_from_line_num;
460 if (direction == ABOVE) {
461 start_from_line_num = above_last_from_line_num;
462 start_line_num = above_last_line_num;
463 end_line_num = Math.min(start_line_num + amount, below_first_line_num);
464 } else if (direction == BELOW) {
465 end_line_num = below_first_line_num;
466 start_line_num = Math.max(end_line_num - amount, above_last_line_num)
467 start_from_line_num = Math.max(below_first_from_line_num - amount, above_last_from_line_num)
468 } else { // direction == ALL
469 start_line_num = above_last_line_num;
470 start_from_line_num = above_last_from_line_num;
471 end_line_num = below_first_line_num;
475 // Filling in all the remaining lines. Overwrite the expand links.
476 if (start_line_num == above_last_line_num && end_line_num == below_first_line_num) {
477 expansion_area = expand_bar.querySelector('.ExpandLinkContainer');
478 expansion_area.innerHTML = '';
480 expansion_area = direction == ABOVE ? above_expansion : below_expansion;
483 insertLines(file_name, expansion_area, direction, start_line_num, end_line_num, start_from_line_num);
486 function insertLines(file_name, expansion_area, direction, start_line_num, end_line_num, start_from_line_num) {
487 var fragment = document.createDocumentFragment();
488 for (var i = 0; i < end_line_num - start_line_num; i++) {
489 var line = document.createElement('div');
490 line.className = 'ExpansionLine';
491 // FIXME: from line numbers are wrong
492 line.innerHTML = '<span class="from expansionlineNumber">' + (start_from_line_num + i + 1) +
493 '</span><span class="to expansionlineNumber">' + (start_line_num + i + 1) +
494 '</span> <span class="text"></span>';
495 line.querySelector('.text').textContent = patched_file_contents[file_name][start_line_num + i];
496 fragment.appendChild(line);
499 if (direction == BELOW)
500 expansion_area.insertBefore(fragment, expansion_area.firstChild);
502 expansion_area.appendChild(fragment);
505 function hunkStartingLine(patched_file, context, prev_line, hunk_num) {
507 var current_line = -1;
508 var last_context_line = context[context.length - 1];
509 if (patched_file[prev_line] == last_context_line)
510 current_line = prev_line + 1;
512 for (var i = prev_line - PATCH_FUZZ; i < prev_line + PATCH_FUZZ; i++) {
513 if (patched_file[i] == last_context_line)
514 current_line = i + 1;
517 if (current_line == -1) {
518 console.log('Hunk #' + hunk_num + ' FAILED.');
523 // For paranoia sake, confirm the rest of the context matches;
524 for (var i = 0; i < context.length - 1; i++) {
525 if (patched_file[current_line - context.length + i] != context[i]) {
526 console.log('Hunk #' + hunk_num + ' FAILED. Did not match preceding context.');
534 function fromLineNumber(line) {
535 return Number(line.querySelector('.from').textContent);
538 function toLineNumber(line) {
539 return Number(line.querySelector('.to').textContent);
542 function textContentsFor(line) {
543 return $('.text', line).text();
546 function lineNumberForFirstNonContextLine(patched_file, line, prev_line, context, hunk_num) {
547 if (context.length) {
548 var prev_line_num = fromLineNumber(prev_line) - 1;
549 return hunkStartingLine(patched_file, context, prev_line_num, hunk_num);
552 if (toLineNumber(line) == 1 || fromLineNumber(line) == 1)
555 console.log('Failed to apply patch. Adds or removes lines before any context lines.');
559 function applyDiff(original_file, file_name) {
560 var diff_sections = files[file_name].getElementsByClassName('DiffSection');
561 var patched_file = original_file.concat([]);
563 // Apply diffs in reverse order to avoid needing to keep track of changing line numbers.
564 for (var i = diff_sections.length - 1; i >= 0; i--) {
565 var section = diff_sections[i];
566 var lines = section.getElementsByClassName('Line');
567 var current_line = -1;
569 var hunk_num = i + 1;
571 for (var j = 0, lines_len = lines.length; j < lines_len; j++) {
573 var line_contents = textContentsFor(line);
574 if ($(line).hasClass('add')) {
575 if (current_line == -1) {
576 current_line = lineNumberForFirstNonContextLine(patched_file, line, lines[j-1], context, hunk_num);
577 if (current_line == -1)
581 patched_file.splice(current_line, 0, line_contents);
583 } else if ($(line).hasClass('remove')) {
584 if (current_line == -1) {
585 current_line = lineNumberForFirstNonContextLine(patched_file, line, lines[j-1], context, hunk_num);
586 if (current_line == -1)
590 if (patched_file[current_line] != line_contents) {
591 console.log('Hunk #' + hunk_num + ' FAILED.');
595 patched_file.splice(current_line, 1);
596 } else if (current_line == -1) {
597 context.push(line_contents);
598 } else if (line_contents != patched_file[current_line]) {
599 console.log('Hunk #' + hunk_num + ' FAILED. Context at end did not match');
610 function openOverallComments(e) {
611 $('.overallComments textarea').addClass('open');
612 $('#statusBubbleContainer').addClass('wrap');
615 function onBodyResize() {
616 updateToolbarAnchorState();
619 function updateToolbarAnchorState() {
620 var has_scrollbar = window.innerWidth > document.documentElement.offsetWidth;
621 $('#toolbar').toggleClass('anchored', has_scrollbar);
624 $(document).ready(function() {
627 $(document.body).prepend('<div id="message"><div class="help">Select line numbers to add a comment.</div><div class="commentStatus"></div></div>');
628 $(document.body).append('<div id="toolbar">' +
629 '<div class="overallComments">' +
630 '<textarea placeholder="Overall comments"></textarea>' +
633 '<span id="statusBubbleContainer"></span>' +
634 '<span class="actions">' +
635 '<span class="links"><span class="bugLink"></span></span>' +
636 '<span id="flagContainer"></span>' +
637 '<button id="preview_comments">Preview</button>' +
638 '<button id="post_comments">Publish</button> ' +
643 $('.overallComments textarea').bind('click', openOverallComments);
645 $(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>');
647 // Create a dummy iframe and monitor resizes in it's contentWindow to detect when the top document's body changes size.
648 // FIXME: Should we setTimeout throttle these?
649 var resize_iframe = $('<iframe class="pseudo_resize_event_iframe"></iframe>');
650 $(document.body).append(resize_iframe);
651 $(resize_iframe[0].contentWindow).bind('resize', onBodyResize);
653 updateToolbarAnchorState();
656 function discardComment() {
657 var line_id = $(this).parentsUntil('.comment').parent().find('textarea').attr('data-comment-for');
658 var line = $('#' + line_id)
659 findCommentBlockFor(line).slideUp('fast', function() {
661 line.removeAttr('data-has-comment');
662 trimCommentContextToBefore(line);
666 function unfreezeComment() {
667 $(this).prev().show();
671 $('.comment .discard').live('click', discardComment);
673 $('.comment .ok').live('click', function() {
674 var comment_textarea = $(this).parentsUntil('.comment').parent().find('textarea');
675 if (comment_textarea.val().trim() == '') {
676 discardComment.call(this);
679 var line_id = comment_textarea.attr('data-comment-for');
680 var line = $('#' + line_id)
681 findCommentBlockFor(line).hide().after($('<div class="frozenComment"></div>').text(comment_textarea.val()));
684 $('.frozenComment').live('click', unfreezeComment);
686 function focusOn(comment) {
687 $('.focused').removeClass('focused');
688 if (comment.length == 0)
690 $(document).scrollTop(comment.addClass('focused').position().top - window.innerHeight/2);
693 function focusNextComment() {
694 var comments = $('.previousComment');
695 if (comments.length == 0)
697 var index = comments.index($('.focused'));
698 // Notice that -1 gets mapped to 0.
699 focusOn($(comments.get(index + 1)));
702 function focusPreviousComment() {
703 var comments = $('.previousComment');
704 if (comments.length == 0)
706 var index = comments.index($('.focused'));
708 index = comments.length;
713 focusOn($(comments.get(index - 1)));
716 var kCharCodeForN = 'n'.charCodeAt(0);
717 var kCharCodeForP = 'p'.charCodeAt(0);
719 $('body').live('keypress', function() {
720 // FIXME: There's got to be a better way to avoid seeing these keypress
722 if (event.target.nodeName == 'TEXTAREA')
724 if (event.charCode == kCharCodeForN)
726 else if (event.charCode == kCharCodeForP)
727 focusPreviousComment();
730 function contextLinesFor(line_id) {
731 return $('div[data-comment-base-line~="' + line_id + '"]');
734 function numberFrom(line_id) {
735 return Number(line_id.replace('line', ''));
738 function trimCommentContextToBefore(line) {
739 var base_line_id = line.attr('data-comment-base-line');
740 var line_to_trim_to = numberFrom(line.attr('id'));
741 contextLinesFor(base_line_id).each(function() {
742 var id = $(this).attr('id');
743 if (numberFrom(id) > line_to_trim_to)
746 removeDataCommentBaseLine(this, base_line_id);
747 if (!$(this).attr('data-comment-base-line'))
748 $(this).removeClass('commentContext');
752 var in_drag_select = false;
754 function stopDragSelect() {
755 $('.selected').removeClass('selected');
756 in_drag_select = false;
759 $('.lineNumber').live('click', function() {
760 var line = $(this).parent();
761 if (line.hasClass('commentContext'))
762 trimCommentContextToBefore(line.prev());
763 }).live('mousedown', function() {
764 in_drag_select = true;
765 $(lineFromLineDescendant(this)).addClass('selected');
766 event.preventDefault();
769 $('.Line').live('mouseenter', function() {
773 var line = lineFromLineContainer(this);
774 line.addClass('selected');
775 }).live('mouseup', function() {
778 var selected = $('.selected');
779 var should_add_comment = !selected.last().next().hasClass('commentContext');
780 selected.addClass('commentContext');
783 if (should_add_comment) {
784 var last = lineFromLineDescendant(selected.last()[0]);
785 addCommentFor($(last));
788 id = selected.last().next()[0].getAttribute('data-comment-base-line');
791 selected.each(function() {
792 addDataCommentBaseLine(this, id);
796 function addDataCommentBaseLine(line, id) {
797 var val = $(line).attr('data-comment-base-line');
799 var parts = val ? val.split(' ') : [];
800 for (var i = 0; i < parts.length; i++) {
806 $(line).attr('data-comment-base-line', parts.join(' '));
809 function removeDataCommentBaseLine(line, id) {
810 var val = $(line).attr('data-comment-base-line');
814 var parts = val.split(' ');
816 for (var i = 0; i < parts.length; i++) {
818 newVal.push(parts[i]);
821 $(line).attr('data-comment-base-line', newVal.join(' '));
824 function lineFromLineDescendant(descendant) {
825 while (descendant && !$(descendant).hasClass('Line')) {
826 descendant = descendant.parentNode;
831 function lineFromLineContainer(lineContainer) {
832 var line = $(lineContainer);
833 if (!line.hasClass('Line'))
834 line = $('.Line', line);
838 $('.DiffSection').live('mouseleave', stopDragSelect).live('mouseup', stopDragSelect);
840 function contextSnippetFor(line, indent) {
842 contextLinesFor(line.attr('id')).each(function() {
844 if ($(this).hasClass('add'))
846 else if ($(this).hasClass('remove'))
848 snippets.push(indent + action + textContentsFor(this));
850 return snippets.join('\n');
853 function fileNameFor(line) {
854 return line.parentsUntil('.FileDiff').parent().find('h1').text();
857 function indentFor(depth) {
858 return (new Array(depth + 1)).join('>') + ' ';
861 function snippetFor(line, indent) {
862 var file_name = fileNameFor(line);
863 var line_number = line.hasClass('remove') ? '-' + fromLineNumber(line[0]) : toLineNumber(line[0]);
864 return indent + file_name + ':' + line_number + '\n' + contextSnippetFor(line, indent);
867 function quotePreviousComments(comments) {
868 var quoted_comments = [];
869 var depth = comments.size();
870 comments.each(function() {
871 var indent = indentFor(depth--);
872 var text = $(this).children('.content').text();
873 quoted_comments.push(indent + '\n' + indent + text.split('\n').join('\n' + indent));
875 return quoted_comments.join('\n');
878 $('#comment_form .winter').live('click', function() {
879 $('#comment_form').addClass('inactive');
882 function fillInReviewForm() {
883 var comments_in_context = []
884 forEachLine(function(line) {
885 if (line.attr('data-has-comment') != 'true')
887 var comment = findCommentBlockFor(line).children('textarea').val().trim();
890 var previous_comments = previousCommentsFor(line);
891 var snippet = snippetFor(line, indentFor(previous_comments.size() + 1));
892 var quoted_comments = quotePreviousComments(previous_comments);
893 var comment_with_context = [];
894 comment_with_context.push(snippet);
895 if (quoted_comments != '')
896 comment_with_context.push(quoted_comments);
897 comment_with_context.push('\n' + comment);
898 comments_in_context.push(comment_with_context.join('\n'));
900 var comment = $('.overallComments textarea').val().trim();
903 comment += comments_in_context.join('\n\n');
904 if (comments_in_context.length > 0)
905 comment = 'View in context: ' + window.location + '\n\n' + comment;
906 var review_form = $('#reviewform').contents();
907 review_form.find('#comment').val(comment);
908 review_form.find('#flags select').each(function() {
909 var control = findControlForFlag(this);
912 $(this).attr('selectedIndex', control.attr('selectedIndex'));
916 $('#preview_comments').live('click', function() {
918 $('#comment_form').removeClass('inactive');
921 $('#post_comments').live('click', function() {
923 $('#reviewform').contents().find('form').submit();