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)
57 if (!window.location.search.match(/action=review/)
58 && !window.location.toString().match(/bugs\.webkit\.org\/PrettyPatch/))
61 var attachment_id = determineAttachmentID();
63 console.log('No attachment ID');
67 var original_file_contents = {};
68 var patched_file_contents = {};
69 var WEBKIT_BASE_DIR = "http://svn.webkit.org/repository/webkit/trunk/";
70 var SIDE_BY_SIDE_DIFFS_KEY = 'sidebysidediffs';
72 function idForLine(number) {
73 return 'line' + number;
76 function nextLineID() {
77 return idForLine(next_line_id++);
80 function forEachLine(callback) {
81 for (var i = 0; i < next_line_id; ++i) {
82 callback($('#' + idForLine(i)));
87 this.id = nextLineID();
91 $(this).hover(function() {
92 $(this).addClass('hot');
95 $(this).removeClass('hot');
99 function fileDiffFor(line) {
100 return line.parents('.FileDiff');
103 function activeCommentFor(line) {
104 // Scope to the diffSection as a performance improvement.
105 return $('textarea[data-comment-for~="' + line[0].id + '"]', fileDiffFor(line));
108 function previousCommentsFor(line) {
109 // Scope to the diffSection as a performance improvement.
110 return $('div[data-comment-for~="' + line[0].id + '"].previousComment', fileDiffFor(line));
113 function findCommentPositionFor(line) {
114 var previous_comments = previousCommentsFor(line);
115 var num_previous_comments = previous_comments.size();
116 if (num_previous_comments)
117 return $(previous_comments[num_previous_comments - 1])
121 function findCommentBlockFor(line) {
122 var comment_block = findCommentPositionFor(line).next();
123 if (!comment_block.hasClass('comment'))
125 return comment_block;
128 function insertCommentFor(line, block) {
129 findCommentPositionFor(line).after(block);
132 function addCommentFor(line) {
133 if (line.attr('data-has-comment')) {
134 // FIXME: This query is overly complex because we place comment blocks
135 // after Lines. Instead, comment blocks should be children of Lines.
136 findCommentPositionFor(line).next().next().filter('.frozenComment').each(unfreezeComment);
139 line.attr('data-has-comment', 'true');
140 line.addClass('commentContext');
142 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>');
143 insertCommentFor(line, comment_block);
144 comment_block.hide().slideDown('fast', function() {
145 $(this).children('textarea').focus();
149 function addCommentField() {
150 var id = $(this).attr('data-comment-for');
153 addCommentFor($('#' + id));
156 function addPreviousComment(line, author, comment_text) {
157 var line_id = line.attr('id');
158 var comment_block = $('<div data-comment-for="' + line_id + '" class="previousComment"></div>');
159 var author_block = $('<div class="author"></div>').text(author + ':');
160 var text_block = $('<div class="content"></div>').text(comment_text);
161 comment_block.append(author_block).append(text_block).each(hoverify).click(addCommentField);
162 addDataCommentBaseLine(line, line_id);
163 insertCommentFor(line, comment_block);
166 function displayPreviousComments(comments) {
167 for (var i = 0; i < comments.length; ++i) {
168 var author = comments[i].author;
169 var file_name = comments[i].file_name;
170 var line_number = comments[i].line_number;
171 var comment_text = comments[i].comment_text;
173 var file = files[file_name];
175 var query = '.Line .to';
176 if (line_number[0] == '-') {
177 // The line_number represent a removal. We need to adjust the query to
178 // look at the "from" lines.
179 query = '.Line .from';
180 // Trim off the '-' control character.
181 line_number = line_number.substr(1);
184 $(file).find(query).each(function() {
185 if ($(this).text() != line_number)
187 var line = $(this).parent();
188 addPreviousComment(line, author, comment_text);
192 var help_text = 'Scroll though diffs with the "j" and "k" keys.';
193 if (comments.length == 0) {
194 $('#message .commentStatus').text(help_text);
198 descriptor = comments.length + ' comment';
199 if (comments.length > 1)
201 $('#message .commentStatus').text('This patch has ' + descriptor + '. Scroll through them with the "n" and "p" keys. ' + help_text);
204 function scanForComments(author, text) {
206 var lines = text.split('\n');
207 for (var i = 0; i < lines.length; ++i) {
208 var parts = lines[i].match(/^([> ]+)([^:]+):(-?\d+)$/);
211 var quote_markers = parts[1];
212 var file_name = parts[2];
213 // FIXME: Store multiple lines for multiline comments and correctly import them here.
214 var line_number = parts[3];
215 if (!file_name in files)
217 while (i < lines.length && lines[i].length > 0 && lines[i][0] == '>')
219 var comment_lines = [];
220 while (i < lines.length && (lines[i].length == 0 || lines[i][0] != '>')) {
221 comment_lines.push(lines[i]);
224 --i; // Decrement i because the for loop will increment it again in a second.
225 var comment_text = comment_lines.join('\n').trim();
228 'file_name': file_name,
229 'line_number': line_number,
230 'comment_text': comment_text
236 function isReviewFlag(select) {
237 return $(select).attr('title') == 'Request for patch review.';
240 function isCommitQueueFlag(select) {
241 return $(select).attr('title').match(/commit-queue/);
244 function findControlForFlag(select) {
245 if (isReviewFlag(select))
246 return $('#toolbar .review select');
247 else if (isCommitQueueFlag(select))
248 return $('#toolbar .commitQueue select');
252 function addFlagsForAttachment(details) {
253 var flag_control = "<select><option></option><option>?</option><option>+</option><option>-</option></select>";
254 $('#flagContainer').append(
255 $('<span class="review"> r: ' + flag_control + '</span>')).append(
256 $('<span class="commitQueue"> cq: ' + flag_control + '</span>'));
258 details.find('#flags select').each(function() {
259 var requestee = $(this).parent().siblings('td:first-child').text().trim();
260 if (requestee.length) {
261 // Remove trailing ':'.
262 requestee = requestee.substr(0, requestee.length - 1);
263 requestee = ' (' + requestee + ')';
265 var control = findControlForFlag(this)
266 control.attr('selectedIndex', $(this).attr('selectedIndex'));
267 control.parent().prepend(requestee);
271 window.addEventListener('message', function(e) {
272 if (e.origin != 'https://webkit-commit-queue.appspot.com')
276 $('.statusBubble')[0].style.height = e.data.height;
277 $('.statusBubble')[0].style.width = e.data.width;
281 function handleStatusBubbleLoad(e) {
282 e.target.contentWindow.postMessage('containerMetrics', 'https://webkit-commit-queue.appspot.com');
285 function fetchHistory() {
286 $.get('attachment.cgi?id=' + attachment_id + '&action=edit', function(data) {
287 var bug_id = /Attachment \d+ Details for Bug (\d+)/.exec(data)[1];
288 $.get('show_bug.cgi?id=' + bug_id, function(data) {
290 $(data).find('.bz_comment').each(function() {
291 var author = $(this).find('.email').text();
292 var text = $(this).find('.bz_comment_text').text();
293 var comment_marker = '(From update of attachment ' + attachment_id + ' .details.)';
294 if (text.match(comment_marker))
295 $.merge(comments, scanForComments(author, text));
297 displayPreviousComments(comments);
300 var details = $(data);
301 addFlagsForAttachment(details);
303 var statusBubble = document.createElement('iframe');
304 statusBubble.className = 'statusBubble';
305 statusBubble.src = 'https://webkit-commit-queue.appspot.com/status-bubble/' + attachment_id;
306 statusBubble.scrolling = 'no';
307 // Can't append the HTML because we need to set the onload handler before appending the iframe to the DOM.
308 statusBubble.onload = handleStatusBubbleLoad;
309 $('#statusBubbleContainer').append(statusBubble);
311 $('#toolbar .bugLink').html('<a href="/show_bug.cgi?id=' + bug_id + '" target="_blank">Bug ' + bug_id + '</a>');
315 function crawlDiff() {
316 $('.Line').each(idify).each(hoverify);
317 $('.FileDiff').each(function() {
318 var file_name = $(this).children('h1').text();
319 files[file_name] = this;
320 addExpandLinks(file_name);
321 $('h1', this).after('<div class="FileDiffLinkContainer">' + diffLinksHtml() + '</div>');
322 updateDiffLinkVisibility(this);
326 function addExpandLinks(file_name) {
327 if (file_name.indexOf('ChangeLog') != -1)
330 var file_diff = files[file_name];
332 // Don't show the links to expand upwards/downwards if the patch starts/ends without context
333 // lines, i.e. starts/ends with add/remove lines.
334 var first_line = file_diff.querySelector('.LineContainer');
336 // If there is no element with a "Line" class, then this is an image diff.
340 $('.context', file_diff).detach();
342 var expand_bar_index = 0;
343 if (!$(first_line).hasClass('add') && !$(first_line).hasClass('remove'))
344 $('h1', file_diff).after(expandBarHtml(file_name, BELOW))
346 $('br').replaceWith(expandBarHtml(file_name));
348 var last_line = file_diff.querySelector('.LineContainer:last-of-type');
349 // Some patches for new files somehow end up with an empty context line at the end
350 // with a from line number of 0. Don't show expand links in that case either.
351 if (!$(last_line).hasClass('add') && !$(last_line).hasClass('remove') && fromLineNumber(last_line) != 0)
352 $(file_diff).append(expandBarHtml(file_name, ABOVE));
355 function expandBarHtml(file_name, opt_direction) {
356 var html = '<div class="ExpandBar">' +
357 '<div class="ExpandArea Expand' + ABOVE + '"></div>' +
358 '<div class="ExpandLinkContainer LinkContainer"><span class="ExpandText">expand: </span>';
360 // FIXME: If there are <100 line to expand, don't show the expand-100 link.
361 // If there are <20 lines to expand, don't show the expand-20 link.
362 if (!opt_direction || opt_direction == ABOVE) {
363 html += expandLinkHtml(ABOVE, 100) +
364 expandLinkHtml(ABOVE, 20);
367 html += expandLinkHtml(ALL);
369 if (!opt_direction || opt_direction == BELOW) {
370 html += expandLinkHtml(BELOW, 20) +
371 expandLinkHtml(BELOW, 100);
374 html += '</div><div class="ExpandArea Expand' + BELOW + '"></div></div>';
378 function expandLinkHtml(direction, amount) {
379 return "<a class='ExpandLink' href='javascript:' data-direction='" + direction + "' data-amount='" + amount + "'>" +
380 (amount ? amount + " " : "") + direction + "</a>";
383 function handleExpandLinkClick() {
384 var expand_bar = $(this).parents('.ExpandBar');
385 var file_name = expand_bar.parents('.FileDiff').children('h1')[0].textContent;
386 var expand_function = partial(expand, expand_bar[0], file_name, this.getAttribute('data-direction'), Number(this.getAttribute('data-amount')));
387 if (file_name in original_file_contents)
390 getWebKitSourceFile(file_name, expand_function, expand_bar);
393 function handleSideBySideLinkClick() {
394 convertDiff('sidebyside', this);
397 function handleUnifyLinkClick() {
398 convertDiff('unified', this);
401 function convertDiff(difftype, convert_link) {
402 var file_diffs = $(convert_link).parents('.FileDiff');
403 if (!file_diffs.size()) {
404 localStorage.setItem('code-review-diffstate', difftype);
405 file_diffs = $('.FileDiff');
408 convertAllFileDiffs(difftype, file_diffs);
411 function patchRevision() {
412 var revision = $('.revision');
413 return revision[0] ? revision.first().text() : null;
416 function getWebKitSourceFile(file_name, onLoad, expand_bar) {
417 function handleLoad(contents) {
418 original_file_contents[file_name] = contents.split('\n');
419 patched_file_contents[file_name] = applyDiff(original_file_contents[file_name], file_name);
423 var revision = patchRevision();
424 var queryParameters = revision ? '?p=' + revision : '';
427 url: WEBKIT_BASE_DIR + file_name + queryParameters,
428 context: document.body,
429 complete: function(xhr, data) {
431 handleLoadError(expand_bar);
433 handleLoad(xhr.responseText);
438 function replaceExpandLinkContainers(expand_bar, text) {
439 $('.ExpandLinkContainer', $(expand_bar).parents('.FileDiff')).replaceWith('<span class="ExpandText">' + text + '</span>');
442 function handleLoadError(expand_bar) {
443 replaceExpandLinkContainers(expand_bar, "Can't expand. Is this a new or deleted file?");
450 function lineNumbersFromSet(set, is_last) {
454 var size = set.size();
455 var start = is_last ? (size - 1) : 0;
456 var end = is_last ? -1 : size;
457 var offset = is_last ? -1 : 1;
459 for (var i = start; i != end; i += offset) {
460 if (to != -1 && from != -1)
461 return {to: to, from: from};
463 var line_number = set[i];
464 if ($(line_number).hasClass('to')) {
466 to = Number(line_number.textContent);
469 from = Number(line_number.textContent);
474 function expand(expand_bar, file_name, direction, amount) {
475 if (file_name in original_file_contents && !patched_file_contents[file_name]) {
476 // FIXME: In this case, try fetching the source file at the revision the patch was created at.
477 // Might need to modify webkit-patch to include that data in the diff.
478 replaceExpandLinkContainers(expand_bar, "Can't expand. Unable to apply patch to tip of tree.");
482 var above_expansion = expand_bar.querySelector('.Expand' + ABOVE)
483 var below_expansion = expand_bar.querySelector('.Expand' + BELOW)
485 var above_line_numbers = $('.expansionLineNumber', above_expansion);
486 if (!above_line_numbers[0]) {
487 var diff_section = expand_bar.previousElementSibling;
488 above_line_numbers = $('.lineNumber', diff_section);
491 var above_last_line_num, above_last_from_line_num;
492 if (above_line_numbers[0]) {
493 var above_numbers = lineNumbersFromSet(above_line_numbers, true);
494 above_last_line_num = above_numbers.to;
495 above_last_from_line_num = above_numbers.from;
497 above_last_from_line_num = above_last_line_num = 0;
499 var below_line_numbers = $('.expansionLineNumber', below_expansion);
500 if (!below_line_numbers[0]) {
501 var diff_section = expand_bar.nextElementSibling;
503 below_line_numbers = $('.lineNumber', diff_section);
506 var below_first_line_num, below_first_from_line_num;
507 if (below_line_numbers[0]) {
508 var below_numbers = lineNumbersFromSet(below_line_numbers, false);
509 below_first_line_num = below_numbers.to - 1;
510 below_first_from_line_num = below_numbers.from - 1;
512 below_first_from_line_num = below_first_line_num = patched_file_contents[file_name].length - 1;
514 var start_line_num, start_from_line_num;
517 if (direction == ABOVE) {
518 start_from_line_num = above_last_from_line_num;
519 start_line_num = above_last_line_num;
520 end_line_num = Math.min(start_line_num + amount, below_first_line_num);
521 } else if (direction == BELOW) {
522 end_line_num = below_first_line_num;
523 start_line_num = Math.max(end_line_num - amount, above_last_line_num)
524 start_from_line_num = Math.max(below_first_from_line_num - amount, above_last_from_line_num)
525 } else { // direction == ALL
526 start_line_num = above_last_line_num;
527 start_from_line_num = above_last_from_line_num;
528 end_line_num = below_first_line_num;
532 // Filling in all the remaining lines. Overwrite the expand links.
533 if (start_line_num == above_last_line_num && end_line_num == below_first_line_num) {
534 expansion_area = expand_bar.querySelector('.ExpandLinkContainer');
535 expansion_area.innerHTML = '';
537 expansion_area = direction == ABOVE ? above_expansion : below_expansion;
540 insertLines(file_name, expansion_area, direction, start_line_num, end_line_num, start_from_line_num);
543 function unifiedLine(from, to, contents, is_expansion_line, opt_className, opt_attributes) {
544 var className = is_expansion_line ? 'ExpansionLine' : 'LineContainer Line';
546 className += ' ' + opt_className;
548 var lineNumberClassName = is_expansion_line ? 'expansionLineNumber' : 'lineNumber';
550 var line = $('<div class="' + className + '" ' + (opt_attributes || '') + '>' +
551 '<span class="from ' + lineNumberClassName + '">' + (from || ' ') +
552 '</span><span class="to ' + lineNumberClassName + '">' + (to || ' ') +
553 '</span> <span class="text"></span>' +
556 $('.text', line).replaceWith(contents);
560 function unifiedExpansionLine(from, to, contents) {
561 return unifiedLine(from, to, contents, true);
564 function sideBySideExpansionLine(from, to, contents) {
565 var line = $('<div class="ExpansionLine"></div>');
566 // Clone the contents so we have two copies we can put back in the DOM.
567 line.append(lineSide('from', contents.clone(true), true, from));
568 line.append(lineSide('to', contents, true, to));
572 function lineSide(side, contents, is_expansion_line, opt_line_number, opt_attributes, opt_class) {
574 if (opt_attributes || opt_class) {
575 class_name = 'class="';
577 class_name += is_expansion_line ? 'ExpansionLine' : 'Line';
578 class_name += ' ' + (opt_class || '') + '"';
581 var attributes = opt_attributes || '';
583 var line_side = $('<div class="LineSide">' +
584 '<div ' + attributes + ' ' + class_name + '>' +
585 '<span class="' + side + ' ' + (is_expansion_line ? 'expansionLineNumber' : 'lineNumber') + '">' +
586 (opt_line_number || ' ') +
588 '<span class="text"></span>' +
592 $('.text', line_side).replaceWith(contents);
596 function insertLines(file_name, expansion_area, direction, start_line_num, end_line_num, start_from_line_num) {
597 var fragment = document.createDocumentFragment();
598 var is_side_by_side = isDiffSideBySide(files[file_name]);
600 for (var i = 0; i < end_line_num - start_line_num; i++) {
601 var from = start_from_line_num + i + 1;
602 var to = start_line_num + i + 1;
603 var contents = $('<span class="text"></span>');
604 contents.text(patched_file_contents[file_name][start_line_num + i]);
605 var line = is_side_by_side ? sideBySideExpansionLine(from, to, contents) : unifiedExpansionLine(from, to, contents);
606 fragment.appendChild(line[0]);
609 if (direction == BELOW)
610 expansion_area.insertBefore(fragment, expansion_area.firstChild);
612 expansion_area.appendChild(fragment);
615 function hunkStartingLine(patched_file, context, prev_line, hunk_num) {
617 var current_line = -1;
618 var last_context_line = context[context.length - 1];
619 if (patched_file[prev_line] == last_context_line)
620 current_line = prev_line + 1;
622 for (var i = prev_line - PATCH_FUZZ; i < prev_line + PATCH_FUZZ; i++) {
623 if (patched_file[i] == last_context_line)
624 current_line = i + 1;
627 if (current_line == -1) {
628 console.log('Hunk #' + hunk_num + ' FAILED.');
633 // For paranoia sake, confirm the rest of the context matches;
634 for (var i = 0; i < context.length - 1; i++) {
635 if (patched_file[current_line - context.length + i] != context[i]) {
636 console.log('Hunk #' + hunk_num + ' FAILED. Did not match preceding context.');
644 function fromLineNumber(line) {
645 var node = line.querySelector('.from');
646 return node ? Number(node.textContent) : 0;
649 function toLineNumber(line) {
650 var node = line.querySelector('.to');
651 return node ? Number(node.textContent) : 0;
654 function textContentsFor(line) {
655 // Just get the first match since a side-by-side diff has two lines with text inside them for
656 // unmodified lines in the diff.
657 return $('.text', line).first().text();
660 function lineNumberForFirstNonContextLine(patched_file, line, prev_line, context, hunk_num) {
661 if (context.length) {
662 var prev_line_num = fromLineNumber(prev_line) - 1;
663 return hunkStartingLine(patched_file, context, prev_line_num, hunk_num);
666 if (toLineNumber(line) == 1 || fromLineNumber(line) == 1)
669 console.log('Failed to apply patch. Adds or removes lines before any context lines.');
673 function applyDiff(original_file, file_name) {
674 var diff_sections = files[file_name].getElementsByClassName('DiffSection');
675 var patched_file = original_file.concat([]);
677 // Apply diffs in reverse order to avoid needing to keep track of changing line numbers.
678 for (var i = diff_sections.length - 1; i >= 0; i--) {
679 var section = diff_sections[i];
680 var lines = section.getElementsByClassName('Line');
681 var current_line = -1;
683 var hunk_num = i + 1;
685 for (var j = 0, lines_len = lines.length; j < lines_len; j++) {
687 var line_contents = textContentsFor(line);
688 if ($(line).hasClass('add')) {
689 if (current_line == -1) {
690 current_line = lineNumberForFirstNonContextLine(patched_file, line, lines[j-1], context, hunk_num);
691 if (current_line == -1)
695 patched_file.splice(current_line, 0, line_contents);
697 } else if ($(line).hasClass('remove')) {
698 if (current_line == -1) {
699 current_line = lineNumberForFirstNonContextLine(patched_file, line, lines[j-1], context, hunk_num);
700 if (current_line == -1)
704 if (patched_file[current_line] != line_contents) {
705 console.log('Hunk #' + hunk_num + ' FAILED.');
709 patched_file.splice(current_line, 1);
710 } else if (current_line == -1) {
711 context.push(line_contents);
712 } else if (line_contents != patched_file[current_line]) {
713 console.log('Hunk #' + hunk_num + ' FAILED. Context at end did not match');
724 function openOverallComments(e) {
725 $('.overallComments textarea').addClass('open');
726 $('#statusBubbleContainer').addClass('wrap');
729 function onBodyResize() {
730 updateToolbarAnchorState();
733 function updateToolbarAnchorState() {
734 var has_scrollbar = window.innerWidth > document.documentElement.offsetWidth;
735 $('#toolbar').toggleClass('anchored', has_scrollbar);
738 function diffLinksHtml(opt_containerClassName) {
739 var containerClassName = opt_containerClassName || '';
740 return '<div class="DiffLinks ' + containerClassName + '">' +
741 '<a href="javascript:" class="unify-link">unified</a>' +
742 '<a href="javascript:" class="side-by-side-link">side-by-side</a>' +
746 $(document).ready(function() {
749 $(document.body).prepend('<div id="message">' +
750 '<div class="help">Select line numbers to add a comment.' +
751 diffLinksHtml('LinkContainer') +
753 '<div class="commentStatus"></div>' +
755 $(document.body).append('<div id="toolbar">' +
756 '<div class="overallComments">' +
757 '<textarea placeholder="Overall comments"></textarea>' +
760 '<span id="statusBubbleContainer"></span>' +
761 '<span class="actions">' +
762 '<span class="links"><span class="bugLink"></span></span>' +
763 '<span id="flagContainer"></span>' +
764 '<button id="preview_comments">Preview</button>' +
765 '<button id="post_comments">Publish</button> ' +
770 $('.overallComments textarea').bind('click', openOverallComments);
772 $(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>');
774 // Create a dummy iframe and monitor resizes in it's contentWindow to detect when the top document's body changes size.
775 // FIXME: Should we setTimeout throttle these?
776 var resize_iframe = $('<iframe class="pseudo_resize_event_iframe"></iframe>');
777 $(document.body).append(resize_iframe);
778 $(resize_iframe[0].contentWindow).bind('resize', onBodyResize);
780 updateToolbarAnchorState();
784 function loadDiffState() {
785 var diffstate = localStorage.getItem('code-review-diffstate');
786 if (diffstate != 'sidebyside' && diffstate != 'unified')
789 convertAllFileDiffs(diffstate, $('.FileDiff'));
792 function isDiffSideBySide(file_diff) {
793 return diffState(file_diff) == 'sidebyside';
796 function diffState(file_diff) {
797 var diff_state = $(file_diff).attr('data-diffstate');
798 return diff_state || 'unified';
801 function unifyLine(line, from, to, contents, classNames, attributes, id) {
802 var new_line = unifiedLine(from, to, contents, false, classNames, attributes);
803 var old_line = $(line);
804 if (!old_line.hasClass('LineContainer'))
805 old_line = old_line.parents('.LineContainer');
807 var comments = commentsToTransferFor($(document.getElementById(id)));
808 old_line.after(comments);
809 old_line.replaceWith(new_line);
812 function updateDiffLinkVisibility(file_diff) {
813 if (diffState(file_diff) == 'unified') {
814 $('.side-by-side-link', file_diff).show();
815 $('.unify-link', file_diff).hide();
817 $('.side-by-side-link', file_diff).hide();
818 $('.unify-link', file_diff).show();
822 function convertAllFileDiffs(diff_type, file_diffs) {
823 file_diffs.each(function() {
824 convertFileDiff(diff_type, this);
828 function convertFileDiff(diff_type, file_diff) {
829 if (diffState(file_diff) == diff_type)
832 $(file_diff).removeClass('sidebyside unified');
833 $(file_diff).addClass(diff_type);
835 $(file_diff).attr('data-diffstate', diff_type);
836 updateDiffLinkVisibility(file_diff);
838 $('.shared .Line', file_diff).each(function() {
839 convertLine(diff_type, this);
842 $('.ExpansionLine', file_diff).each(function() {
843 convertExpansionLine(diff_type, this);
847 function convertLine(diff_type, line) {
848 var convert_function = diff_type == 'sidebyside' ? sideBySideifyLine : unifyLine;
849 var from = fromLineNumber(line);
850 var to = toLineNumber(line);
851 var contents = $('.text', line).first();
852 var classNames = classNamesForMovingLine(line);
853 var attributes = attributesForMovingLine(line);
855 convert_function(line, from, to, contents, classNames, attributes, id)
858 function classNamesForMovingLine(line) {
859 var classParts = line.className.split(' ');
860 var classBuffer = [];
861 for (var i = 0; i < classParts.length; i++) {
862 var part = classParts[i];
863 if (part != 'LineContainer' && part != 'Line')
864 classBuffer.push(part);
866 return classBuffer.join(' ');
869 function attributesForMovingLine(line) {
870 var attributesBuffer = ['id=' + line.id];
871 // Make sure to keep all data- attributes.
872 $(line.attributes).each(function() {
873 if (this.name.indexOf('data-') == 0)
874 attributesBuffer.push(this.name + '=' + this.value);
876 return attributesBuffer.join(' ');
879 function sideBySideifyLine(line, from, to, contents, classNames, attributes, id) {
882 var from_attributes = '';
883 var to_attributes = '';
884 // Clone the contents so we have two copies we can put back in the DOM.
885 var from_contents = contents.clone(true);
886 var to_contents = contents;
888 var container_class = 'LineContainer';
889 var container_attributes = '';
891 if (from && !to) { // This is a remove line.
892 from_class = classNames;
893 from_attributes = attributes;
895 } else if (to && !from) { // This is an add line.
896 to_class = classNames;
897 to_attributes = attributes;
900 container_attributes = attributes;
901 container_class += ' Line ' + classNames;
904 var new_line = $('<div ' + container_attributes + ' class="' + container_class + '"></div>');
905 new_line.append(lineSide('from', from_contents, false, from, from_attributes, from_class));
906 new_line.append(lineSide('to', to_contents, false, to, to_attributes, to_class));
908 $(line).replaceWith(new_line);
910 var line = $(document.getElementById(id));
911 line.after(commentsToTransferFor(line));
914 function convertExpansionLine(diff_type, line) {
915 var convert_function = diff_type == 'sidebyside' ? sideBySideExpansionLine : unifiedExpansionLine;
916 var contents = $('.text', line).first();
917 var from = fromLineNumber(line);
918 var to = toLineNumber(line);
919 var new_line = convert_function(from, to, contents);
920 $(line).replaceWith(new_line);
923 function commentsToTransferFor(line) {
924 var fragment = document.createDocumentFragment();
926 previousCommentsFor(line).each(function() {
927 fragment.appendChild(this);
930 var active_comments = activeCommentFor(line);
931 var num_active_comments = active_comments.size();
932 if (num_active_comments > 0) {
933 if (num_active_comments > 1)
934 console.log('ERROR: There is more than one active comment for ' + line.attr('id') + '.');
936 var parent = active_comments[0].parentNode;
937 var frozenComment = parent.nextSibling;
938 fragment.appendChild(parent);
939 fragment.appendChild(frozenComment);
945 function discardComment() {
946 var line_id = $(this).parentsUntil('.comment').parent().find('textarea').attr('data-comment-for');
947 var line = $('#' + line_id)
948 findCommentBlockFor(line).slideUp('fast', function() {
950 line.removeAttr('data-has-comment');
951 trimCommentContextToBefore(line, line.attr('data-comment-base-line'));
955 function unfreezeComment() {
956 $(this).prev().show();
960 $('.side-by-side-link').live('click', handleSideBySideLinkClick);
961 $('.unify-link').live('click', handleUnifyLinkClick);
962 $('.ExpandLink').live('click', handleExpandLinkClick);
963 $('.comment .discard').live('click', discardComment);
964 $('.frozenComment').live('click', unfreezeComment);
966 $('.comment .ok').live('click', function() {
967 var comment_textarea = $(this).parentsUntil('.comment').parent().find('textarea');
968 if (comment_textarea.val().trim() == '') {
969 discardComment.call(this);
972 var line_id = comment_textarea.attr('data-comment-for');
973 var line = $('#' + line_id)
974 findCommentBlockFor(line).hide().after($('<div class="frozenComment"></div>').text(comment_textarea.val()));
977 function focusOn(node) {
978 $('.focused').removeClass('focused');
979 if (node.length == 0)
981 $(document).scrollTop(node.addClass('focused').position().top - window.innerHeight / 2);
984 function focusNext(className, is_backward) {
985 var focusable_nodes = $('.previousComment,.DiffBlock').filter(function() {
986 return ($(this).hasClass('previousComment') || $('.add,.remove', this).size());
989 var index = focusable_nodes.index($('.focused'));
990 if (index == -1 && is_backward)
991 index = focusable_nodes.length;
993 var offset = is_backward ? -1 : 1;
994 var end = is_backward ? -1 : focusable_nodes.size();
995 for (var i = index + offset; i != end; i = i + offset) {
996 var node = $(focusable_nodes[i]);
997 if (node.hasClass(className)) {
1004 var kCharCodeForN = 'n'.charCodeAt(0);
1005 var kCharCodeForP = 'p'.charCodeAt(0);
1006 var kCharCodeForJ = 'j'.charCodeAt(0);
1007 var kCharCodeForK = 'k'.charCodeAt(0);
1009 $('body').live('keypress', function() {
1010 // FIXME: There's got to be a better way to avoid seeing these keypress
1012 if (event.target.nodeName == 'TEXTAREA')
1015 switch (event.charCode) {
1017 focusNext('previousComment', false);
1021 focusNext('previousComment', true);
1025 focusNext('DiffBlock', false);
1029 focusNext('DiffBlock', true);
1034 function contextLinesFor(comment_base_lines, file_diff) {
1035 var base_lines = comment_base_lines.split(' ');
1036 return $('div[data-comment-base-line]', file_diff).filter(function() {
1037 return $(this).attr('data-comment-base-line').split(' ').some(function(item) {
1038 return base_lines.indexOf(item) != -1;
1043 function numberFrom(line_id) {
1044 return Number(line_id.replace('line', ''));
1047 function trimCommentContextToBefore(line, comment_base_line) {
1048 var line_to_trim_to = numberFrom(line.attr('id'));
1049 contextLinesFor(comment_base_line, fileDiffFor(line)).each(function() {
1050 var id = $(this).attr('id');
1051 if (numberFrom(id) > line_to_trim_to)
1054 removeDataCommentBaseLine(this, comment_base_line);
1055 if (!$(this).attr('data-comment-base-line'))
1056 $(this).removeClass('commentContext');
1060 var drag_select_start_index = -1;
1062 function stopDragSelect() {
1063 $('.selected').removeClass('selected');
1064 drag_select_start_index = -1;
1067 function lineOffsetFrom(line, offset) {
1068 var file_diff = line.parents('.FileDiff');
1069 var all_lines = $('.Line', file_diff);
1070 var index = all_lines.index(line);
1071 return $(all_lines[index + offset]);
1074 function previousLineFor(line) {
1075 return lineOffsetFrom(line, -1);
1078 function nextLineFor(line) {
1079 return lineOffsetFrom(line, 1);
1082 $('.lineNumber').live('click', function() {
1083 var line = lineFromLineDescendant($(this));
1084 if (line.hasClass('commentContext'))
1085 trimCommentContextToBefore(previousLineFor(line), line.attr('data-comment-base-line'));
1086 }).live('mousedown', function() {
1087 var line = lineFromLineDescendant($(this));
1088 drag_select_start_index = numberFrom(line.attr('id'));
1089 line.addClass('selected');
1090 event.preventDefault();
1093 function selectTo(focus_index) {
1094 var selected = $('.selected').removeClass('selected');
1095 var is_backward = drag_select_start_index > focus_index;
1096 var current_index = is_backward ? focus_index : drag_select_start_index;
1097 var last_index = is_backward ? drag_select_start_index : focus_index;
1098 while (current_index <= last_index) {
1099 $('#line' + current_index).addClass('selected')
1104 function selectToLineContainer(line_container) {
1105 var line = lineFromLineContainer(line_container);
1106 selectTo(numberFrom(line.attr('id')));
1109 $('.LineContainer').live('mouseenter', function() {
1110 if (drag_select_start_index == -1)
1112 selectToLineContainer(this);
1113 }).live('mouseup', function() {
1114 if (drag_select_start_index == -1)
1117 selectToLineContainer(this);
1119 var selected = $('.selected');
1120 var already_has_comment = selected.last().hasClass('commentContext');
1121 selected.addClass('commentContext');
1123 var comment_base_line;
1124 if (already_has_comment)
1125 comment_base_line = selected.last().attr('data-comment-base-line');
1127 var last = lineFromLineDescendant(selected.last());
1128 addCommentFor($(last));
1129 comment_base_line = last.attr('id');
1132 selected.each(function() {
1133 addDataCommentBaseLine(this, comment_base_line);
1137 function addDataCommentBaseLine(line, id) {
1138 var val = $(line).attr('data-comment-base-line');
1140 var parts = val ? val.split(' ') : [];
1141 for (var i = 0; i < parts.length; i++) {
1147 $(line).attr('data-comment-base-line', parts.join(' '));
1150 function removeDataCommentBaseLine(line, comment_base_lines) {
1151 var val = $(line).attr('data-comment-base-line');
1155 var base_lines = comment_base_lines.split(' ');
1156 var parts = val.split(' ');
1158 for (var i = 0; i < parts.length; i++) {
1159 if (base_lines.indexOf(parts[i]) == -1)
1160 newVal.push(parts[i]);
1163 $(line).attr('data-comment-base-line', newVal.join(' '));
1166 function lineFromLineDescendant(descendant) {
1167 return descendant.hasClass('Line') ? descendant : descendant.parents('.Line');
1170 function lineFromLineContainer(lineContainer) {
1171 var line = $(lineContainer);
1172 if (!line.hasClass('Line'))
1173 line = $('.Line', line);
1177 $('.DiffSection').live('mouseleave', stopDragSelect).live('mouseup', stopDragSelect);
1179 function contextSnippetFor(line, indent) {
1181 contextLinesFor(line.attr('id'), fileDiffFor(line)).each(function() {
1183 if ($(this).hasClass('add'))
1185 else if ($(this).hasClass('remove'))
1187 snippets.push(indent + action + textContentsFor(this));
1189 return snippets.join('\n');
1192 function fileNameFor(line) {
1193 return fileDiffFor(line).find('h1').text();
1196 function indentFor(depth) {
1197 return (new Array(depth + 1)).join('>') + ' ';
1200 function snippetFor(line, indent) {
1201 var file_name = fileNameFor(line);
1202 var line_number = line.hasClass('remove') ? '-' + fromLineNumber(line[0]) : toLineNumber(line[0]);
1203 return indent + file_name + ':' + line_number + '\n' + contextSnippetFor(line, indent);
1206 function quotePreviousComments(comments) {
1207 var quoted_comments = [];
1208 var depth = comments.size();
1209 comments.each(function() {
1210 var indent = indentFor(depth--);
1211 var text = $(this).children('.content').text();
1212 quoted_comments.push(indent + '\n' + indent + text.split('\n').join('\n' + indent));
1214 return quoted_comments.join('\n');
1217 $('#comment_form .winter').live('click', function() {
1218 $('#comment_form').addClass('inactive');
1221 function fillInReviewForm() {
1222 var comments_in_context = []
1223 forEachLine(function(line) {
1224 if (line.attr('data-has-comment') != 'true')
1226 var comment = findCommentBlockFor(line).children('textarea').val().trim();
1229 var previous_comments = previousCommentsFor(line);
1230 var snippet = snippetFor(line, indentFor(previous_comments.size() + 1));
1231 var quoted_comments = quotePreviousComments(previous_comments);
1232 var comment_with_context = [];
1233 comment_with_context.push(snippet);
1234 if (quoted_comments != '')
1235 comment_with_context.push(quoted_comments);
1236 comment_with_context.push('\n' + comment);
1237 comments_in_context.push(comment_with_context.join('\n'));
1239 var comment = $('.overallComments textarea').val().trim();
1242 comment += comments_in_context.join('\n\n');
1243 if (comments_in_context.length > 0)
1244 comment = 'View in context: ' + window.location + '\n\n' + comment;
1245 var review_form = $('#reviewform').contents();
1246 review_form.find('#comment').val(comment);
1247 review_form.find('#flags select').each(function() {
1248 var control = findControlForFlag(this);
1249 if (!control.size())
1251 $(this).attr('selectedIndex', control.attr('selectedIndex'));
1255 $('#preview_comments').live('click', function() {
1257 $('#comment_form').removeClass('inactive');
1260 $('#post_comments').live('click', function() {
1262 $('#reviewform').contents().find('form').submit();