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 getWebKitSourceFile(file_name, onLoad, expand_bar) {
412 function handleLoad(contents) {
413 original_file_contents[file_name] = contents.split('\n');
414 patched_file_contents[file_name] = applyDiff(original_file_contents[file_name], file_name);
419 url: WEBKIT_BASE_DIR + file_name,
420 context: document.body,
421 complete: function(xhr, data) {
423 handleLoadError(expand_bar);
425 handleLoad(xhr.responseText);
430 function replaceExpandLinkContainers(expand_bar, text) {
431 $('.ExpandLinkContainer', $(expand_bar).parents('.FileDiff')).replaceWith('<span class="ExpandText">' + text + '</span>');
434 function handleLoadError(expand_bar) {
435 // FIXME: In this case, try fetching the source file at the revision the patch was created at,
436 // in case the file has bee deleted.
437 // Might need to modify webkit-patch to include that data in the diff.
438 replaceExpandLinkContainers(expand_bar, "Can't expand. Is this a new or deleted file?");
445 function expand(expand_bar, file_name, direction, amount) {
446 if (file_name in original_file_contents && !patched_file_contents[file_name]) {
447 // FIXME: In this case, try fetching the source file at the revision the patch was created at.
448 // Might need to modify webkit-patch to include that data in the diff.
449 replaceExpandLinkContainers(expand_bar, "Can't expand. Unable to apply patch to tip of tree.");
453 var above_expansion = expand_bar.querySelector('.Expand' + ABOVE)
454 var below_expansion = expand_bar.querySelector('.Expand' + BELOW)
456 var above_last_line = above_expansion.querySelector('.ExpansionLine:last-of-type');
457 if (!above_last_line) {
458 var diff_section = expand_bar.previousElementSibling;
459 above_last_line = diff_section.querySelector('.LineContainer:last-of-type');
462 var above_last_line_num, above_last_from_line_num;
463 if (above_last_line) {
464 above_last_line_num = toLineNumber(above_last_line);
465 above_last_from_line_num = fromLineNumber(above_last_line);
467 above_last_from_line_num = above_last_line_num = 0;
469 var below_first_line = below_expansion.querySelector('.ExpansionLine');
470 if (!below_first_line) {
471 var diff_section = expand_bar.nextElementSibling;
473 below_first_line = diff_section.querySelector('.LineContainer');
476 var below_first_line_num, below_first_from_line_num;
477 if (below_first_line) {
478 below_first_line_num = toLineNumber(below_first_line) - 1;
479 below_first_from_line_num = fromLineNumber(below_first_line) - 1;
481 below_first_from_line_num = below_first_line_num = patched_file_contents[file_name].length - 1;
483 var start_line_num, start_from_line_num;
486 if (direction == ABOVE) {
487 start_from_line_num = above_last_from_line_num;
488 start_line_num = above_last_line_num;
489 end_line_num = Math.min(start_line_num + amount, below_first_line_num);
490 } else if (direction == BELOW) {
491 end_line_num = below_first_line_num;
492 start_line_num = Math.max(end_line_num - amount, above_last_line_num)
493 start_from_line_num = Math.max(below_first_from_line_num - amount, above_last_from_line_num)
494 } else { // direction == ALL
495 start_line_num = above_last_line_num;
496 start_from_line_num = above_last_from_line_num;
497 end_line_num = below_first_line_num;
501 // Filling in all the remaining lines. Overwrite the expand links.
502 if (start_line_num == above_last_line_num && end_line_num == below_first_line_num) {
503 expansion_area = expand_bar.querySelector('.ExpandLinkContainer');
504 expansion_area.innerHTML = '';
506 expansion_area = direction == ABOVE ? above_expansion : below_expansion;
509 insertLines(file_name, expansion_area, direction, start_line_num, end_line_num, start_from_line_num);
512 function unifiedLine(from, to, contents, is_expansion_line, opt_className, opt_attributes) {
513 var className = is_expansion_line ? 'ExpansionLine' : 'LineContainer Line';
515 className += ' ' + opt_className;
517 var lineNumberClassName = is_expansion_line ? 'expansionLineNumber' : 'lineNumber';
519 var line = $('<div class="' + className + '" ' + (opt_attributes || '') + '>' +
520 '<span class="from ' + lineNumberClassName + '">' + (from || ' ') +
521 '</span><span class="to ' + lineNumberClassName + '">' + (to || ' ') +
522 '</span> <span class="text"></span>' +
525 $('.text', line).replaceWith(contents);
529 function unifiedExpansionLine(line_number, contents) {
530 return unifiedLine(line_number, line_number, contents, true);
533 function sideBySideExpansionLine(line_number, contents) {
534 var line = $('<div class="ExpansionLine"></div>');
535 line.append(lineSide('from', contents, true, line_number));
536 line.append(lineSide('to', contents, true, line_number));
540 function lineSide(side, contents, is_expansion_line, opt_line_number, opt_attributes, opt_class) {
542 if (opt_attributes || opt_class) {
543 class_name = 'class="';
545 class_name += is_expansion_line ? 'ExpansionLine' : 'Line';
546 class_name += ' ' + (opt_class || '') + '"';
549 var attributes = opt_attributes || '';
551 var line_side = $('<div class="LineSide">' +
552 '<div ' + attributes + ' ' + class_name + '>' +
553 '<span class="' + side + ' ' + (is_expansion_line ? 'expansionLineNumber' : 'lineNumber') + '">' +
554 (opt_line_number || ' ') +
556 '<span class="text"></span>' +
560 $('.text', line_side).replaceWith(contents);
564 function insertLines(file_name, expansion_area, direction, start_line_num, end_line_num, start_from_line_num) {
565 var fragment = document.createDocumentFragment();
566 var is_side_by_side = isDiffSideBySide(files[file_name]);
568 for (var i = 0; i < end_line_num - start_line_num; i++) {
569 // FIXME: from line numbers are wrong
570 var line_number = start_from_line_num + i + 1;
571 var contents = $('<span class="text"></span>');
572 contents.text(patched_file_contents[file_name][start_line_num + i]);
573 var line = is_side_by_side ? sideBySideExpansionLine(line_number, contents) : unifiedExpansionLine(line_number, contents);
574 fragment.appendChild(line[0]);
577 if (direction == BELOW)
578 expansion_area.insertBefore(fragment, expansion_area.firstChild);
580 expansion_area.appendChild(fragment);
583 function hunkStartingLine(patched_file, context, prev_line, hunk_num) {
585 var current_line = -1;
586 var last_context_line = context[context.length - 1];
587 if (patched_file[prev_line] == last_context_line)
588 current_line = prev_line + 1;
590 for (var i = prev_line - PATCH_FUZZ; i < prev_line + PATCH_FUZZ; i++) {
591 if (patched_file[i] == last_context_line)
592 current_line = i + 1;
595 if (current_line == -1) {
596 console.log('Hunk #' + hunk_num + ' FAILED.');
601 // For paranoia sake, confirm the rest of the context matches;
602 for (var i = 0; i < context.length - 1; i++) {
603 if (patched_file[current_line - context.length + i] != context[i]) {
604 console.log('Hunk #' + hunk_num + ' FAILED. Did not match preceding context.');
612 function fromLineNumber(line) {
613 var node = line.querySelector('.from');
614 return node ? Number(node.textContent) : 0;
617 function toLineNumber(line) {
618 var node = line.querySelector('.to');
619 return node ? Number(node.textContent) : 0;
622 function textContentsFor(line) {
623 // Just get the first match since a side-by-side diff has two lines with text inside them for
624 // unmodified lines in the diff.
625 return $('.text', line).first().text();
628 function lineNumberForFirstNonContextLine(patched_file, line, prev_line, context, hunk_num) {
629 if (context.length) {
630 var prev_line_num = fromLineNumber(prev_line) - 1;
631 return hunkStartingLine(patched_file, context, prev_line_num, hunk_num);
634 if (toLineNumber(line) == 1 || fromLineNumber(line) == 1)
637 console.log('Failed to apply patch. Adds or removes lines before any context lines.');
641 function applyDiff(original_file, file_name) {
642 var diff_sections = files[file_name].getElementsByClassName('DiffSection');
643 var patched_file = original_file.concat([]);
645 // Apply diffs in reverse order to avoid needing to keep track of changing line numbers.
646 for (var i = diff_sections.length - 1; i >= 0; i--) {
647 var section = diff_sections[i];
648 var lines = section.getElementsByClassName('Line');
649 var current_line = -1;
651 var hunk_num = i + 1;
653 for (var j = 0, lines_len = lines.length; j < lines_len; j++) {
655 var line_contents = textContentsFor(line);
656 if ($(line).hasClass('add')) {
657 if (current_line == -1) {
658 current_line = lineNumberForFirstNonContextLine(patched_file, line, lines[j-1], context, hunk_num);
659 if (current_line == -1)
663 patched_file.splice(current_line, 0, line_contents);
665 } else if ($(line).hasClass('remove')) {
666 if (current_line == -1) {
667 current_line = lineNumberForFirstNonContextLine(patched_file, line, lines[j-1], context, hunk_num);
668 if (current_line == -1)
672 if (patched_file[current_line] != line_contents) {
673 console.log('Hunk #' + hunk_num + ' FAILED.');
677 patched_file.splice(current_line, 1);
678 } else if (current_line == -1) {
679 context.push(line_contents);
680 } else if (line_contents != patched_file[current_line]) {
681 console.log('Hunk #' + hunk_num + ' FAILED. Context at end did not match');
692 function openOverallComments(e) {
693 $('.overallComments textarea').addClass('open');
694 $('#statusBubbleContainer').addClass('wrap');
697 function onBodyResize() {
698 updateToolbarAnchorState();
701 function updateToolbarAnchorState() {
702 var has_scrollbar = window.innerWidth > document.documentElement.offsetWidth;
703 $('#toolbar').toggleClass('anchored', has_scrollbar);
706 function diffLinksHtml(opt_containerClassName) {
707 var containerClassName = opt_containerClassName || '';
708 return '<div class="DiffLinks ' + containerClassName + '">' +
709 '<a href="javascript:" class="unify-link">unified</a>' +
710 '<a href="javascript:" class="side-by-side-link">side-by-side</a>' +
714 $(document).ready(function() {
717 $(document.body).prepend('<div id="message">' +
718 '<div class="help">Select line numbers to add a comment.' +
719 diffLinksHtml('LinkContainer') +
721 '<div class="commentStatus"></div>' +
723 $(document.body).append('<div id="toolbar">' +
724 '<div class="overallComments">' +
725 '<textarea placeholder="Overall comments"></textarea>' +
728 '<span id="statusBubbleContainer"></span>' +
729 '<span class="actions">' +
730 '<span class="links"><span class="bugLink"></span></span>' +
731 '<span id="flagContainer"></span>' +
732 '<button id="preview_comments">Preview</button>' +
733 '<button id="post_comments">Publish</button> ' +
738 $('.overallComments textarea').bind('click', openOverallComments);
740 $(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>');
742 // Create a dummy iframe and monitor resizes in it's contentWindow to detect when the top document's body changes size.
743 // FIXME: Should we setTimeout throttle these?
744 var resize_iframe = $('<iframe class="pseudo_resize_event_iframe"></iframe>');
745 $(document.body).append(resize_iframe);
746 $(resize_iframe[0].contentWindow).bind('resize', onBodyResize);
748 updateToolbarAnchorState();
752 function loadDiffState() {
753 var diffstate = localStorage.getItem('code-review-diffstate');
754 if (diffstate != 'sidebyside' && diffstate != 'unified')
757 convertAllFileDiffs(diffstate, $('.FileDiff'));
760 function isDiffSideBySide(file_diff) {
761 return diffState(file_diff) == 'sidebyside';
764 function diffState(file_diff) {
765 var diff_state = $(file_diff).attr('data-diffstate');
766 return diff_state || 'unified';
769 function unifyLine(line, from, to, contents, classNames, attributes, id) {
770 var new_line = unifiedLine(from, to, contents, false, classNames, attributes);
771 var old_line = $(line);
772 if (!old_line.hasClass('LineContainer'))
773 old_line = old_line.parents('.LineContainer');
775 var comments = commentsToTransferFor($(document.getElementById(id)));
776 old_line.after(comments);
777 old_line.replaceWith(new_line);
780 function updateDiffLinkVisibility(file_diff) {
781 if (diffState(file_diff) == 'unified') {
782 $('.side-by-side-link', file_diff).show();
783 $('.unify-link', file_diff).hide();
785 $('.side-by-side-link', file_diff).hide();
786 $('.unify-link', file_diff).show();
790 function convertAllFileDiffs(diff_type, file_diffs) {
791 file_diffs.each(function() {
792 convertFileDiff(diff_type, this);
796 function convertFileDiff(diff_type, file_diff) {
797 if (diffState(file_diff) == diff_type)
800 $(file_diff).attr('data-diffstate', diff_type);
801 updateDiffLinkVisibility(file_diff);
803 $('.Line', file_diff).each(function() {
804 convertLine(diff_type, this);
807 $('.ExpansionLine', file_diff).each(function() {
808 convertExpansionLine(diff_type, this);
812 function convertLine(diff_type, line) {
813 var convert_function = diff_type == 'sidebyside' ? sideBySideifyLine : unifyLine;
814 var from = fromLineNumber(line);
815 var to = toLineNumber(line);
816 var contents = $('.text', line);
817 var classNames = classNamesForMovingLine(line);
818 var attributes = attributesForMovingLine(line);
820 convert_function(line, from, to, contents, classNames, attributes, id)
823 function classNamesForMovingLine(line) {
824 var classParts = line.className.split(' ');
825 var classBuffer = [];
826 for (var i = 0; i < classParts.length; i++) {
827 var part = classParts[i];
828 if (part != 'LineContainer' && part != 'Line')
829 classBuffer.push(part);
831 return classBuffer.join(' ');
834 function attributesForMovingLine(line) {
835 var attributesBuffer = ['id=' + line.id];
836 // Make sure to keep all data- attributes.
837 $(line.attributes).each(function() {
838 if (this.name.indexOf('data-') == 0)
839 attributesBuffer.push(this.name + '=' + this.value);
841 return attributesBuffer.join(' ');
844 // FIXME: Put removed lines to the left of their corresponding added lines.
845 function sideBySideifyLine(line, from, to, contents, classNames, attributes, id) {
848 var from_attributes = '';
849 var to_attributes = '';
850 // Clone the contents so we have two copies we can put back in the DOM.
851 var from_contents = contents.clone(true);
852 var to_contents = contents;
854 var container_class = 'LineContainer';
855 var container_attributes = '';
857 if (from && !to) { // This is a remove line.
858 from_class = classNames;
859 from_attributes = attributes;
861 } else if (to && !from) { // This is an add line.
862 to_class = classNames;
863 to_attributes = attributes;
866 container_attributes = attributes;
867 container_class += ' Line ' + classNames;
870 var new_line = $('<div ' + container_attributes + ' class="' + container_class + '"></div>');
871 new_line.append(lineSide('from', from_contents, false, from, from_attributes, from_class));
872 new_line.append(lineSide('to', to_contents, false, to, to_attributes, to_class));
874 $(line).replaceWith(new_line);
876 var line = $(document.getElementById(id));
877 line.after(commentsToTransferFor(line));
880 function convertExpansionLine(diff_type, line) {
881 var convert_function = diff_type == 'sidebyside' ? sideBySideExpansionLine : unifiedExpansionLine;
882 var contents = $('.text', line);
883 var line_number = fromLineNumber(line);
884 var new_line = convert_function(line_number, contents);
885 $(line).replaceWith(new_line);
888 function commentsToTransferFor(line) {
889 var fragment = document.createDocumentFragment();
891 previousCommentsFor(line).each(function() {
892 fragment.appendChild(this);
895 var active_comments = activeCommentFor(line);
896 var num_active_comments = active_comments.size();
897 if (num_active_comments > 0) {
898 if (num_active_comments > 1)
899 console.log('ERROR: There is more than one active comment for ' + line.attr('id') + '.');
901 var parent = active_comments[0].parentNode;
902 var frozenComment = parent.nextSibling;
903 fragment.appendChild(parent);
904 fragment.appendChild(frozenComment);
910 function discardComment() {
911 var line_id = $(this).parentsUntil('.comment').parent().find('textarea').attr('data-comment-for');
912 var line = $('#' + line_id)
913 findCommentBlockFor(line).slideUp('fast', function() {
915 line.removeAttr('data-has-comment');
916 trimCommentContextToBefore(line);
920 function unfreezeComment() {
921 $(this).prev().show();
925 $('.side-by-side-link').live('click', handleSideBySideLinkClick);
926 $('.unify-link').live('click', handleUnifyLinkClick);
927 $('.ExpandLink').live('click', handleExpandLinkClick);
928 $('.comment .discard').live('click', discardComment);
929 $('.frozenComment').live('click', unfreezeComment);
931 $('.comment .ok').live('click', function() {
932 var comment_textarea = $(this).parentsUntil('.comment').parent().find('textarea');
933 if (comment_textarea.val().trim() == '') {
934 discardComment.call(this);
937 var line_id = comment_textarea.attr('data-comment-for');
938 var line = $('#' + line_id)
939 findCommentBlockFor(line).hide().after($('<div class="frozenComment"></div>').text(comment_textarea.val()));
942 function focusOn(node) {
943 $('.focused').removeClass('focused');
944 if (node.length == 0)
946 $(document).scrollTop(node.addClass('focused').position().top - window.innerHeight / 2);
949 function focusNext(className, is_backward) {
950 var focusable_nodes = $('.previousComment,.DiffBlock').filter(function() {
951 return ($(this).hasClass('previousComment') || $('.add,.remove', this).size());
954 var index = focusable_nodes.index($('.focused'));
955 if (index == -1 && is_backward)
956 index = focusable_nodes.length;
958 var offset = is_backward ? -1 : 1;
959 var end = is_backward ? -1 : focusable_nodes.size();
960 for (var i = index + offset; i != end; i = i + offset) {
961 var node = $(focusable_nodes[i]);
962 if (node.hasClass(className)) {
969 var kCharCodeForN = 'n'.charCodeAt(0);
970 var kCharCodeForP = 'p'.charCodeAt(0);
971 var kCharCodeForJ = 'j'.charCodeAt(0);
972 var kCharCodeForK = 'k'.charCodeAt(0);
974 $('body').live('keypress', function() {
975 // FIXME: There's got to be a better way to avoid seeing these keypress
977 if (event.target.nodeName == 'TEXTAREA')
980 switch (event.charCode) {
982 focusNext('previousComment', false);
986 focusNext('previousComment', true);
990 focusNext('DiffBlock', false);
994 focusNext('DiffBlock', true);
999 function contextLinesFor(line_id) {
1000 return $('div[data-comment-base-line~="' + line_id + '"]');
1003 function numberFrom(line_id) {
1004 return Number(line_id.replace('line', ''));
1007 function trimCommentContextToBefore(line) {
1008 var base_line_id = line.attr('data-comment-base-line');
1009 var line_to_trim_to = numberFrom(line.attr('id'));
1010 contextLinesFor(base_line_id).each(function() {
1011 var id = $(this).attr('id');
1012 if (numberFrom(id) > line_to_trim_to)
1015 removeDataCommentBaseLine(this, base_line_id);
1016 if (!$(this).attr('data-comment-base-line'))
1017 $(this).removeClass('commentContext');
1021 var in_drag_select = false;
1023 function stopDragSelect() {
1024 $('.selected').removeClass('selected');
1025 in_drag_select = false;
1028 function lineOffsetFrom(line, offset) {
1029 var file_diff = line.parents('.FileDiff');
1030 var all_lines = $('.Line', file_diff);
1031 var index = all_lines.index(line);
1032 return $(all_lines[index + offset]);
1035 function previousLineFor(line) {
1036 return lineOffsetFrom(line, -1);
1039 function nextLineFor(line) {
1040 return lineOffsetFrom(line, 1);
1043 $('.lineNumber').live('click', function() {
1044 var line = $(this).parents('.Line');
1045 if (line.hasClass('commentContext'))
1046 trimCommentContextToBefore(previousLineFor(line));
1047 }).live('mousedown', function() {
1048 in_drag_select = true;
1049 $(lineFromLineDescendant(this)).addClass('selected');
1050 event.preventDefault();
1053 $('.LineContainer').live('mouseenter', function() {
1054 if (!in_drag_select)
1057 var line = lineFromLineContainer(this);
1058 line.addClass('selected');
1059 }).live('mouseup', function() {
1060 if (!in_drag_select)
1062 var selected = $('.selected');
1063 var should_add_comment = !nextLineFor(selected.last()).hasClass('commentContext');
1064 selected.addClass('commentContext');
1067 if (should_add_comment) {
1068 var last = lineFromLineDescendant(selected.last()[0]);
1069 addCommentFor($(last));
1072 id = nextLineFor(selected.last())[0].getAttribute('data-comment-base-line');
1075 selected.each(function() {
1076 addDataCommentBaseLine(this, id);
1080 function addDataCommentBaseLine(line, id) {
1081 var val = $(line).attr('data-comment-base-line');
1083 var parts = val ? val.split(' ') : [];
1084 for (var i = 0; i < parts.length; i++) {
1090 $(line).attr('data-comment-base-line', parts.join(' '));
1093 function removeDataCommentBaseLine(line, id) {
1094 var val = $(line).attr('data-comment-base-line');
1098 var parts = val.split(' ');
1100 for (var i = 0; i < parts.length; i++) {
1102 newVal.push(parts[i]);
1105 $(line).attr('data-comment-base-line', newVal.join(' '));
1108 function lineFromLineDescendant(descendant) {
1109 while (descendant && !$(descendant).hasClass('Line')) {
1110 descendant = descendant.parentNode;
1115 function lineFromLineContainer(lineContainer) {
1116 var line = $(lineContainer);
1117 if (!line.hasClass('Line'))
1118 line = $('.Line', line);
1122 $('.DiffSection').live('mouseleave', stopDragSelect).live('mouseup', stopDragSelect);
1124 function contextSnippetFor(line, indent) {
1126 contextLinesFor(line.attr('id')).each(function() {
1128 if ($(this).hasClass('add'))
1130 else if ($(this).hasClass('remove'))
1132 snippets.push(indent + action + textContentsFor(this));
1134 return snippets.join('\n');
1137 function fileNameFor(line) {
1138 return fileDiffFor(line).find('h1').text();
1141 function indentFor(depth) {
1142 return (new Array(depth + 1)).join('>') + ' ';
1145 function snippetFor(line, indent) {
1146 var file_name = fileNameFor(line);
1147 var line_number = line.hasClass('remove') ? '-' + fromLineNumber(line[0]) : toLineNumber(line[0]);
1148 return indent + file_name + ':' + line_number + '\n' + contextSnippetFor(line, indent);
1151 function quotePreviousComments(comments) {
1152 var quoted_comments = [];
1153 var depth = comments.size();
1154 comments.each(function() {
1155 var indent = indentFor(depth--);
1156 var text = $(this).children('.content').text();
1157 quoted_comments.push(indent + '\n' + indent + text.split('\n').join('\n' + indent));
1159 return quoted_comments.join('\n');
1162 $('#comment_form .winter').live('click', function() {
1163 $('#comment_form').addClass('inactive');
1166 function fillInReviewForm() {
1167 var comments_in_context = []
1168 forEachLine(function(line) {
1169 if (line.attr('data-has-comment') != 'true')
1171 var comment = findCommentBlockFor(line).children('textarea').val().trim();
1174 var previous_comments = previousCommentsFor(line);
1175 var snippet = snippetFor(line, indentFor(previous_comments.size() + 1));
1176 var quoted_comments = quotePreviousComments(previous_comments);
1177 var comment_with_context = [];
1178 comment_with_context.push(snippet);
1179 if (quoted_comments != '')
1180 comment_with_context.push(quoted_comments);
1181 comment_with_context.push('\n' + comment);
1182 comments_in_context.push(comment_with_context.join('\n'));
1184 var comment = $('.overallComments textarea').val().trim();
1187 comment += comments_in_context.join('\n\n');
1188 if (comments_in_context.length > 0)
1189 comment = 'View in context: ' + window.location + '\n\n' + comment;
1190 var review_form = $('#reviewform').contents();
1191 review_form.find('#comment').val(comment);
1192 review_form.find('#flags select').each(function() {
1193 var control = findControlForFlag(this);
1194 if (!control.size())
1196 $(this).attr('selectedIndex', control.attr('selectedIndex'));
1200 $('#preview_comments').live('click', function() {
1202 $('#comment_form').removeClass('inactive');
1205 $('#post_comments').live('click', function() {
1207 $('#reviewform').contents().find('form').submit();